Among the various members of the "line family
Among the various members of the "line family," which two have to be named
inonecertain order to be labeled correctly. Question 8 options: a)
ray and line segment b)
line and plane c)
ray and line d)
line and line segment
Source: http://www.transtutors.com/questions/math-328321.htm
Monday, 30 September 2013
How to solve a recursive equation
How to solve a recursive equation
I have been given a task to solve the following recursive equation
\begin{align*} a_1&=-2\\ a_2&= 12\\ a_n&= -4a_n{}_-{}_1-4a_n{}_-{}_2,
\quad n \geq 3. \end{align*}
Should I start by rewriting $a_n$ or is there some kind of approach to
solve these?
I tried rewriting it to a Quadratic Equation (English isn't my native
language, sorry if this is incorrect). Is this the right approach, if so
how do I continue?
\begin{align*} a_n&= -4a_n{}_-{}_1-4a_n{}_-{}_2\\ x^2&= -4x-4\\ 0&= x^2 +
4x + 4 \end{align*}
I have been given a task to solve the following recursive equation
\begin{align*} a_1&=-2\\ a_2&= 12\\ a_n&= -4a_n{}_-{}_1-4a_n{}_-{}_2,
\quad n \geq 3. \end{align*}
Should I start by rewriting $a_n$ or is there some kind of approach to
solve these?
I tried rewriting it to a Quadratic Equation (English isn't my native
language, sorry if this is incorrect). Is this the right approach, if so
how do I continue?
\begin{align*} a_n&= -4a_n{}_-{}_1-4a_n{}_-{}_2\\ x^2&= -4x-4\\ 0&= x^2 +
4x + 4 \end{align*}
When printing, load print.css only and not styles.css
When printing, load print.css only and not styles.css
Is there a way to use only print.css and not styles.css when printing? I
feel like 90% of my print.css is undoing the styles in styles.css.
Is there a way to use only print.css and not styles.css when printing? I
feel like 90% of my print.css is undoing the styles in styles.css.
Ninject dependency binding from xml
Ninject dependency binding from xml
Ninject kernel binding is like this as you know.
kernel.Bind<IMyService>().To<MyService>();
I want to get MyService from xml. WebConfig or App.Config like this.
<add key="service" value="MyNamespace.MyService">
I can get this string in code. But How can I use it
kernel.Bind<IMyService>().To<???>();
Or can Niniject support this as default?
Ninject kernel binding is like this as you know.
kernel.Bind<IMyService>().To<MyService>();
I want to get MyService from xml. WebConfig or App.Config like this.
<add key="service" value="MyNamespace.MyService">
I can get this string in code. But How can I use it
kernel.Bind<IMyService>().To<???>();
Or can Niniject support this as default?
Sunday, 29 September 2013
With Azure auto-scaling do I need to specify a MachineKey in web.config?
With Azure auto-scaling do I need to specify a MachineKey in web.config?
For a ASP.NET MVC project I worked on recently it was deployed to multiple
server instances and required to have a machinekey configured.
I have another project which will be deployed onto Azure (Web site
standard) and I'm not sure if Azure configures a machinekey for you or
handles that kind of thing internally itself or if you have to configure
one.
Does anyone know. I can't seem to find any resources specifically about this.
For a ASP.NET MVC project I worked on recently it was deployed to multiple
server instances and required to have a machinekey configured.
I have another project which will be deployed onto Azure (Web site
standard) and I'm not sure if Azure configures a machinekey for you or
handles that kind of thing internally itself or if you have to configure
one.
Does anyone know. I can't seem to find any resources specifically about this.
How can i remove XML attribute with specific content with Regex?
How can i remove XML attribute with specific content with Regex?
I have huge amount XML files and I need to remove attributes with specific
content.
<Image Width="214.57"
Height="165"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Source="{DynamicResourceExtension
ResourceKey=images_4bd6348715-testImage.jpg}"
Canvas.Left="8"
Canvas.Top="24" />
First case:
Operator can enter images_4bd6348715-testImage.jpg and attribute Source
should be removed.
Attribute can have any name.
Second case:
Text can be inside node. Node can have any name:
<Image Width="214.57"
Height="165"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Canvas.Left="8"
Canvas.Top="24" >
<Image.Source2>
<DynamicResource>
<DynamicResource.ResourceKey>
images_4bd6348715-testImage.jpg
</DynamicResource.ResourceKey>
<DynamicResource>
</Image.Source2>
</Image>
In both cases i only know that inside attribe or node i will have
DynamicResource or DynamicResourceExtension
How can i do this with Regex query?
I have huge amount XML files and I need to remove attributes with specific
content.
<Image Width="214.57"
Height="165"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Source="{DynamicResourceExtension
ResourceKey=images_4bd6348715-testImage.jpg}"
Canvas.Left="8"
Canvas.Top="24" />
First case:
Operator can enter images_4bd6348715-testImage.jpg and attribute Source
should be removed.
Attribute can have any name.
Second case:
Text can be inside node. Node can have any name:
<Image Width="214.57"
Height="165"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Canvas.Left="8"
Canvas.Top="24" >
<Image.Source2>
<DynamicResource>
<DynamicResource.ResourceKey>
images_4bd6348715-testImage.jpg
</DynamicResource.ResourceKey>
<DynamicResource>
</Image.Source2>
</Image>
In both cases i only know that inside attribe or node i will have
DynamicResource or DynamicResourceExtension
How can i do this with Regex query?
Infinite loop in haskell
Infinite loop in haskell
So I am writing a program to generate a list of prime numbers in haskell.
I create two functions shown below:
{-
Given a list of prime numbers, this function will
add the next prime number to the list. So, given the
list [2, 3], it will return [2, 3, 5]
-}
nextPrime xs = xs ++ [lastVal + nextCounts]
where
lastVal = (head . reverse) $ xs
isNextPrime y = 0 `elem` ( map ( y `mod`) xs )
nextVals = (map isNextPrime [lastVal, lastVal+1 ..] )
nextCounts = length $ takeWhile (\x -> x) nextVals
allPrimes xs = allPrimes np
where
np = nextPrime xs
Now the function 'nextPrime' is doing what it is supposed to do. However,
when I do a call to allPrimes as shown below:
take 5 $ allPrimes [2,3]
The program goes into an infinite loop. I thought Haskells "lazy" features
were supposed to take care of all this? What am I missing??
So I am writing a program to generate a list of prime numbers in haskell.
I create two functions shown below:
{-
Given a list of prime numbers, this function will
add the next prime number to the list. So, given the
list [2, 3], it will return [2, 3, 5]
-}
nextPrime xs = xs ++ [lastVal + nextCounts]
where
lastVal = (head . reverse) $ xs
isNextPrime y = 0 `elem` ( map ( y `mod`) xs )
nextVals = (map isNextPrime [lastVal, lastVal+1 ..] )
nextCounts = length $ takeWhile (\x -> x) nextVals
allPrimes xs = allPrimes np
where
np = nextPrime xs
Now the function 'nextPrime' is doing what it is supposed to do. However,
when I do a call to allPrimes as shown below:
take 5 $ allPrimes [2,3]
The program goes into an infinite loop. I thought Haskells "lazy" features
were supposed to take care of all this? What am I missing??
Saturday, 28 September 2013
what directory does open() use by default?
what directory does open() use by default?
I'm trying to do this:
for line in open('some.txt'):
and it's saying the file is not found. I have the file in the same
direction as my python program. what's wrong? I thought it checked the
directory to be
I'm trying to do this:
for line in open('some.txt'):
and it's saying the file is not found. I have the file in the same
direction as my python program. what's wrong? I thought it checked the
directory to be
Time Complexity of Simple Algo
Time Complexity of Simple Algo
I'm trying to figure out the running time of the code below.
If add and trimToSize are both O(n), the interior of the block would run
in 2N time, and then since the loop takes N time, the whole program would
run in N*(2N) time?... O(n^2)?
ArrayList a = new ArrayList();
for (int i = 0; i< N; i++){
a.add(i);
a.trimToSize();
}
I'm trying to figure out the running time of the code below.
If add and trimToSize are both O(n), the interior of the block would run
in 2N time, and then since the loop takes N time, the whole program would
run in N*(2N) time?... O(n^2)?
ArrayList a = new ArrayList();
for (int i = 0; i< N; i++){
a.add(i);
a.trimToSize();
}
check the divisibility by 13 of a binary number
check the divisibility by 13 of a binary number
how to check if a binary number is divisible 13 if the user inputs the
digits from the most significant to the least significant?
the number of bits can be very large,so there is no point converting it
into decimal and then checking its divisibility.
i have approached it in the conventional way. nuber of bits range upto
10^5, so it is giving overflow while converting it into decimal.
how to approach this? example:
110010000100100 it is div by 13
111111111111111 it is not divisible by 13
how to check if a binary number is divisible 13 if the user inputs the
digits from the most significant to the least significant?
the number of bits can be very large,so there is no point converting it
into decimal and then checking its divisibility.
i have approached it in the conventional way. nuber of bits range upto
10^5, so it is giving overflow while converting it into decimal.
how to approach this? example:
110010000100100 it is div by 13
111111111111111 it is not divisible by 13
Why my JQuery ajax functions waits indefinitely
Why my JQuery ajax functions waits indefinitely
I have a jQuery ajax function calls to load the data. When I am testing in
Chrome sometimes it doesn't call the request complete function and
sometimes it works. Please let me know what could be the reason.
var request = $.ajax({
url: data_url,
type: 'post',
data: ""
});
request.done(function(result)
{
console.log("Done");
}
The URL and everything are correct because it works sometime when I click
refresh. Is it something that I need to pass some end code when I am
sending the stream from browser?
In server side, I am using PHP echo function to send encoded JSON.
I have a jQuery ajax function calls to load the data. When I am testing in
Chrome sometimes it doesn't call the request complete function and
sometimes it works. Please let me know what could be the reason.
var request = $.ajax({
url: data_url,
type: 'post',
data: ""
});
request.done(function(result)
{
console.log("Done");
}
The URL and everything are correct because it works sometime when I click
refresh. Is it something that I need to pass some end code when I am
sending the stream from browser?
In server side, I am using PHP echo function to send encoded JSON.
Friday, 27 September 2013
How do you save the characters of a file into a string or array
How do you save the characters of a file into a string or array
For example, if I had a file name random.txt, which read:
This is a string. Abc Zxy
How would you save the characters in random.txt to a string or array that
includes all of the characters in the text file?
So far I have (using redirection for file)
include
include
int main () { int c;
do {
c = fgetc(stdin);
putchar(c);
} while (c != EOF);
return 0;
}
For example, if I had a file name random.txt, which read:
This is a string. Abc Zxy
How would you save the characters in random.txt to a string or array that
includes all of the characters in the text file?
So far I have (using redirection for file)
include
include
int main () { int c;
do {
c = fgetc(stdin);
putchar(c);
} while (c != EOF);
return 0;
}
Implement Thread in my class?
Implement Thread in my class?
I would like to know how to implement a thread in this class to make it
safe from the problems of ANR (Application Not Responding)
public class myClass {
private static String LOG_TAG = Root.class.getName();
public boolean isDeviceRooted() throws IOException {
if (checkRootMethod1()){return true;}
if (checkRootMethod2()){return true;}
if (checkRootMethod3()){return true;}
return false;
}
public boolean checkRootMethod1(){
String buildTags = android.os.Build.TAGS;
if (buildTags != null && buildTags.contains("test-keys")) {
return true;
}
return false;
}
public boolean checkRootMethod2(){
try {
File file = new File("/system/app/Superuser.apk");
if (file.exists()) {
return true;
}
else {
return false;
}
} catch (Exception e) {
}
return false;
}
public boolean checkRootMethod3() {
if (new ExecShell().executeCommand(SHELL_CMD.check_su_binary) !=
null){
return true;
}else{
return false;
}
}
}
If for example this code is execute when i press a button, if i press many
times this button, my app have an ANR.
I would like to know how to implement a thread in this class to make it
safe from the problems of ANR (Application Not Responding)
public class myClass {
private static String LOG_TAG = Root.class.getName();
public boolean isDeviceRooted() throws IOException {
if (checkRootMethod1()){return true;}
if (checkRootMethod2()){return true;}
if (checkRootMethod3()){return true;}
return false;
}
public boolean checkRootMethod1(){
String buildTags = android.os.Build.TAGS;
if (buildTags != null && buildTags.contains("test-keys")) {
return true;
}
return false;
}
public boolean checkRootMethod2(){
try {
File file = new File("/system/app/Superuser.apk");
if (file.exists()) {
return true;
}
else {
return false;
}
} catch (Exception e) {
}
return false;
}
public boolean checkRootMethod3() {
if (new ExecShell().executeCommand(SHELL_CMD.check_su_binary) !=
null){
return true;
}else{
return false;
}
}
}
If for example this code is execute when i press a button, if i press many
times this button, my app have an ANR.
Why would Flash embeds show up as "Missing Plug-In" in a Cocoa WebView?
Why would Flash embeds show up as "Missing Plug-In" in a Cocoa WebView?
Building a very straightforward Cocoa app using Xcode 5. The main window
is simply a WebView with plugins enabled that attempts to load a page from
the Internet with a Flash embed on it.
Sandboxing is disabled and I've double- and triple-checked that plugins
are enabled on the webview (both in the nib and programatically.) I've
also tried running the app in both 32- and 64-bit modes.
Even navigating the WebView to the Adobe Flash website shows a missing
plug-in box. What could cause the WebView object to not have Flash
available?
Building a very straightforward Cocoa app using Xcode 5. The main window
is simply a WebView with plugins enabled that attempts to load a page from
the Internet with a Flash embed on it.
Sandboxing is disabled and I've double- and triple-checked that plugins
are enabled on the webview (both in the nib and programatically.) I've
also tried running the app in both 32- and 64-bit modes.
Even navigating the WebView to the Adobe Flash website shows a missing
plug-in box. What could cause the WebView object to not have Flash
available?
Illegal Start of Expression Java Boolean?
Illegal Start of Expression Java Boolean?
I'm trying to run a Bitwise number comparison and my code keeps coming up
with an Illegal start of expression on line 30 of my code with the "if"
statement.
My code reads as so:
public class Project7 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double P = keyboard.nextDouble();
double Q = keyboard.nextDouble();
double R = keyboard.nextDouble();
double S = keyboard.nextDouble();
boolean First_Relation;
boolean Second_Relation;
if (P>Q) First_Relation = true;
if (R<S) Second_Relation = true;
if
(First_Relation = true) & (Second_Relation = true);
System.out.println("Given the values for p,q,r, and s the expression "
+ "(p > q) && !(r < s) evaluates to " );
}
I'm trying to run a Bitwise number comparison and my code keeps coming up
with an Illegal start of expression on line 30 of my code with the "if"
statement.
My code reads as so:
public class Project7 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double P = keyboard.nextDouble();
double Q = keyboard.nextDouble();
double R = keyboard.nextDouble();
double S = keyboard.nextDouble();
boolean First_Relation;
boolean Second_Relation;
if (P>Q) First_Relation = true;
if (R<S) Second_Relation = true;
if
(First_Relation = true) & (Second_Relation = true);
System.out.println("Given the values for p,q,r, and s the expression "
+ "(p > q) && !(r < s) evaluates to " );
}
PRFilledPolygon - Opacity/Color with Cocos2d in Objective-C
PRFilledPolygon - Opacity/Color with Cocos2d in Objective-C
i have a question about PRFilledPolygon from PrKit which you can found
here:
https://github.com/Panajev/PRKit/blob/master-v2/PRKit/PRFilledPolygon.m
My concern is to runAction with CCFadeout or CCFadein with this class.
This class inherits from CCNode which have no methods like setColor or
setOpacity. But to run this actions which i named above require a methode
setOpacity to make the texture transparent.
So my first step was to in change "CCNode" to "CCNodeRGBA". I have no idea
what my next step is. I have read out in other forums and found this
article:
http://www.cocos2d-iphone.org/forums/topic/prfilledpolygon-opacitycolor/
But this doesn't work.
second found article here:
http://insights.empatika.com/blog/2013/04/06/hackathon-ios-game-in-7-days/
So i play a bit in the draw method but my texture won't be transparent.
Has anybody used PRFilledPolygon and has the same problem like me?
Hope anyone understand me.
Greetings Alex
i have a question about PRFilledPolygon from PrKit which you can found
here:
https://github.com/Panajev/PRKit/blob/master-v2/PRKit/PRFilledPolygon.m
My concern is to runAction with CCFadeout or CCFadein with this class.
This class inherits from CCNode which have no methods like setColor or
setOpacity. But to run this actions which i named above require a methode
setOpacity to make the texture transparent.
So my first step was to in change "CCNode" to "CCNodeRGBA". I have no idea
what my next step is. I have read out in other forums and found this
article:
http://www.cocos2d-iphone.org/forums/topic/prfilledpolygon-opacitycolor/
But this doesn't work.
second found article here:
http://insights.empatika.com/blog/2013/04/06/hackathon-ios-game-in-7-days/
So i play a bit in the draw method but my texture won't be transparent.
Has anybody used PRFilledPolygon and has the same problem like me?
Hope anyone understand me.
Greetings Alex
How to check if an incoming email is duplicate in Inbox using javamail IMAP
How to check if an incoming email is duplicate in Inbox using javamail IMAP
Now I would like to check if an incoming email is duplicate via IMAP using
javamail, which may mean one email equals others that they have the same
Subject,From,To,CC,BCC,Body,Attachements.But I donnot find any APIs to
support this.
So can anybody tell me how to do this. any ideas are much appreciated.Thanks
Now I would like to check if an incoming email is duplicate via IMAP using
javamail, which may mean one email equals others that they have the same
Subject,From,To,CC,BCC,Body,Attachements.But I donnot find any APIs to
support this.
So can anybody tell me how to do this. any ideas are much appreciated.Thanks
Thursday, 26 September 2013
can i wrap OpenCV's c++ interface with c and then wrap that with Lisp's CFFI?
can i wrap OpenCV's c++ interface with c and then wrap that with Lisp's CFFI?
I was also wondering about the possibility of wrapping c++ interface in c
and then wrapping that in lisp so i could add all the c++ functionality as
well to my cl-opencv wrapper because i would like to make it complete....
also wondered if i do that, can i use the c++ wrapper with the c wrapper
in lisp ....if it is possible if you could show me a quick example
program, like an open window and show a picture function, only in c and
c++ together ....like using cv::namedWindow instead of cvNamedWindow and
all the other parts being c .....here is my attempt the program below runs
when i use cv::namedWindow only but fails with
shape.cpp:37:32: error: invalid initialization of
reference of type 'cv::InputArray {aka const cv::_InputArray&}'
from expression of type 'IplImage* {aka _IplImage*}'In file included from
/usr/local/include/opencv/highgui.h:48:0,
from shape.cpp:4:
/usr/local/include/opencv2/highgui/highgui.hpp:78:19: error:
in passing argument 2 of 'void cv::imshow(const string&, cv::InputArray)'
Compilation exited abnormally with code 1 at Thu Sep 26 21:18:00
when i add cv::imshow
#include <cv.h>
#include <highgui.h>
using namespace std;
int main(){
CvCapture* capture =0;
capture = cvCaptureFromCAM(0);
if(!capture){
printf("Capture failure\n");
return -1;
}
IplImage* frame=0;
cv::namedWindow("Video");
// cout << "colorModel = " << endl << " " << size << endl << endl;
while(true){
frame = cvQueryFrame(capture);
if(!frame) break;
frame=cvCloneImage(frame);
cv::imshow("Video", frame );
cvReleaseImage(&frame);
//Wait 50mS
int c = cvWaitKey(10);
//If 'ESC' is pressed, break the loop
if((char)c==27 ) break;
}
cvDestroyAllWindows() ;
cvReleaseCapture(&capture);
return 0;
}
I'd like to know if it would be doable...like be 100% sure before i start,
that i could at least wrap every c++ function in c and wrap that with
lisp..or if u think id run into snags in some places or even
impossibilities.....and also would wrapping it twice make it slow? and id
the c interface better/worse than the c++..or can i accomlish everything
in the c interface that i can in c++
I was also wondering about the possibility of wrapping c++ interface in c
and then wrapping that in lisp so i could add all the c++ functionality as
well to my cl-opencv wrapper because i would like to make it complete....
also wondered if i do that, can i use the c++ wrapper with the c wrapper
in lisp ....if it is possible if you could show me a quick example
program, like an open window and show a picture function, only in c and
c++ together ....like using cv::namedWindow instead of cvNamedWindow and
all the other parts being c .....here is my attempt the program below runs
when i use cv::namedWindow only but fails with
shape.cpp:37:32: error: invalid initialization of
reference of type 'cv::InputArray {aka const cv::_InputArray&}'
from expression of type 'IplImage* {aka _IplImage*}'In file included from
/usr/local/include/opencv/highgui.h:48:0,
from shape.cpp:4:
/usr/local/include/opencv2/highgui/highgui.hpp:78:19: error:
in passing argument 2 of 'void cv::imshow(const string&, cv::InputArray)'
Compilation exited abnormally with code 1 at Thu Sep 26 21:18:00
when i add cv::imshow
#include <cv.h>
#include <highgui.h>
using namespace std;
int main(){
CvCapture* capture =0;
capture = cvCaptureFromCAM(0);
if(!capture){
printf("Capture failure\n");
return -1;
}
IplImage* frame=0;
cv::namedWindow("Video");
// cout << "colorModel = " << endl << " " << size << endl << endl;
while(true){
frame = cvQueryFrame(capture);
if(!frame) break;
frame=cvCloneImage(frame);
cv::imshow("Video", frame );
cvReleaseImage(&frame);
//Wait 50mS
int c = cvWaitKey(10);
//If 'ESC' is pressed, break the loop
if((char)c==27 ) break;
}
cvDestroyAllWindows() ;
cvReleaseCapture(&capture);
return 0;
}
I'd like to know if it would be doable...like be 100% sure before i start,
that i could at least wrap every c++ function in c and wrap that with
lisp..or if u think id run into snags in some places or even
impossibilities.....and also would wrapping it twice make it slow? and id
the c interface better/worse than the c++..or can i accomlish everything
in the c interface that i can in c++
Wednesday, 25 September 2013
Mashable like mega menu design
Mashable like mega menu design
I need to make a mega menu/mashable like menu similar to one as show in
image below
So far i have been able to make it work to some extent example on jsFiddle
HERE.
this has some design issue and one functionality issue.
When i try to hide the default text for each dropdown menu
//$(this).find(".nav-info").hide(); then Menu 4 & 5 doesn't show up on
right side.
I am actually trying to create a menu similar to one as on this website.
One this website they also show a default text for parent menu which i
don't need actually.
I modified script to show the first li of sub-menu it works find for
Parent menu ONE, TWO but creates alignment problem for MENU FOUR and FIVE.
I would appreciate if some can help me fix this issue...
CODE
<div class="container_16">
<div class="nav-main grid_16">
<div class="wrap-nav-media">
<ul id="nav-top-media">
<!-- ONE -->
<li class="nav-item-1"><a href="..company-overview">Parent
Menu One</a>
<div style="display: none;" class="inner-nav-media">
<ul>
<li class=""><a class="current"
href="../directors"
rel="sub-1-relative-1">sub-1-relative-1</a>
</li>
<li class=""><a class="current"
href="../management-team"
rel="sub-1-relative-2">sub-1-relative-2</a>
</li>
<li class="last"><a class="current"
href="../tems.html"
rel="sub-1-relative-3">sub-1-relative-3</a>
</li>
</ul>
<div style="display: block;" class="menu-page
first" id="mega-sub-1-relative-1"> <a
href="../board-of-directors" title="Board of
Directors" rel="nofollow" class="thumb">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-1-relative-1</p>
</div>
</div>
<div style="display: block;" class="menu-page"
id="mega-sub-1-relative-2"> <a
href="../management-team" title="Management Team"
rel="nofollow" class="thumb">
<div style="height:80px
width:80px;
background-color:yellow;
float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-1-relative-2</p>
</div>
</div>
<div style="display: none;" class="menu-page"
id="mega-sub-1-relative-3"> <a
href="../vision.html" title="Vision"
rel="nofollow" class="thumb">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-1-relative-3</p>
</div>
</div>
</div>
</li>
<!-- TWO -->
<li class="nav-item-2"> <a href="..capabilities">Parent
Menu TWO</a>
<div style="display: none;" class="inner-nav-media">
<ul>
<li class=""><a class="current"
href="../infrastructure"
rel="sub-2-relative-1">sub-2-relative-1</a>
</li>
<li class=""><a class="current"
href="..capabilities/building"
rel="sub-2-relative-2">sub-2-relative-2</a>
</li>
<li class="last"><a class="current"
href="..capabilities/rail"
rel="sub-2-relative-3">sub-2-relative-3</a>
</li>
</ul>
<div style="display: none;" class="menu-page
first" id="mega-sub-2-relative-1"> <a
href="../infrastructure" title="Infrastructure"
rel="nofollow" class="thumb">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-2-relative-1</p>
</div>
</div>
<div style="display: none;" class="menu-page"
id="mega-sub-2-relative-2"> <a
href="../building" title="Building" rel="nofollow"
class="thumb">
<div style="height:80px width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-2-relative-2</p>
</div>
</div>
<div style="display: none;" class="menu-page"
id="mega-sub-2-relative-3"> <a href="/rail"
title="Rail" rel="nofollow" class="thumb">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-2-relative-3</p>
</div>
</div>
</div>
</li>
<li class="nav-item-3"><a href="../projects">THREE</a>
</li>
<li class="nav-item-4"> <a href="../-businesses">FOUR</a>
<div style="display: none;" class="inner-nav-media">
<div style="display: block; float:right;"
class="menu-page nav-info"> <a class="thumb"
rel="nofollow" title=" Businesses"
href="../businesses">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>TEXT will be here...</p>
</div>
</div>
<ul>
<li class=""> <a class="current"
href="2.html"
rel="sub-4-relative-1">sub-4-relative-1</a>
</li>
<li class=""> <a class="current"
href="1.html"
rel="sub-4-relative-2">sub-4-relative-2</a>
</li>
</ul>
<div style="display: none;" class="menu-page
first" id="mega-sub-4-relative-1"> <a
href="../group.html" title="" rel="nofollow"
class="thumb">
<img
src="HLG-Mega-Menu_files/20110602_1-ARG.jpg"
alt="">
</a>
<div>
<p>TEXT will be here...</p>
</div>
</div>
<div style="display: none;" class="menu-page"
id="mega-sub-4-relative-2"> <a
href="../advance-water-and-environmentawe.html"
title="Advance Water and Environment (AWE)"
rel="nofollow" class="thumb">
<img
src="HLG-Mega-Menu_files/20121024_AWG-220x165.jpg"
alt="Advance Water and Environment
(AWE)">
</a>
<div>
<p>TEXT will be here...</p>
</div>
</div>
</div>
</li>
<li class="last nav-item-5"><a
href="../sustainability">FIVE</a>
<div style="display: none;" class="inner-nav-media">
<div style="display: block;" class="menu-page
nav-info"> <a class="thumb" rel="nofollow"
title="" href="">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>This is Default text when i try to hide
this then this menu moves to left</p>
</div>
</div>
<ul>
<li class=""><a class="current" href=""
rel="sub-5-relative-1">sub-5-relative-1</a>
</li>
<li class=""><a class="current" href=""
rel="sub-5-relative-2">sub-5-relative-2</a>
</li>
<li class=""><a class="current" href=""
rel="sub-5-relative-3">sub-5-relative-3</a>
</li>
<li class="last"><a class="current" href=""
rel="sub-5-relative-4">sub-5-relative-4</a>
</li>
</ul>
<div style="display: none;" class="menu-page
first" id="mega-sub-5-relative-1"> <a
href="/safety.html" title="" rel="nofollow"
class="thumb">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-5-relative-3</p>
</div>
</div>
<div style="display: none;" class="menu-page"
id="mega-sub-5-relative-2"> <a
href="/environment.html" title="Environment"
rel="nofollow" class="thumb">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-5-relative-2</p>
</div>
</div>
<div style="display: none;" class="menu-page"
id="mega-sub-5-relative-3"> <a
href="/community.html" title="Community"
rel="nofollow" class="thumb">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-5-relative-3</p>
</div>
</div>
<div style="display: none;" class="menu-page"
id="mega-sub-5-relative-4"> <a
href="/quality.html" title="Quality"
rel="nofollow" class="thumb">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-5-relative-4</p>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
I need to make a mega menu/mashable like menu similar to one as show in
image below
So far i have been able to make it work to some extent example on jsFiddle
HERE.
this has some design issue and one functionality issue.
When i try to hide the default text for each dropdown menu
//$(this).find(".nav-info").hide(); then Menu 4 & 5 doesn't show up on
right side.
I am actually trying to create a menu similar to one as on this website.
One this website they also show a default text for parent menu which i
don't need actually.
I modified script to show the first li of sub-menu it works find for
Parent menu ONE, TWO but creates alignment problem for MENU FOUR and FIVE.
I would appreciate if some can help me fix this issue...
CODE
<div class="container_16">
<div class="nav-main grid_16">
<div class="wrap-nav-media">
<ul id="nav-top-media">
<!-- ONE -->
<li class="nav-item-1"><a href="..company-overview">Parent
Menu One</a>
<div style="display: none;" class="inner-nav-media">
<ul>
<li class=""><a class="current"
href="../directors"
rel="sub-1-relative-1">sub-1-relative-1</a>
</li>
<li class=""><a class="current"
href="../management-team"
rel="sub-1-relative-2">sub-1-relative-2</a>
</li>
<li class="last"><a class="current"
href="../tems.html"
rel="sub-1-relative-3">sub-1-relative-3</a>
</li>
</ul>
<div style="display: block;" class="menu-page
first" id="mega-sub-1-relative-1"> <a
href="../board-of-directors" title="Board of
Directors" rel="nofollow" class="thumb">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-1-relative-1</p>
</div>
</div>
<div style="display: block;" class="menu-page"
id="mega-sub-1-relative-2"> <a
href="../management-team" title="Management Team"
rel="nofollow" class="thumb">
<div style="height:80px
width:80px;
background-color:yellow;
float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-1-relative-2</p>
</div>
</div>
<div style="display: none;" class="menu-page"
id="mega-sub-1-relative-3"> <a
href="../vision.html" title="Vision"
rel="nofollow" class="thumb">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-1-relative-3</p>
</div>
</div>
</div>
</li>
<!-- TWO -->
<li class="nav-item-2"> <a href="..capabilities">Parent
Menu TWO</a>
<div style="display: none;" class="inner-nav-media">
<ul>
<li class=""><a class="current"
href="../infrastructure"
rel="sub-2-relative-1">sub-2-relative-1</a>
</li>
<li class=""><a class="current"
href="..capabilities/building"
rel="sub-2-relative-2">sub-2-relative-2</a>
</li>
<li class="last"><a class="current"
href="..capabilities/rail"
rel="sub-2-relative-3">sub-2-relative-3</a>
</li>
</ul>
<div style="display: none;" class="menu-page
first" id="mega-sub-2-relative-1"> <a
href="../infrastructure" title="Infrastructure"
rel="nofollow" class="thumb">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-2-relative-1</p>
</div>
</div>
<div style="display: none;" class="menu-page"
id="mega-sub-2-relative-2"> <a
href="../building" title="Building" rel="nofollow"
class="thumb">
<div style="height:80px width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-2-relative-2</p>
</div>
</div>
<div style="display: none;" class="menu-page"
id="mega-sub-2-relative-3"> <a href="/rail"
title="Rail" rel="nofollow" class="thumb">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-2-relative-3</p>
</div>
</div>
</div>
</li>
<li class="nav-item-3"><a href="../projects">THREE</a>
</li>
<li class="nav-item-4"> <a href="../-businesses">FOUR</a>
<div style="display: none;" class="inner-nav-media">
<div style="display: block; float:right;"
class="menu-page nav-info"> <a class="thumb"
rel="nofollow" title=" Businesses"
href="../businesses">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>TEXT will be here...</p>
</div>
</div>
<ul>
<li class=""> <a class="current"
href="2.html"
rel="sub-4-relative-1">sub-4-relative-1</a>
</li>
<li class=""> <a class="current"
href="1.html"
rel="sub-4-relative-2">sub-4-relative-2</a>
</li>
</ul>
<div style="display: none;" class="menu-page
first" id="mega-sub-4-relative-1"> <a
href="../group.html" title="" rel="nofollow"
class="thumb">
<img
src="HLG-Mega-Menu_files/20110602_1-ARG.jpg"
alt="">
</a>
<div>
<p>TEXT will be here...</p>
</div>
</div>
<div style="display: none;" class="menu-page"
id="mega-sub-4-relative-2"> <a
href="../advance-water-and-environmentawe.html"
title="Advance Water and Environment (AWE)"
rel="nofollow" class="thumb">
<img
src="HLG-Mega-Menu_files/20121024_AWG-220x165.jpg"
alt="Advance Water and Environment
(AWE)">
</a>
<div>
<p>TEXT will be here...</p>
</div>
</div>
</div>
</li>
<li class="last nav-item-5"><a
href="../sustainability">FIVE</a>
<div style="display: none;" class="inner-nav-media">
<div style="display: block;" class="menu-page
nav-info"> <a class="thumb" rel="nofollow"
title="" href="">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>This is Default text when i try to hide
this then this menu moves to left</p>
</div>
</div>
<ul>
<li class=""><a class="current" href=""
rel="sub-5-relative-1">sub-5-relative-1</a>
</li>
<li class=""><a class="current" href=""
rel="sub-5-relative-2">sub-5-relative-2</a>
</li>
<li class=""><a class="current" href=""
rel="sub-5-relative-3">sub-5-relative-3</a>
</li>
<li class="last"><a class="current" href=""
rel="sub-5-relative-4">sub-5-relative-4</a>
</li>
</ul>
<div style="display: none;" class="menu-page
first" id="mega-sub-5-relative-1"> <a
href="/safety.html" title="" rel="nofollow"
class="thumb">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-5-relative-3</p>
</div>
</div>
<div style="display: none;" class="menu-page"
id="mega-sub-5-relative-2"> <a
href="/environment.html" title="Environment"
rel="nofollow" class="thumb">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-5-relative-2</p>
</div>
</div>
<div style="display: none;" class="menu-page"
id="mega-sub-5-relative-3"> <a
href="/community.html" title="Community"
rel="nofollow" class="thumb">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-5-relative-3</p>
</div>
</div>
<div style="display: none;" class="menu-page"
id="mega-sub-5-relative-4"> <a
href="/quality.html" title="Quality"
rel="nofollow" class="thumb">
<div style="height:80px
width:80px;
background-color:yellow;float:right;">IMAGE</div>
</a>
<div>
<p>Brief Contents will show up here
sub-5-relative-4</p>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
Thursday, 19 September 2013
Can IPython cell magics get access to a unique cell identifier?
Can IPython cell magics get access to a unique cell identifier?
I'm trying to implement magics to support a programming language where
entire modules must be compiled at once. My goal is that all cells in a
notebook with a particular cell magic will be coalesced into a single
module M.
To make this work, when a cell C changes I need to remove the old contents
of C from M and replace them with the new contents of C. However when the
cell magic is called for C, there is no way to tell that it is C and not
any other old or new cell. What I need is an identifier that is constant
between calls to the cell magic.
Is this kind of cell identifier available anywhere in the IPython API?
I'm trying to implement magics to support a programming language where
entire modules must be compiled at once. My goal is that all cells in a
notebook with a particular cell magic will be coalesced into a single
module M.
To make this work, when a cell C changes I need to remove the old contents
of C from M and replace them with the new contents of C. However when the
cell magic is called for C, there is no way to tell that it is C and not
any other old or new cell. What I need is an identifier that is constant
between calls to the cell magic.
Is this kind of cell identifier available anywhere in the IPython API?
How come a globally defined array that gets data pushed to it with in a callback function is empty in the global scope?
How come a globally defined array that gets data pushed to it with in a
callback function is empty in the global scope?
I assign an empty array to the global variable artistURLs. I then push
strings (the local variable artistURL) into the artistURLs array with in
the Cheerio .each() iterator method.
var request = require('request'),
cheerio = require('cheerio'),
url = 'http://www.primarytalent.com/',
artistURLs = [];
request(url, function(err, resp, body){
if(err)
throw err;
$ = cheerio.load(body);
$('#rosterlists div li a').each(function(){
var urlCap = this.attr('href').slice(1);
var artistURL = url.concat(urlCap);
artistURLs.push(artistURL);
});
console.log(artistURLs);
});
I know that artistURL is successfully being pushed into artistURLs because
console.log(artistURLs);
will display the populated array in my terminal. The problem is if I try
running console.log(artistURLs); outside of the callback function in the
global scope. For example
var request = require('request'),
cheerio = require('cheerio'),
url = 'http://www.primarytalent.com/',
artistURLs = [];
request(url, function(err, resp, body){
if(err)
throw err;
$ = cheerio.load(body);
$('#rosterlists div li a').each(function(){
var urlCap = this.attr('href').slice(1);
var artistURL = url.concat(urlCap);
artistURLs.push(artistURL);
});
});
console.log(artistURLs);
So you can see that I have moved console.log(artistURLs); outside of
request(). For some reason trying to access artistURLs in the global scope
returns me an empty array as if all the processing that happened with in
`request()~ never even happened.
How come this is happening and how can ensure that all the urls that are
being pushed into artistURLs remain in artistURLs?
Thanks
callback function is empty in the global scope?
I assign an empty array to the global variable artistURLs. I then push
strings (the local variable artistURL) into the artistURLs array with in
the Cheerio .each() iterator method.
var request = require('request'),
cheerio = require('cheerio'),
url = 'http://www.primarytalent.com/',
artistURLs = [];
request(url, function(err, resp, body){
if(err)
throw err;
$ = cheerio.load(body);
$('#rosterlists div li a').each(function(){
var urlCap = this.attr('href').slice(1);
var artistURL = url.concat(urlCap);
artistURLs.push(artistURL);
});
console.log(artistURLs);
});
I know that artistURL is successfully being pushed into artistURLs because
console.log(artistURLs);
will display the populated array in my terminal. The problem is if I try
running console.log(artistURLs); outside of the callback function in the
global scope. For example
var request = require('request'),
cheerio = require('cheerio'),
url = 'http://www.primarytalent.com/',
artistURLs = [];
request(url, function(err, resp, body){
if(err)
throw err;
$ = cheerio.load(body);
$('#rosterlists div li a').each(function(){
var urlCap = this.attr('href').slice(1);
var artistURL = url.concat(urlCap);
artistURLs.push(artistURL);
});
});
console.log(artistURLs);
So you can see that I have moved console.log(artistURLs); outside of
request(). For some reason trying to access artistURLs in the global scope
returns me an empty array as if all the processing that happened with in
`request()~ never even happened.
How come this is happening and how can ensure that all the urls that are
being pushed into artistURLs remain in artistURLs?
Thanks
Force Close After Implementation of Splash Screen w AsyncTask
Force Close After Implementation of Splash Screen w AsyncTask
I'm getting a force close issue after attempting to implement a splash
screen into my app.
The issue occurs on line 76 lv.setAdapter(adapter); however I'm unsure as
to why.
Any input is greatly appreciated.
09-19 15:20:53.687: E/AndroidRuntime(25177): FATAL EXCEPTION: main
09-19 15:20:53.687: E/AndroidRuntime(25177): java.lang.NullPointerException
09-19 15:20:53.687: E/AndroidRuntime(25177): at
com.example.project1.MainActivity$MyTask.onPostExecute(MainActivity.java:76)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
com.example.project1.MainActivity$MyTask.onPostExecute(MainActivity.java:1)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
android.os.AsyncTask.finish(AsyncTask.java:631)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
android.os.AsyncTask.access$600(AsyncTask.java:177)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
android.os.Handler.dispatchMessage(Handler.java:99)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
android.os.Looper.loop(Looper.java:137)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
android.app.ActivityThread.main(ActivityThread.java:4931)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
java.lang.reflect.Method.invokeNative(Native Method)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
java.lang.reflect.Method.invoke(Method.java:511)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
dalvik.system.NativeStart.main(Native Method)
SOURCE:
public class MainActivity extends Activity {
Context context;
ArrayList<String> aa = new ArrayList<String>();
ListView lv;
final String URL = "http://news.google.com";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
setContentView(R.layout.splash);
lv= (ListView) findViewById(R.id.listView1);
new MyTask().execute(URL);
}
private class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog prog;
String title = "";
@Override
protected void onPreExecute() {
prog = new ProgressDialog(MainActivity.this);
prog.setMessage("Loading....");
prog.show();
}
@Override
protected String doInBackground(String... params) {
try {
Document doc = Jsoup.connect(params[0]).get();
Element tableHeader = doc.select("tr").first();
for (Element element : tableHeader.children()) {
aa.add(element.text().toString());
}
title = doc.title();
} catch (IOException e) {
e.printStackTrace();
}
return title;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prog.dismiss();
ArrayAdapter<String> adapter = new
ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,aa);
lv.setAdapter(adapter);
}
}
}
I'm getting a force close issue after attempting to implement a splash
screen into my app.
The issue occurs on line 76 lv.setAdapter(adapter); however I'm unsure as
to why.
Any input is greatly appreciated.
09-19 15:20:53.687: E/AndroidRuntime(25177): FATAL EXCEPTION: main
09-19 15:20:53.687: E/AndroidRuntime(25177): java.lang.NullPointerException
09-19 15:20:53.687: E/AndroidRuntime(25177): at
com.example.project1.MainActivity$MyTask.onPostExecute(MainActivity.java:76)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
com.example.project1.MainActivity$MyTask.onPostExecute(MainActivity.java:1)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
android.os.AsyncTask.finish(AsyncTask.java:631)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
android.os.AsyncTask.access$600(AsyncTask.java:177)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
android.os.Handler.dispatchMessage(Handler.java:99)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
android.os.Looper.loop(Looper.java:137)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
android.app.ActivityThread.main(ActivityThread.java:4931)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
java.lang.reflect.Method.invokeNative(Native Method)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
java.lang.reflect.Method.invoke(Method.java:511)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
09-19 15:20:53.687: E/AndroidRuntime(25177): at
dalvik.system.NativeStart.main(Native Method)
SOURCE:
public class MainActivity extends Activity {
Context context;
ArrayList<String> aa = new ArrayList<String>();
ListView lv;
final String URL = "http://news.google.com";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
setContentView(R.layout.splash);
lv= (ListView) findViewById(R.id.listView1);
new MyTask().execute(URL);
}
private class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog prog;
String title = "";
@Override
protected void onPreExecute() {
prog = new ProgressDialog(MainActivity.this);
prog.setMessage("Loading....");
prog.show();
}
@Override
protected String doInBackground(String... params) {
try {
Document doc = Jsoup.connect(params[0]).get();
Element tableHeader = doc.select("tr").first();
for (Element element : tableHeader.children()) {
aa.add(element.text().toString());
}
title = doc.title();
} catch (IOException e) {
e.printStackTrace();
}
return title;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prog.dismiss();
ArrayAdapter<String> adapter = new
ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,aa);
lv.setAdapter(adapter);
}
}
}
Doing something is faster than doing nothing in Matlab loop
Doing something is faster than doing nothing in Matlab loop
In the process of analyzing how fast a trivial loop could be, I
encountered this strange phenomenon.
Doing nothing with a variable is much slower than doing something with it.
Of course this is not a real problem as you won't often feel the urge to
write code that does nothing, but this surprised me so I wonder if anyone
understands what is happening and whether this could be a problem in real
situations.
Here is what I found:
for t= 1:1e6, y=x; end %This runs fast, about 0.1 sec
for t= 1:1e6, x; end %This takes over half a second
I tried adding a trivial calculation in the loop to ensure the loop would
not be optimized away but this did not change results.
To summarize, my question is:
What is happening and should I ever worry about it?
In the process of analyzing how fast a trivial loop could be, I
encountered this strange phenomenon.
Doing nothing with a variable is much slower than doing something with it.
Of course this is not a real problem as you won't often feel the urge to
write code that does nothing, but this surprised me so I wonder if anyone
understands what is happening and whether this could be a problem in real
situations.
Here is what I found:
for t= 1:1e6, y=x; end %This runs fast, about 0.1 sec
for t= 1:1e6, x; end %This takes over half a second
I tried adding a trivial calculation in the loop to ensure the loop would
not be optimized away but this did not change results.
To summarize, my question is:
What is happening and should I ever worry about it?
In Chrome 'transform-origin' is invalid?
In Chrome 'transform-origin' is invalid?
My Chrome console returns Invalid CSS property name to a transform-origin
CCS attribute as the site loads even though it works and I have a -webkit-
prefixed version.
The target CSS looks like this:
-webkit-transform-origin: 0% 50%;
-moz-transform-origin: 0% 50%;
transform-origin: 0% 50%;
Is it really an issue?
My Chrome console returns Invalid CSS property name to a transform-origin
CCS attribute as the site loads even though it works and I have a -webkit-
prefixed version.
The target CSS looks like this:
-webkit-transform-origin: 0% 50%;
-moz-transform-origin: 0% 50%;
transform-origin: 0% 50%;
Is it really an issue?
How to use Font Awesome with JSF
How to use Font Awesome with JSF
I am trying to use Font Awesome icons with my JSF application. I have had
some success by following the getting started instructions and adding the
following to my view's <h:head> section:
<link
href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css"
rel="stylesheet" />
This gives me a nice home icon when I use the icon-home class:
However, I don't want to be dependent on the bootstrap server to provide
the Font Awesome resources, so I am trying to bundle these with my war,
and configure my views to use the bundled resources.
I am using the pre-made JAR created by the webjars project. My pom has the
following dependency:
<dependency>
<groupId>org.webjars</groupId>
<artifactId>font-awesome</artifactId>
<version>3.2.1</version>
</dependency>
This places the JAR in my WAR's WEB-INF/lib directory. The relevent parts
of the JAR's structure are:
META-INF
- MANIFEST.MF
+ maven
- resources
- webjars
- font-awesome
- 3.2.1
- css
- font-awesome.css
- *other css files*
- font
- *font files*
I have tried the following to include the icons in my project:
<h:outputStylesheet library="webjars"
name="font-awesome/3.2.1/css/font-awesome.css" />
However, this renders the previously working home icon as:
And my browser (Chrome) shows the following errors in the console
(domain/port/context-root changed to protect the innocent ;):
GET
http://DOMAIN:PORT/CONTEXT-ROOT/javax.faces.resource/font-awesome/3.2.1/font/fontawesome-webfont.woff?v=3.2.1
404 (Not Found)
GET
http://DOMAIN:PORT/CONTEXT-ROOT/javax.faces.resource/font-awesome/3.2.1/font/fontawesome-webfont.ttf?v=3.2.1
404 (Not Found)
GET
http://DOMAIN:PORT/CONTEXT-ROOT/javax.faces.resource/font-awesome/3.2.1/font/fontawesome-webfont.svg
404 (Not Found)
So it looks like although the css file is resolved properly, the files
which contain the fonts that the css file refers to cannot be found. I
have checked those references in the css file and they are:
src: url('../font/fontawesome-webfont.eot?v=3.2.1');
src: url('../font/fontawesome-webfont.eot?#iefix&v=3.2.1')
format('embedded-opentype'),
url('../font/fontawesome-webfont.woff?v=3.2.1') format('woff'),
url('../font/fontawesome-webfont.ttf?v=3.2.1') format('truetype'),
url('../font/fontawesome-webfont.svg#fontawesomeregular?v=3.2.1')
format('svg');
Those paths are relative to the css resource, so I thought JSF should have
no problem finding it. Now I'm not sure what to do.
Any pointers would be great! Cheers.
I am trying to use Font Awesome icons with my JSF application. I have had
some success by following the getting started instructions and adding the
following to my view's <h:head> section:
<link
href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css"
rel="stylesheet" />
This gives me a nice home icon when I use the icon-home class:
However, I don't want to be dependent on the bootstrap server to provide
the Font Awesome resources, so I am trying to bundle these with my war,
and configure my views to use the bundled resources.
I am using the pre-made JAR created by the webjars project. My pom has the
following dependency:
<dependency>
<groupId>org.webjars</groupId>
<artifactId>font-awesome</artifactId>
<version>3.2.1</version>
</dependency>
This places the JAR in my WAR's WEB-INF/lib directory. The relevent parts
of the JAR's structure are:
META-INF
- MANIFEST.MF
+ maven
- resources
- webjars
- font-awesome
- 3.2.1
- css
- font-awesome.css
- *other css files*
- font
- *font files*
I have tried the following to include the icons in my project:
<h:outputStylesheet library="webjars"
name="font-awesome/3.2.1/css/font-awesome.css" />
However, this renders the previously working home icon as:
And my browser (Chrome) shows the following errors in the console
(domain/port/context-root changed to protect the innocent ;):
GET
http://DOMAIN:PORT/CONTEXT-ROOT/javax.faces.resource/font-awesome/3.2.1/font/fontawesome-webfont.woff?v=3.2.1
404 (Not Found)
GET
http://DOMAIN:PORT/CONTEXT-ROOT/javax.faces.resource/font-awesome/3.2.1/font/fontawesome-webfont.ttf?v=3.2.1
404 (Not Found)
GET
http://DOMAIN:PORT/CONTEXT-ROOT/javax.faces.resource/font-awesome/3.2.1/font/fontawesome-webfont.svg
404 (Not Found)
So it looks like although the css file is resolved properly, the files
which contain the fonts that the css file refers to cannot be found. I
have checked those references in the css file and they are:
src: url('../font/fontawesome-webfont.eot?v=3.2.1');
src: url('../font/fontawesome-webfont.eot?#iefix&v=3.2.1')
format('embedded-opentype'),
url('../font/fontawesome-webfont.woff?v=3.2.1') format('woff'),
url('../font/fontawesome-webfont.ttf?v=3.2.1') format('truetype'),
url('../font/fontawesome-webfont.svg#fontawesomeregular?v=3.2.1')
format('svg');
Those paths are relative to the css resource, so I thought JSF should have
no problem finding it. Now I'm not sure what to do.
Any pointers would be great! Cheers.
Select total members and amount they paid - SQL
Select total members and amount they paid - SQL
I need help for generating a SQL for MySQL database.
I have three tables:
Organisations
members
Payments
Organisations table:
+------------+---------+--------+
| id | name |website |
+------------+---------+--------+
| 1 | AAA | a.com |
|-------------------------------+
| 2 | BBB | b.com |
+------------+---------+--------+
Members table:
+------------+-------------------+--------+-----------------+-----------+
| id | organisation_id |name | Payment_confirm | join_date |
+------------+-------------------+--------+-----------------+-----------+
| 1 | 1 | james | 1 | 2013-8-02 |
|-----------------------------------------+-----------------+-----------+
| 2 | 1 | Jimmy | 0 | 2013-8-25 |
+------------+-------------------+--------+-----------------+-----------+
| 3 | 2 | Manny | 1 | 2013-07-02|
|-----------------------------------------+-----------------+-----------+
| 4 | 1 | Kim | 1 | 2013-09-02|
+------------+-------------------+--------+-----------------+-----------+
Payments table:
+------------+-------------------+--------+-----------------+----------------+
| id | member_id |amount | transaction_id |
transferred_at |
+------------+-------------------+--------+-----------------+----------------+
| 1 | 1 | 100 | T1001 | 2013-8-03
|
|-----------------------------------------+-----------------+---------------
+
| 2 | 2 | 0 | null | Null
|
+------------+-------------------+--------+-----------------+----------------+
| 3 | 3 | 200 | T1002 | Null
|
|-----------------------------------------+-----------------+----------------+
| 4 | 4 | 50 | T1005 | 2013-09-05
|
+------------+-------------------+--------+-----------------+----------------+
How can i select the following:
Expecting the following output:
+------------+-------------------+--------+-----------------+
| Org name | Revenue |untransferred amount |
+------------+-------------------+--------------------------+
| AAA | 150 | 0 |
|-----------------------------------------------------------+
| BBB | 200 | 200 |
+------------+-------------------+--------------------------+
Org name = organisation name
Revenue = Total amount received
untransferred amount = transferred_at is null (payments table)
Thanks in advanced.
I need help for generating a SQL for MySQL database.
I have three tables:
Organisations
members
Payments
Organisations table:
+------------+---------+--------+
| id | name |website |
+------------+---------+--------+
| 1 | AAA | a.com |
|-------------------------------+
| 2 | BBB | b.com |
+------------+---------+--------+
Members table:
+------------+-------------------+--------+-----------------+-----------+
| id | organisation_id |name | Payment_confirm | join_date |
+------------+-------------------+--------+-----------------+-----------+
| 1 | 1 | james | 1 | 2013-8-02 |
|-----------------------------------------+-----------------+-----------+
| 2 | 1 | Jimmy | 0 | 2013-8-25 |
+------------+-------------------+--------+-----------------+-----------+
| 3 | 2 | Manny | 1 | 2013-07-02|
|-----------------------------------------+-----------------+-----------+
| 4 | 1 | Kim | 1 | 2013-09-02|
+------------+-------------------+--------+-----------------+-----------+
Payments table:
+------------+-------------------+--------+-----------------+----------------+
| id | member_id |amount | transaction_id |
transferred_at |
+------------+-------------------+--------+-----------------+----------------+
| 1 | 1 | 100 | T1001 | 2013-8-03
|
|-----------------------------------------+-----------------+---------------
+
| 2 | 2 | 0 | null | Null
|
+------------+-------------------+--------+-----------------+----------------+
| 3 | 3 | 200 | T1002 | Null
|
|-----------------------------------------+-----------------+----------------+
| 4 | 4 | 50 | T1005 | 2013-09-05
|
+------------+-------------------+--------+-----------------+----------------+
How can i select the following:
Expecting the following output:
+------------+-------------------+--------+-----------------+
| Org name | Revenue |untransferred amount |
+------------+-------------------+--------------------------+
| AAA | 150 | 0 |
|-----------------------------------------------------------+
| BBB | 200 | 200 |
+------------+-------------------+--------------------------+
Org name = organisation name
Revenue = Total amount received
untransferred amount = transferred_at is null (payments table)
Thanks in advanced.
Wednesday, 18 September 2013
omit post back in making ( > )
omit post back in making ( > )
i wanna make some thing like this ( << 1 2 3 4 >> ) end of my view . i do
like below . and it work .but i have post back. can i do it another way to
omit post back?
int page = (int)ViewBag.page;
int pages = (int)ViewBag.pages;
<div class="pagination pagination-left">
<ul>
<li>@Html.ActionLink("«", "MyAction", new { numberpage = pages
})</li>
@{for (int i = pages; i >= 1; i--)
{
if (i == page)
{
<li class="active">@Html.ActionLink(i.ToString(), "
MyAction ", new { numberpage = i })</li>
}
else
{
<li>@Html.ActionLink(i.ToString(), " MyAction ", new {
numberpage = i })</li>
}
}
}
<li>@Html.ActionLink("»", " MyAction ", new { numberpage = 1
})</li>
</ul>
</div>
i wanna make some thing like this ( << 1 2 3 4 >> ) end of my view . i do
like below . and it work .but i have post back. can i do it another way to
omit post back?
int page = (int)ViewBag.page;
int pages = (int)ViewBag.pages;
<div class="pagination pagination-left">
<ul>
<li>@Html.ActionLink("«", "MyAction", new { numberpage = pages
})</li>
@{for (int i = pages; i >= 1; i--)
{
if (i == page)
{
<li class="active">@Html.ActionLink(i.ToString(), "
MyAction ", new { numberpage = i })</li>
}
else
{
<li>@Html.ActionLink(i.ToString(), " MyAction ", new {
numberpage = i })</li>
}
}
}
<li>@Html.ActionLink("»", " MyAction ", new { numberpage = 1
})</li>
</ul>
</div>
VISUAL STUDIO 2010 WEB APP NOT WORKING ON CHROME
VISUAL STUDIO 2010 WEB APP NOT WORKING ON CHROME
Im currently running my project on INTERNET EXPLORER 7 and it works
perfectly...
but I have to run it also on GOOGLE CHROME and when I do it results on an
error showing
Oops! Google Chrome could not connect to "ip.ip.ip.ip"
Try reloading: "ip.ip.ip.ip"
I tried using different solutions based on this site and still not working
this site -> Localhost not working in chrome and firefox
Im currently running my project on INTERNET EXPLORER 7 and it works
perfectly...
but I have to run it also on GOOGLE CHROME and when I do it results on an
error showing
Oops! Google Chrome could not connect to "ip.ip.ip.ip"
Try reloading: "ip.ip.ip.ip"
I tried using different solutions based on this site and still not working
this site -> Localhost not working in chrome and firefox
Pull a SQL field with or without a space
Pull a SQL field with or without a space
I would like to run the following queries as one query. My goal is to pull
all rows where the Store field = Best Buy or BestBuy, not pulling the same
row twice. Is there a way to do this one swoop?
Insert Into dbo.X WHERE Store = 'Best Buy';
Insert Into dbo.X WHERE Store = 'BestBuy';
I would like to run the following queries as one query. My goal is to pull
all rows where the Store field = Best Buy or BestBuy, not pulling the same
row twice. Is there a way to do this one swoop?
Insert Into dbo.X WHERE Store = 'Best Buy';
Insert Into dbo.X WHERE Store = 'BestBuy';
evaluation of list comprehensions in python
evaluation of list comprehensions in python
In trying to use a list comprehension to make a list given a conditional,
I see the following:
In [1]: mydicts = [{'foo':'val1'},{'foo':''}]
In [2]: mylist = [d for d in mydicts if d['foo']]
In [3]: mylist
Out[3]: [{'foo': 'val1'}]
In [4]: mydicts[1]['foo'] = 'val2'
In [5]: mydicts
Out[5]: [{'foo': 'val1'}, {'foo': 'val2'}]
In [6]: mylist
Out[6]: [{'foo': 'val1'}]
I've been reading the docs to try and understand this but have come up
with nothing so far, so I'll ask my question here: why is it that mylist
never includes {'foo': 'val2'} even though the reference in the list
comprehension points to mydict, which by In [6] contains {'foo': 'val2'}?
Is this because Python eagerly evaluates list comprehensions? Or is the
lazy/eager dichotomy totally irrelevant to this?
In trying to use a list comprehension to make a list given a conditional,
I see the following:
In [1]: mydicts = [{'foo':'val1'},{'foo':''}]
In [2]: mylist = [d for d in mydicts if d['foo']]
In [3]: mylist
Out[3]: [{'foo': 'val1'}]
In [4]: mydicts[1]['foo'] = 'val2'
In [5]: mydicts
Out[5]: [{'foo': 'val1'}, {'foo': 'val2'}]
In [6]: mylist
Out[6]: [{'foo': 'val1'}]
I've been reading the docs to try and understand this but have come up
with nothing so far, so I'll ask my question here: why is it that mylist
never includes {'foo': 'val2'} even though the reference in the list
comprehension points to mydict, which by In [6] contains {'foo': 'val2'}?
Is this because Python eagerly evaluates list comprehensions? Or is the
lazy/eager dichotomy totally irrelevant to this?
Reporting Services column visibility expression includes substring column names
Reporting Services column visibility expression includes substring column
names
I have an SSRS 2012 report with columns that are to displayed or hidden
based on user parameter selections. Each column has a visibility
expression associated with it. For instance, the expression to show or
hide the "Cash Flow" column is:
=IIF(InStr(JOIN(Parameters!IF_Variables.Value,","),"CashFlow")>0,False,True)
The problem is that I also have a column called "AnnualCashFlow", with a
corresponding visibility expression. If the users selects it, the
"CashFlow" column will also be displayed, even if it wasn't chosen,
because it is a substring of the longer column name.
There are several other columns that are related in this way. How can I
formulate an expression that will only find the exact string requested?
names
I have an SSRS 2012 report with columns that are to displayed or hidden
based on user parameter selections. Each column has a visibility
expression associated with it. For instance, the expression to show or
hide the "Cash Flow" column is:
=IIF(InStr(JOIN(Parameters!IF_Variables.Value,","),"CashFlow")>0,False,True)
The problem is that I also have a column called "AnnualCashFlow", with a
corresponding visibility expression. If the users selects it, the
"CashFlow" column will also be displayed, even if it wasn't chosen,
because it is a substring of the longer column name.
There are several other columns that are related in this way. How can I
formulate an expression that will only find the exact string requested?
WCF WebHttpBinding Craches Web Server
WCF WebHttpBinding Craches Web Server
I am banging my head against the wall here. I have a service that takes as
input an object on a POST. When debugging I foind that my service resieves
the result and performs the as expected but at the end of the method as I
return out of the webmethod I get an error:
System.Net.WebException: The underlying connection was closed: An
unexpected error occurred on a receive. ---> System.IO.IOException: Unable
to read data from the transport connection: An existing connection was
forcibly closed by the remote host. --->
System.Net.Sockets.SocketException: An existing connection was forcibly
closed by the remote host
I can not for the life of me figure out what is going on, i'm assuming its
either how i'm calling the service or config, does anyone have any ideas?
My contract looks like:
[ServiceContract]
public interface IHouseholdService
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "GetHouseholds",
ResponseFormat = WebMessageFormat.Json, RequestFormat =
WebMessageFormat.Json)]
HouseholdDto[] GetHouseholdsByCriteria(HouseholdSearch criteria);
}
and my config looks like this:
</endpoint>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webBehaviour">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="Default">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
I'm calling it like this:
var dto = new HouseholdSearch() {HouseholdNumber = "16653373"};
var url = "http://localhost:48460/Household.svc/GetHouseholds";
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
var ser = new DataContractJsonSerializer(dto.GetType());
var ms = new MemoryStream();
ser.WriteObject(ms, dto);
String json = Encoding.UTF8.GetString(ms.ToArray());
var writer = new StreamWriter(request.GetRequestStream());
writer.Write(json);
writer.Close();
WebResponse responce = request.GetResponse();
Stream reader = responce.GetResponseStream();
var sReader = new StreamReader(reader);
var outResult = sReader.ReadToEnd();
sReader.Close();
Any help would be super helpful!!!
I am banging my head against the wall here. I have a service that takes as
input an object on a POST. When debugging I foind that my service resieves
the result and performs the as expected but at the end of the method as I
return out of the webmethod I get an error:
System.Net.WebException: The underlying connection was closed: An
unexpected error occurred on a receive. ---> System.IO.IOException: Unable
to read data from the transport connection: An existing connection was
forcibly closed by the remote host. --->
System.Net.Sockets.SocketException: An existing connection was forcibly
closed by the remote host
I can not for the life of me figure out what is going on, i'm assuming its
either how i'm calling the service or config, does anyone have any ideas?
My contract looks like:
[ServiceContract]
public interface IHouseholdService
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "GetHouseholds",
ResponseFormat = WebMessageFormat.Json, RequestFormat =
WebMessageFormat.Json)]
HouseholdDto[] GetHouseholdsByCriteria(HouseholdSearch criteria);
}
and my config looks like this:
</endpoint>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webBehaviour">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="Default">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
I'm calling it like this:
var dto = new HouseholdSearch() {HouseholdNumber = "16653373"};
var url = "http://localhost:48460/Household.svc/GetHouseholds";
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
var ser = new DataContractJsonSerializer(dto.GetType());
var ms = new MemoryStream();
ser.WriteObject(ms, dto);
String json = Encoding.UTF8.GetString(ms.ToArray());
var writer = new StreamWriter(request.GetRequestStream());
writer.Write(json);
writer.Close();
WebResponse responce = request.GetResponse();
Stream reader = responce.GetResponseStream();
var sReader = new StreamReader(reader);
var outResult = sReader.ReadToEnd();
sReader.Close();
Any help would be super helpful!!!
link Text wrapping spacing
link Text wrapping spacing
I have a very long text string that wraps around fine, however, the text
looks squeezed. Is there a way to add some space between the wrapped text
using css or anything else?
I have a very long text string that wraps around fine, however, the text
looks squeezed. Is there a way to add some space between the wrapped text
using css or anything else?
Migration from solr 3.6.1 to 4.4 - custom analyzer
Migration from solr 3.6.1 to 4.4 - custom analyzer
I have problem with migration from solr 3.6.1 to 4.4.
In schema I have fieldType with custom analyzer, and field "content" that
use this type.
In data-config I have 2 main entity sections:
1) fetch data from wiki
2) fetch data from binary files by Tika
On 3.6.1 everything worked fine.
On 4.4 after executing data import, I am getting status which inform that
all documents that I want has been processed.
After executing this query "*:*", I am getting all documents that I want.
But when I trying to search by specific words from "content" (e.g.
"content:project") I've get only documents from wiki.
I check my indexes, and it seems that I have only terms from wiki.
When I change order in data-config:
1) fetch data from binary files by Tika
2) fetch data from wiki
I have only terms from binary files.
Second problem is that altough I have some data indexed sometimes the same
query return results, sometimes not.
Without my custom analyzer everything works correctly (when I use type
text_general from example),
it should point that problem lies in my custom code,
but when I use analysis from admin panel on "content" field everything
looks good.
I have problem with migration from solr 3.6.1 to 4.4.
In schema I have fieldType with custom analyzer, and field "content" that
use this type.
In data-config I have 2 main entity sections:
1) fetch data from wiki
2) fetch data from binary files by Tika
On 3.6.1 everything worked fine.
On 4.4 after executing data import, I am getting status which inform that
all documents that I want has been processed.
After executing this query "*:*", I am getting all documents that I want.
But when I trying to search by specific words from "content" (e.g.
"content:project") I've get only documents from wiki.
I check my indexes, and it seems that I have only terms from wiki.
When I change order in data-config:
1) fetch data from binary files by Tika
2) fetch data from wiki
I have only terms from binary files.
Second problem is that altough I have some data indexed sometimes the same
query return results, sometimes not.
Without my custom analyzer everything works correctly (when I use type
text_general from example),
it should point that problem lies in my custom code,
but when I use analysis from admin panel on "content" field everything
looks good.
IE6 Selectors issues
IE6 Selectors issues
My site actually works okay in other browsers but when I checked in IE6,
there is a problem. In my global navigation, I clicked this certain page.
For example, I clicked ABOUT ME page. My global navigation changes its
image when the page is active. Like it has a different color from inactive
pages. In IE6, when I'm in the current page, ABOUT ME, the current image
in the global navigation is different. Say, it's CONTACT US. But when
hovered, the image that appears is correct.
This is the snippet of CSS:
.cat-item-5 {
float: left;
display: inline;
width: 162px;
height: 48px;
text-indent: -30000px;
background: -639px 0 url(images/menu.png) no-repeat;
}
.cat-item-5 a {
display: block;
width: 162px;
height: 48px;
background: -639px 0 url(images/menu.png) no-repeat;
}
.cat-item-5 a:hover,
.cat-item-5.current-cat a {
background: -639px 0 url(images/menu_o.png) no-repeat;
}
Hope you can help me, thanks!
My site actually works okay in other browsers but when I checked in IE6,
there is a problem. In my global navigation, I clicked this certain page.
For example, I clicked ABOUT ME page. My global navigation changes its
image when the page is active. Like it has a different color from inactive
pages. In IE6, when I'm in the current page, ABOUT ME, the current image
in the global navigation is different. Say, it's CONTACT US. But when
hovered, the image that appears is correct.
This is the snippet of CSS:
.cat-item-5 {
float: left;
display: inline;
width: 162px;
height: 48px;
text-indent: -30000px;
background: -639px 0 url(images/menu.png) no-repeat;
}
.cat-item-5 a {
display: block;
width: 162px;
height: 48px;
background: -639px 0 url(images/menu.png) no-repeat;
}
.cat-item-5 a:hover,
.cat-item-5.current-cat a {
background: -639px 0 url(images/menu_o.png) no-repeat;
}
Hope you can help me, thanks!
Tuesday, 17 September 2013
trying to get coffeescript to compile correctly to javascript for node server
trying to get coffeescript to compile correctly to javascript for node server
I'm working my way through a book on node.js, but I'm attempting to learn
it in coffeescript rather than javascript.
Currently attempting to get some coffeescript to compile to this js as
part of a routing demonstration:
var http = require('http'),
url = require('url');
http.createServer(function (req, res) {
var pathname = url.parse(req.url).pathname;
if (pathname === '/') {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Home Page\n')
} else if (pathname === '/about') {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('About Us\n')
} else if (pathname === '/redirect') {
res.writeHead(301, {
'Location': '/'
});
res.end();
} else {
res.writeHead(404, {
'Content-Type': 'text/plain'
});
res.end('Page not found\n')
}
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');
Here's my coffeescript code:
http = require 'http'
url = require 'url'
port = 3000
host = "127.0.0.1"
http.createServer (req, res) ->
pathname = url.parse(req.url).pathname
if pathname == '/'
res.writeHead 200, 'Content-Type': 'text/plain'
res.end 'Home Page\n'
else pathname == '/about'
res.writeHead 200, 'Content-Type': 'text/plain'
res.end 'About Us\n'
else pathname == '/redirect'
res.writeHead 301, 'Location': '/'
res.end()
else
res.writeHead 404, 'Content-Type': 'text/plain'
res.end 'Page not found\n'
.listen port, host
console.log "Server running at http://#{host}:#{port}/"
The error that I'm getting back is:
helloworld.coffee:14:1: error: unexpected INDENT
res.writeHead 200, 'Content-Type': 'text/plain'
^^^^^^^^
which makes me think that there's something wrong with the way that I have
the if...else logic set up.
Any thoughts why this might be happening?
I'm working my way through a book on node.js, but I'm attempting to learn
it in coffeescript rather than javascript.
Currently attempting to get some coffeescript to compile to this js as
part of a routing demonstration:
var http = require('http'),
url = require('url');
http.createServer(function (req, res) {
var pathname = url.parse(req.url).pathname;
if (pathname === '/') {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Home Page\n')
} else if (pathname === '/about') {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('About Us\n')
} else if (pathname === '/redirect') {
res.writeHead(301, {
'Location': '/'
});
res.end();
} else {
res.writeHead(404, {
'Content-Type': 'text/plain'
});
res.end('Page not found\n')
}
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');
Here's my coffeescript code:
http = require 'http'
url = require 'url'
port = 3000
host = "127.0.0.1"
http.createServer (req, res) ->
pathname = url.parse(req.url).pathname
if pathname == '/'
res.writeHead 200, 'Content-Type': 'text/plain'
res.end 'Home Page\n'
else pathname == '/about'
res.writeHead 200, 'Content-Type': 'text/plain'
res.end 'About Us\n'
else pathname == '/redirect'
res.writeHead 301, 'Location': '/'
res.end()
else
res.writeHead 404, 'Content-Type': 'text/plain'
res.end 'Page not found\n'
.listen port, host
console.log "Server running at http://#{host}:#{port}/"
The error that I'm getting back is:
helloworld.coffee:14:1: error: unexpected INDENT
res.writeHead 200, 'Content-Type': 'text/plain'
^^^^^^^^
which makes me think that there's something wrong with the way that I have
the if...else logic set up.
Any thoughts why this might be happening?
custom checkbox repeating in ie7 and ie8
custom checkbox repeating in ie7 and ie8
Custom check box of a form I am buidling seems to get repeated in IE7. I
am using "custom-form-elements.js" from
http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/
It is working fine except the check box seems like repeating in IE7 and
IE8. I have added the javascript file as stated there. Attached is my
check box image file
In the javascript file I have changed the width/height as below
var checkboxHeight = "24";
And in my css as below
.checkbox {
width: 25px;
height: 24px;
padding: 0 5px 0 0;
background: url(../images/checkbox.png) no-repeat;
display: block;
clear: left;
float: left;
margin-left: 90px;
margin-right: 20px;
}
Custom check box of a form I am buidling seems to get repeated in IE7. I
am using "custom-form-elements.js" from
http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/
It is working fine except the check box seems like repeating in IE7 and
IE8. I have added the javascript file as stated there. Attached is my
check box image file
In the javascript file I have changed the width/height as below
var checkboxHeight = "24";
And in my css as below
.checkbox {
width: 25px;
height: 24px;
padding: 0 5px 0 0;
background: url(../images/checkbox.png) no-repeat;
display: block;
clear: left;
float: left;
margin-left: 90px;
margin-right: 20px;
}
Why is my Scrapy scraper only returning the second page of results?
Why is my Scrapy scraper only returning the second page of results?
College is starting soon for me, so I decided to build a web scraper for
Rate My Professor to help me find the highest rated teachers at my school.
The scraper works perfectly well... but only for the second page! No
matter what I try, I can't get it to work properly.
This is the URL that I am scraping from:
http://www.ratemyprofessors.com/SelectTeacher.jsp?sid=2311&pageNo=3 (not
my actual college, but has the same type of URL structure)
And here is my spider:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from rmp.items import RmpItem
class MySpider(CrawlSpider):
name = "rmp"
allowed_domains = ["ratemyprofessors.com"]
start_urls =
["http://www.ratemyprofessors.com/SelectTeacher.jsp?sid=2311"]
rules = (Rule(SgmlLinkExtractor(allow=('&pageNo=\d',),
restrict_xpaths=('//a[@id="next"]',)), callback='parser',
follow=True),)
def parser(self, response):
hxs = HtmlXPathSelector(response)
html = hxs.select("//div[@class='entry odd vertical-center'] | //
div[@class='entry even vertical-center']")
profs = []
for line in html:
prof = RmpItem()
prof["name"] = line.select("div[@class='profName']/a/text()").
extract()
prof["dept"] = line.select("div[@class='profDept']/text()").
extract()
prof["ratings"] = line.select("div[@class='profRatings']/
text()").extract()
prof["avg"] = line.select("div[@class='profAvg']/text()").
extract()
profs.append(prof)
Some things I have tried include removing the restrict_xpaths keyword
argument (resulted in the scraper going after the first, the last, the
next, and the back buttons because all share the &pageNo=\d URL structure)
and changing the regex of the allow keyword argument (resulted in no
change).
Does anybody have any suggestions? This seems to be a simple problem, but
I've already spent an hour and a half trying to figure it out! Any help
would be very appreciated.
College is starting soon for me, so I decided to build a web scraper for
Rate My Professor to help me find the highest rated teachers at my school.
The scraper works perfectly well... but only for the second page! No
matter what I try, I can't get it to work properly.
This is the URL that I am scraping from:
http://www.ratemyprofessors.com/SelectTeacher.jsp?sid=2311&pageNo=3 (not
my actual college, but has the same type of URL structure)
And here is my spider:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from rmp.items import RmpItem
class MySpider(CrawlSpider):
name = "rmp"
allowed_domains = ["ratemyprofessors.com"]
start_urls =
["http://www.ratemyprofessors.com/SelectTeacher.jsp?sid=2311"]
rules = (Rule(SgmlLinkExtractor(allow=('&pageNo=\d',),
restrict_xpaths=('//a[@id="next"]',)), callback='parser',
follow=True),)
def parser(self, response):
hxs = HtmlXPathSelector(response)
html = hxs.select("//div[@class='entry odd vertical-center'] | //
div[@class='entry even vertical-center']")
profs = []
for line in html:
prof = RmpItem()
prof["name"] = line.select("div[@class='profName']/a/text()").
extract()
prof["dept"] = line.select("div[@class='profDept']/text()").
extract()
prof["ratings"] = line.select("div[@class='profRatings']/
text()").extract()
prof["avg"] = line.select("div[@class='profAvg']/text()").
extract()
profs.append(prof)
Some things I have tried include removing the restrict_xpaths keyword
argument (resulted in the scraper going after the first, the last, the
next, and the back buttons because all share the &pageNo=\d URL structure)
and changing the regex of the allow keyword argument (resulted in no
change).
Does anybody have any suggestions? This seems to be a simple problem, but
I've already spent an hour and a half trying to figure it out! Any help
would be very appreciated.
C# using filewatcher to monitor folder to send an email when pdf is received with attachment of pdf
C# using filewatcher to monitor folder to send an email when pdf is
received with attachment of pdf
I have the following code to watch a folder for incoming files. Once the
folder receives the files, the program sends and email along with an
attachment of the file, in this case, a pdf. However, sometimes we receive
more than one file and it sends multiple emails with the same pdf, but
with a different file name. Do I have to release the pdf files? I thought
I was doing that with the pdfFile.Dispose() and mail.Dispose().
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Mail;
namespace Email
{
class Program
{
static string files;
static void Main(string[] args)
{
fileWatcher();
}
private static void fileWatcher()
{
try
{
//Create a filesystemwatcher to monitor the path for documents.
string path = @"\\server\folder\";
FileSystemWatcher watcher = new FileSystemWatcher(path);
//Watch for changes in the Last Access, Last Write times,
renaming of files and directories.
watcher.NotifyFilter = NotifyFilters.LastAccess |
NotifyFilters.FileName | NotifyFilters.LastWrite
| NotifyFilters.DirectoryName | NotifyFilters.CreationTime;
watcher.Filter = "FILE*";
//Register a handler that gets called when a file is created.
watcher.Created += new FileSystemEventHandler(watcher_Created);
//Register a handler that gets called if the FileSystemWatcher
need to report an error.
watcher.Error += new ErrorEventHandler(watcher_Error);
//Begin watching the path for budget documents/
watcher.EnableRaisingEvents = true;
Console.WriteLine("Monitoring incoming files for Budget
documents.");
Console.WriteLine("Please do not close.");
Console.WriteLine("Press Enter to quit the program.");
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught", e);
}
}
//This method is called when a file is created.
static void watcher_Created(object sender, FileSystemEventArgs e)
{
try
{
//Show that a file has been created
WatcherChangeTypes changeTypes = e.ChangeType;
Console.WriteLine("File {0} {1}", e.FullPath,
changeTypes.ToString());
String fileName = e.Name.ToString();
sendMail(fileName);
// throw new NotImplementedException();
}
catch (Exception exc)
{
Console.WriteLine("{0} Exception caught", exc);
}
}
static void watcher_Error(object sender, ErrorEventArgs e)
{
Console.WriteLine("The file watcher has detected an error.");
throw new NotImplementedException();
}
private static void sendMail(string fileName)
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("From@mail.com");
mail.To.Add("Me@mail.com");
string filesDirectory = @"\server\folder\";
string searchForFile = "FILE*";
string[] searchFiles = Directory.GetFiles(filesDirectory,
searchForFile);
foreach (string File in searchFiles)
files = File;
Attachment pdfFile = new Attachment(files);
mail.Subject = "PDF Files " + fileName;
mail.Body = "Attached is the pdf file " + fileName + ".";
mail.Attachments.Add(pdfFile);
SmtpClient client = new SmtpClient("SMTP.MAIL.COM");
client.Send(mail);
//To release files and enable accessing them after they are sent.
pdfFile.Dispose();
mail.Dispose();
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught", e);
}
}
}
}
Any help would be greatly appreciated.
received with attachment of pdf
I have the following code to watch a folder for incoming files. Once the
folder receives the files, the program sends and email along with an
attachment of the file, in this case, a pdf. However, sometimes we receive
more than one file and it sends multiple emails with the same pdf, but
with a different file name. Do I have to release the pdf files? I thought
I was doing that with the pdfFile.Dispose() and mail.Dispose().
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Mail;
namespace Email
{
class Program
{
static string files;
static void Main(string[] args)
{
fileWatcher();
}
private static void fileWatcher()
{
try
{
//Create a filesystemwatcher to monitor the path for documents.
string path = @"\\server\folder\";
FileSystemWatcher watcher = new FileSystemWatcher(path);
//Watch for changes in the Last Access, Last Write times,
renaming of files and directories.
watcher.NotifyFilter = NotifyFilters.LastAccess |
NotifyFilters.FileName | NotifyFilters.LastWrite
| NotifyFilters.DirectoryName | NotifyFilters.CreationTime;
watcher.Filter = "FILE*";
//Register a handler that gets called when a file is created.
watcher.Created += new FileSystemEventHandler(watcher_Created);
//Register a handler that gets called if the FileSystemWatcher
need to report an error.
watcher.Error += new ErrorEventHandler(watcher_Error);
//Begin watching the path for budget documents/
watcher.EnableRaisingEvents = true;
Console.WriteLine("Monitoring incoming files for Budget
documents.");
Console.WriteLine("Please do not close.");
Console.WriteLine("Press Enter to quit the program.");
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught", e);
}
}
//This method is called when a file is created.
static void watcher_Created(object sender, FileSystemEventArgs e)
{
try
{
//Show that a file has been created
WatcherChangeTypes changeTypes = e.ChangeType;
Console.WriteLine("File {0} {1}", e.FullPath,
changeTypes.ToString());
String fileName = e.Name.ToString();
sendMail(fileName);
// throw new NotImplementedException();
}
catch (Exception exc)
{
Console.WriteLine("{0} Exception caught", exc);
}
}
static void watcher_Error(object sender, ErrorEventArgs e)
{
Console.WriteLine("The file watcher has detected an error.");
throw new NotImplementedException();
}
private static void sendMail(string fileName)
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("From@mail.com");
mail.To.Add("Me@mail.com");
string filesDirectory = @"\server\folder\";
string searchForFile = "FILE*";
string[] searchFiles = Directory.GetFiles(filesDirectory,
searchForFile);
foreach (string File in searchFiles)
files = File;
Attachment pdfFile = new Attachment(files);
mail.Subject = "PDF Files " + fileName;
mail.Body = "Attached is the pdf file " + fileName + ".";
mail.Attachments.Add(pdfFile);
SmtpClient client = new SmtpClient("SMTP.MAIL.COM");
client.Send(mail);
//To release files and enable accessing them after they are sent.
pdfFile.Dispose();
mail.Dispose();
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught", e);
}
}
}
}
Any help would be greatly appreciated.
Passing dictionary to a View
Passing dictionary to a View
I am passing this type into my view
Dictionary<String, List<myObj>> results = ...
View(results);
My view has this declaration
<%@ Page Title="" Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<Models.myObj>>" %>
I run into this error: The model item passed into the dictionary is of
type
'System.Collections.Generic.Dictionary2[System.String,System.Collections.Generic.List1[Models.myObj]]',
but this dictionary requires a model item of type
'System.Collections.Generic.IEnumerable1[Models.myObj]'.`
This is because of the new structure I am sending down to the view. How do
I auto update the view so it uses the new param type?
I am passing this type into my view
Dictionary<String, List<myObj>> results = ...
View(results);
My view has this declaration
<%@ Page Title="" Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<Models.myObj>>" %>
I run into this error: The model item passed into the dictionary is of
type
'System.Collections.Generic.Dictionary2[System.String,System.Collections.Generic.List1[Models.myObj]]',
but this dictionary requires a model item of type
'System.Collections.Generic.IEnumerable1[Models.myObj]'.`
This is because of the new structure I am sending down to the view. How do
I auto update the view so it uses the new param type?
gdb not recording command history
gdb not recording command history
I am trying to record my command history in gdb so when I close gdb and
open it again, I can press the up arrow key and get commands from previous
sessions. I tried a solution mentioned here, but it doesn't seem to work.
Here is my .gdbinit file:
set history filename ~/.gdb_history
set history save
handle SIG34 nostop noprint pass
handle SIGHUP nostop noprint pass
The signals are handled correctly in gdb so I presume the file must be
being read correctly...
Any suggestions are appreciated!
Edit
Also I need to the gdb using sudo sometimes, would this affect the saving
/ retrieving of commands?
I am trying to record my command history in gdb so when I close gdb and
open it again, I can press the up arrow key and get commands from previous
sessions. I tried a solution mentioned here, but it doesn't seem to work.
Here is my .gdbinit file:
set history filename ~/.gdb_history
set history save
handle SIG34 nostop noprint pass
handle SIGHUP nostop noprint pass
The signals are handled correctly in gdb so I presume the file must be
being read correctly...
Any suggestions are appreciated!
Edit
Also I need to the gdb using sudo sometimes, would this affect the saving
/ retrieving of commands?
Sunday, 15 September 2013
onbeforeunload not always working
onbeforeunload not always working
I'm making a simple script to save some data on when a user access a page
and leaves a page, along with some other page details. The script "works",
but it doesn't work all the time. It seems to be working sporadically. I'm
not getting console errors on the time it doesn't. The server side works
fine.
window.onload = function() {
var timeStarted, i, c, l, timeLeft, pageData;
timeStarted = new Date().getTime();
i = <?php echo $model->id; ?>;
c = <?php echo $model->cat; ?>;
l= <?php echo $model->loc; ?>;
window.onbeforeunload = function(){
timeLeft = new Date().getTime();
pageData = [{name: 'timeStarted', value: timeStarted},
{name: 'i', value: job},
{name: 'c', value: cat},
{name: 'l', value: loc},
{name: 'timeLeft', value: timeLeft}];
// Set url for JavaSCript
var url = '<?php echo Yii::app()->createUrl("item/viewedItemInformation");
?>';
<?php echo CHtml::ajax(array(
'url'=>'js:url',
'data'=> "js: pageData",
'type'=>'post',
'dataType'=>'json',
)); ?>;
}
}
Note
I've just read this post window.onbeforeunload not working in chrome and I
am using chrome. However I seem to get the same results in FF too.
What is the correct away about solving this?
I'm making a simple script to save some data on when a user access a page
and leaves a page, along with some other page details. The script "works",
but it doesn't work all the time. It seems to be working sporadically. I'm
not getting console errors on the time it doesn't. The server side works
fine.
window.onload = function() {
var timeStarted, i, c, l, timeLeft, pageData;
timeStarted = new Date().getTime();
i = <?php echo $model->id; ?>;
c = <?php echo $model->cat; ?>;
l= <?php echo $model->loc; ?>;
window.onbeforeunload = function(){
timeLeft = new Date().getTime();
pageData = [{name: 'timeStarted', value: timeStarted},
{name: 'i', value: job},
{name: 'c', value: cat},
{name: 'l', value: loc},
{name: 'timeLeft', value: timeLeft}];
// Set url for JavaSCript
var url = '<?php echo Yii::app()->createUrl("item/viewedItemInformation");
?>';
<?php echo CHtml::ajax(array(
'url'=>'js:url',
'data'=> "js: pageData",
'type'=>'post',
'dataType'=>'json',
)); ?>;
}
}
Note
I've just read this post window.onbeforeunload not working in chrome and I
am using chrome. However I seem to get the same results in FF too.
What is the correct away about solving this?
Replacing a div that is called by jQuery onclick
Replacing a div that is called by jQuery onclick
I have a list object and each contains an upvote div that is called
onclick by my jQuery (I essentially flip the vote button in each div and
asynchronously change the vote for that div via Ajax). All object divs are
contained within row.replace which I use to sort the objects
asynchronously. The thing is that once I click on the sorter and sort the
content of the .row.replace div, the upvote divs in the sorted list of
objects stop getting called onclick ie. I can upvote and remove my upvote
before sorting with jqury+ajax, once the sort is applied and the contents
of the div are replaced, my upvote button stops working.
Here is the jQuery:
$(document).ready(function () {
$('.sorter').click(function () {
$('.row.replace').empty();
$('.row.replace').append("<br><br><br><br><p align='center'><img
id='theImg'
src='/media/loading1.gif'/></p><br><br><br><br><br><br><br><br>");
var sort = $(this).attr("name");
$.ajax({
type: "POST",
url: "/filter_home/" + "Lunch" + "/" + "TrendingNow" + "/",
data: {
'name': 'me',
'csrfmiddlewaretoken': '{{csrf_token}}'
},
dataType: "json",
success: function (json) {
//loop through json object
//alert("yoo");
$('.row.replace').empty();
for (var i = 0; i < json.length; i++) {
$('.row.replace').append("<div class='showroom-item span3'> <div
class='thumbnail'> <img class='food_pic' src='/media/" +
json[i].fields.image + "' alt='Portfolio Image'> <div
class='span3c'> <a><b>" + json[i].fields.name + "</b> </a>
</div> <div class='span3d'> posted by <a><b>" +
json[i].fields.creator.username + "</b></a> </div> <div
class='span3c'> <div class='btn-group'> <div class='flip flip" +
json[i].pk + "'> <div class='card'> {% if 0 %} <div class='face
front'> <button type='button' class='btn btn-grove-one upvote'
id='upvote' name='" + json[i].pk + "'>Upvoted <i
class='glyphicons thumbs_up'><i></i></i><i class='vote-count" +
json[i].pk + "'>" + json[i].fields.other_votes +
"</i></a></button> </div> <div class='face back'> <button
type='button' class='btn btn-grove-two upvote' id='upvote'
name='" + json[i].pk + "'>Upvote <i class='glyphicons
thumbs_up'><i></i></i><i class='vote-count" + json[i].pk + "'>"
+ json[i].fields.other_votes + " </i></a></button> </div> {%
else %} <div class='face front'> <button type='button'
class='btn btn-grove-two upvote' id='upvote' name='" +
json[i].pk + "'>Upvote <i class='glyphicons
thumbs_up'><i></i></i><i class='vote-count" + json[i].pk + "'>"
+ json[i].fields.other_votes + " </i></a></button> </div> <div
class='face back'> <button type='button' class='btn
btn-grove-one upvote' id='upvote' name='" + json[i].pk +
"'>Upvoted <i class='glyphicons thumbs_up'><i></i></i><i
class='vote-count" + json[i].pk + "'>" +
json[i].fields.other_votes + "</i></a></button> </div> {% endif
%} </div> </div> </div> <div class='btn-group'> <button
type='button' class='btn btn-grove-two'><i class='glyphicons
comments'><i></i></i>" + json[i].fields.comment_count +
"</a></button> </div> </div> </div> </div>");
}
//json[i].fields.name
},
error: function (xhr, errmsg, err) {
alert("oops, something went wrong! Please try again.");
}
});
return false;
});
$('.upvote').click(function () {
var x = $(this).attr("name");
$.ajax({
type: "POST",
url: "/upvote/" + x + "/",
data: {
'name': 'me',
'csrfmiddlewaretoken': '{{csrf_token}}'
},
dataType: "json",
success: function (json) {
var y = "vote-count" + x;;
$('i[class= "' + y + '"]').text(json.vote_count);
//flip button
$('.flip' + x).find('.card').toggleClass('flipped');
},
error: function (xhr, errmsg, err) {
alert("oops, something went wrong! Please try again.");
}
});
return false;
});
});
I have a list object and each contains an upvote div that is called
onclick by my jQuery (I essentially flip the vote button in each div and
asynchronously change the vote for that div via Ajax). All object divs are
contained within row.replace which I use to sort the objects
asynchronously. The thing is that once I click on the sorter and sort the
content of the .row.replace div, the upvote divs in the sorted list of
objects stop getting called onclick ie. I can upvote and remove my upvote
before sorting with jqury+ajax, once the sort is applied and the contents
of the div are replaced, my upvote button stops working.
Here is the jQuery:
$(document).ready(function () {
$('.sorter').click(function () {
$('.row.replace').empty();
$('.row.replace').append("<br><br><br><br><p align='center'><img
id='theImg'
src='/media/loading1.gif'/></p><br><br><br><br><br><br><br><br>");
var sort = $(this).attr("name");
$.ajax({
type: "POST",
url: "/filter_home/" + "Lunch" + "/" + "TrendingNow" + "/",
data: {
'name': 'me',
'csrfmiddlewaretoken': '{{csrf_token}}'
},
dataType: "json",
success: function (json) {
//loop through json object
//alert("yoo");
$('.row.replace').empty();
for (var i = 0; i < json.length; i++) {
$('.row.replace').append("<div class='showroom-item span3'> <div
class='thumbnail'> <img class='food_pic' src='/media/" +
json[i].fields.image + "' alt='Portfolio Image'> <div
class='span3c'> <a><b>" + json[i].fields.name + "</b> </a>
</div> <div class='span3d'> posted by <a><b>" +
json[i].fields.creator.username + "</b></a> </div> <div
class='span3c'> <div class='btn-group'> <div class='flip flip" +
json[i].pk + "'> <div class='card'> {% if 0 %} <div class='face
front'> <button type='button' class='btn btn-grove-one upvote'
id='upvote' name='" + json[i].pk + "'>Upvoted <i
class='glyphicons thumbs_up'><i></i></i><i class='vote-count" +
json[i].pk + "'>" + json[i].fields.other_votes +
"</i></a></button> </div> <div class='face back'> <button
type='button' class='btn btn-grove-two upvote' id='upvote'
name='" + json[i].pk + "'>Upvote <i class='glyphicons
thumbs_up'><i></i></i><i class='vote-count" + json[i].pk + "'>"
+ json[i].fields.other_votes + " </i></a></button> </div> {%
else %} <div class='face front'> <button type='button'
class='btn btn-grove-two upvote' id='upvote' name='" +
json[i].pk + "'>Upvote <i class='glyphicons
thumbs_up'><i></i></i><i class='vote-count" + json[i].pk + "'>"
+ json[i].fields.other_votes + " </i></a></button> </div> <div
class='face back'> <button type='button' class='btn
btn-grove-one upvote' id='upvote' name='" + json[i].pk +
"'>Upvoted <i class='glyphicons thumbs_up'><i></i></i><i
class='vote-count" + json[i].pk + "'>" +
json[i].fields.other_votes + "</i></a></button> </div> {% endif
%} </div> </div> </div> <div class='btn-group'> <button
type='button' class='btn btn-grove-two'><i class='glyphicons
comments'><i></i></i>" + json[i].fields.comment_count +
"</a></button> </div> </div> </div> </div>");
}
//json[i].fields.name
},
error: function (xhr, errmsg, err) {
alert("oops, something went wrong! Please try again.");
}
});
return false;
});
$('.upvote').click(function () {
var x = $(this).attr("name");
$.ajax({
type: "POST",
url: "/upvote/" + x + "/",
data: {
'name': 'me',
'csrfmiddlewaretoken': '{{csrf_token}}'
},
dataType: "json",
success: function (json) {
var y = "vote-count" + x;;
$('i[class= "' + y + '"]').text(json.vote_count);
//flip button
$('.flip' + x).find('.card').toggleClass('flipped');
},
error: function (xhr, errmsg, err) {
alert("oops, something went wrong! Please try again.");
}
});
return false;
});
});
Iterating over JSON object in python
Iterating over JSON object in python
I have my JSON code below being stored in jso variable.
jso = {
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
Whenever I'm trying to fetch the data or iterate over the JSON Object,
it's printing the data in the reverse order i.e object first and then the
other parameters.
For eg. I execute:
>>> for k,v in jso.iteritems():
... print v
...
AND THE OUTPUT I GOT:
OUTPUT GETTING
{'GlossList': {'GlossEntry': {'Abbrev': 'ISO 8879:1986', 'GlossDef':
{'GlossSeeAlso': ['GML', 'XML']}, 'GlossSee': 'markup'}}, 'title': 'S'}
It can be seen that though 'title':'S' was written before the 'GlossList'
Object still the data is printing in the reverse order. I mean it should
have:
OUTPUT EXPECTED
{ 'title': 'S', 'GlossList': {'GlossEntry': {'Abbrev': 'ISO 8879:1986',
'GlossDef': {'GlossSeeAlso': ['GML', 'XML']}, 'GlossSee': 'markup'}}}
I have my JSON code below being stored in jso variable.
jso = {
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
Whenever I'm trying to fetch the data or iterate over the JSON Object,
it's printing the data in the reverse order i.e object first and then the
other parameters.
For eg. I execute:
>>> for k,v in jso.iteritems():
... print v
...
AND THE OUTPUT I GOT:
OUTPUT GETTING
{'GlossList': {'GlossEntry': {'Abbrev': 'ISO 8879:1986', 'GlossDef':
{'GlossSeeAlso': ['GML', 'XML']}, 'GlossSee': 'markup'}}, 'title': 'S'}
It can be seen that though 'title':'S' was written before the 'GlossList'
Object still the data is printing in the reverse order. I mean it should
have:
OUTPUT EXPECTED
{ 'title': 'S', 'GlossList': {'GlossEntry': {'Abbrev': 'ISO 8879:1986',
'GlossDef': {'GlossSeeAlso': ['GML', 'XML']}, 'GlossSee': 'markup'}}}
PSPACE with examples
PSPACE with examples
I came across the PSPACE concept that PSPACE is the set of all decision
problems which can be solved by a Turing machine using a polynomial amount
of space.
this does not make me clear what exactly it is.
Can someone please explain PSPACE and complete PSPACE with example??
I came across the PSPACE concept that PSPACE is the set of all decision
problems which can be solved by a Turing machine using a polynomial amount
of space.
this does not make me clear what exactly it is.
Can someone please explain PSPACE and complete PSPACE with example??
Why a button isn't being shown even when php doesn't corrupt it
Why a button isn't being shown even when php doesn't corrupt it
<?php
require 'openid.php';
try
{
# Change 'localhost' to your domain name.
$openid = new LightOpenID('localhost');
if(!$openid->mode)
{
if(isset($_GET['login']))
{
$openid->identity = 'https://www.google.com/accounts/o8/id';
header('Location: ' . $openid->authUrl());
}
?>
<form action="?login" method="post">
<button>Login with Google</button>
</form>
<?php
}
elseif($openid->mode == 'cancel')
{
echo 'User has canceled authentication!';
}
else
{
echo 'User ' . ($openid->validate() ? $openid->identity . ' has '
: 'has not ') . 'logged in.';
}
}
catch(ErrorException $e)
{
echo $e->getMessage();
}
This question was asked but a big part wasn't answered due lack of testing
, the question is that why doesn't the login with google button be shown
after a login note : this is openid and will be redirected to google after
its shown and back to the page after logging to google but it doesn't show
the button after the login, reason ? for testing I have uploaded in
http://dota2tradebots.com/googlelogin.php
<?php
require 'openid.php';
try
{
# Change 'localhost' to your domain name.
$openid = new LightOpenID('localhost');
if(!$openid->mode)
{
if(isset($_GET['login']))
{
$openid->identity = 'https://www.google.com/accounts/o8/id';
header('Location: ' . $openid->authUrl());
}
?>
<form action="?login" method="post">
<button>Login with Google</button>
</form>
<?php
}
elseif($openid->mode == 'cancel')
{
echo 'User has canceled authentication!';
}
else
{
echo 'User ' . ($openid->validate() ? $openid->identity . ' has '
: 'has not ') . 'logged in.';
}
}
catch(ErrorException $e)
{
echo $e->getMessage();
}
This question was asked but a big part wasn't answered due lack of testing
, the question is that why doesn't the login with google button be shown
after a login note : this is openid and will be redirected to google after
its shown and back to the page after logging to google but it doesn't show
the button after the login, reason ? for testing I have uploaded in
http://dota2tradebots.com/googlelogin.php
Remove time from embedded Google Calendar
Remove time from embedded Google Calendar
I was wondering if there is any way to remove the time infornt of the
events in a google calendar. http://i.imgur.com/PtA0CVQ.png
Because now the events are very poorly visible
I was wondering if there is any way to remove the time infornt of the
events in a google calendar. http://i.imgur.com/PtA0CVQ.png
Because now the events are very poorly visible
There is no alert when submitting a form using ajaxForm plugin
There is no alert when submitting a form using ajaxForm plugin
How can I have an alert that the form has been submitted successfully? I
have already tried to look at the page of the plugin still come up empty
handed.
This is the code I have tried so far maybe there is something wrong with
my syntax:
<script type="text/javascript">
$(document).ready(function(){
$('#f1').ajaxForm({
success: function(){
alert("Form successfully submitted");
}
});
});
</script>
The code above works and successfully inserted all the data in the forms
but the alert that suppose to appear after successfully submitted the form
is missing for some reason.
How can I have an alert that the form has been submitted successfully? I
have already tried to look at the page of the plugin still come up empty
handed.
This is the code I have tried so far maybe there is something wrong with
my syntax:
<script type="text/javascript">
$(document).ready(function(){
$('#f1').ajaxForm({
success: function(){
alert("Form successfully submitted");
}
});
});
</script>
The code above works and successfully inserted all the data in the forms
but the alert that suppose to appear after successfully submitted the form
is missing for some reason.
Saturday, 14 September 2013
How can I read a String from a file split it into characters and put it in to a 2D array?
How can I read a String from a file split it into characters and put it in
to a 2D array?
I am creating a program that simulates the function of a scantron marker.
I have a text file with the name of the student follow by their answers.
Here's the sample file I created:
Arnie EADCC Betty dadec Carol ba ea
In my main I ask the user to input the file name and I pass that to a
QuizMarker class that I created. Now I want to grab the name as a string
and put it into a 1D array and grab the answers as a character array and
put it into a 2D array so that I can compare the Student answers with a
correct answers file. I hard coded the number of rows just for testing
purposes. I have been trying to figure out how to make this work the whole
freaking day but my brain is completely toasted by now. I need HELP. here
is my code for the method readNamesAnswers():
public void readNamesAnswers(){
while (readerStu_Ans.hasNext()){
studentName[indexStudentName] = readerStu_Ans.nextLine();
for (int iRowStudentAnswer=0; iRowStudentAnswer<3;
iRowStudentAnswer++){
studentAnswers[iRowStudentAnswer]=
stuAnswers.split("(?!^)");
System.out.println(studentAnswers[iRowStudentAnswer][0]);
}
for(int row=0; row<3; row++){
for(int column= 0;
column<studentAnswers[column].length; column++){
System.out.println(studentAnswers[column][row]);
}}
System.out.println("\n"+studentName[indexStudentName]);
System.out.println();
indexStudentName++;
}
}
PS. I new to java and programming in general. Thanks in advance for all
the help.
to a 2D array?
I am creating a program that simulates the function of a scantron marker.
I have a text file with the name of the student follow by their answers.
Here's the sample file I created:
Arnie EADCC Betty dadec Carol ba ea
In my main I ask the user to input the file name and I pass that to a
QuizMarker class that I created. Now I want to grab the name as a string
and put it into a 1D array and grab the answers as a character array and
put it into a 2D array so that I can compare the Student answers with a
correct answers file. I hard coded the number of rows just for testing
purposes. I have been trying to figure out how to make this work the whole
freaking day but my brain is completely toasted by now. I need HELP. here
is my code for the method readNamesAnswers():
public void readNamesAnswers(){
while (readerStu_Ans.hasNext()){
studentName[indexStudentName] = readerStu_Ans.nextLine();
for (int iRowStudentAnswer=0; iRowStudentAnswer<3;
iRowStudentAnswer++){
studentAnswers[iRowStudentAnswer]=
stuAnswers.split("(?!^)");
System.out.println(studentAnswers[iRowStudentAnswer][0]);
}
for(int row=0; row<3; row++){
for(int column= 0;
column<studentAnswers[column].length; column++){
System.out.println(studentAnswers[column][row]);
}}
System.out.println("\n"+studentName[indexStudentName]);
System.out.println();
indexStudentName++;
}
}
PS. I new to java and programming in general. Thanks in advance for all
the help.
WPF Window ScaleTransform animation
WPF Window ScaleTransform animation
I have a Window in WPF that I want to display with ShowDialog and when the
window is displayed it should have a scaling animation. I have
successfully created the animation and all works great except one thing:
When the window approaches it's fully scaled state and the easing function
kicks in, the outer edges of the window seems to go beyond the actual
window bounds and get clipped. How can I use this scaling animation with
easing and not have it clipped?
This is the scaling animation I'm using:
<DoubleAnimation
Storyboard.TargetProperty="(Window.RenderTransform).(ScaleTransform.ScaleX)"
BeginTime="0:0:0.0" Duration="0:0:0.4" From="0" To="1">
<DoubleAnimation.EasingFunction>
<BackEase EasingMode="EaseOut" Amplitude="0.25" />
</DoubleAnimation.EasingFunction>
</DoubleAnimation>
<DoubleAnimation
Storyboard.TargetProperty="(Window.RenderTransform).(ScaleTransform.ScaleY)"
BeginTime="0:0:0.0" Duration="0:0:0.4" From="0" To="1">
<DoubleAnimation.EasingFunction>
<BackEase EasingMode="EaseOut" Amplitude="0.25" />
</DoubleAnimation.EasingFunction>
</DoubleAnimation>
I have a Window in WPF that I want to display with ShowDialog and when the
window is displayed it should have a scaling animation. I have
successfully created the animation and all works great except one thing:
When the window approaches it's fully scaled state and the easing function
kicks in, the outer edges of the window seems to go beyond the actual
window bounds and get clipped. How can I use this scaling animation with
easing and not have it clipped?
This is the scaling animation I'm using:
<DoubleAnimation
Storyboard.TargetProperty="(Window.RenderTransform).(ScaleTransform.ScaleX)"
BeginTime="0:0:0.0" Duration="0:0:0.4" From="0" To="1">
<DoubleAnimation.EasingFunction>
<BackEase EasingMode="EaseOut" Amplitude="0.25" />
</DoubleAnimation.EasingFunction>
</DoubleAnimation>
<DoubleAnimation
Storyboard.TargetProperty="(Window.RenderTransform).(ScaleTransform.ScaleY)"
BeginTime="0:0:0.0" Duration="0:0:0.4" From="0" To="1">
<DoubleAnimation.EasingFunction>
<BackEase EasingMode="EaseOut" Amplitude="0.25" />
</DoubleAnimation.EasingFunction>
</DoubleAnimation>
what does it mean when checking for external changes in netbeans shows "suspended"
what does it mean when checking for external changes in netbeans shows
"suspended"
I am new to netbeans and just added some remote repos with the team menu.
Now I keep seeing a "scanning for external changes" that is set to
"suspended" -- which then flicks to an intermittent progress bar. What
does "suspended" mean? Are my repos done downloading and now Netbeans is
just checking for any updates? I tried googling this and found a bunch of
bug reports for various failures related to "scanning for external
changes."
"suspended"
I am new to netbeans and just added some remote repos with the team menu.
Now I keep seeing a "scanning for external changes" that is set to
"suspended" -- which then flicks to an intermittent progress bar. What
does "suspended" mean? Are my repos done downloading and now Netbeans is
just checking for any updates? I tried googling this and found a bunch of
bug reports for various failures related to "scanning for external
changes."
Can I create windows on different threads with FLTK 1.3?
Can I create windows on different threads with FLTK 1.3?
I'm currently working on a sound signal visualizer. After getting the
signal, I need to plot both its waveform and spectrum on two different
windows.Thus I implemented a Plotter class, which creates its own thread
for each instance when constructed. But now I'm running into troubles
because many of FLTK's features seemed to be thread-unsafe, because it
crashes on some class method calls. (Such as set axis scale)
The model I'm using now:
Plotter 1 -> ctor() -> create thread
\
Plotter 2 -> ctor() -> create thread----> PlotterThread(Plotter*this) -
/ |
Plotter 3 -> ctor() -> create thread |
|
create fltk window
and init object
Is this model even practicable? I have no idea now... Thanks.
I'm currently working on a sound signal visualizer. After getting the
signal, I need to plot both its waveform and spectrum on two different
windows.Thus I implemented a Plotter class, which creates its own thread
for each instance when constructed. But now I'm running into troubles
because many of FLTK's features seemed to be thread-unsafe, because it
crashes on some class method calls. (Such as set axis scale)
The model I'm using now:
Plotter 1 -> ctor() -> create thread
\
Plotter 2 -> ctor() -> create thread----> PlotterThread(Plotter*this) -
/ |
Plotter 3 -> ctor() -> create thread |
|
create fltk window
and init object
Is this model even practicable? I have no idea now... Thanks.
i keep getting a Value error in python
i keep getting a Value error in python
I am new to programming and m just starting a GCSE in computer programming
I decided I would make a basic maths game. I started with this code.
#Callum Dashfield 12/09/2-13
print ("what is your name")
name = input ()
print ("hello " + name + " i am steve and this is my maths test. Are
you ready? Y/N")
answer_1 = input ()
answer_1 = int (answer_1)
if answer_1 ==Y:
print ("Good then lets get started")
else:
print ("well you have started now so to late lets go")
I went to test it and every time I do I get this.
what is your name
Callum
hello Callum i am steve and this is my maths test. Are you ready? Y/N
Y
Traceback (most recent call last):
File "C:\Users\callum\Documents\programming\maths test.py", line 6,
in <module>
answer_1 = int (answer_1)
ValueError: invalid literal for int() with base 10: 'Y'
>>>
Can anyone tell me what I have done wrong
I am new to programming and m just starting a GCSE in computer programming
I decided I would make a basic maths game. I started with this code.
#Callum Dashfield 12/09/2-13
print ("what is your name")
name = input ()
print ("hello " + name + " i am steve and this is my maths test. Are
you ready? Y/N")
answer_1 = input ()
answer_1 = int (answer_1)
if answer_1 ==Y:
print ("Good then lets get started")
else:
print ("well you have started now so to late lets go")
I went to test it and every time I do I get this.
what is your name
Callum
hello Callum i am steve and this is my maths test. Are you ready? Y/N
Y
Traceback (most recent call last):
File "C:\Users\callum\Documents\programming\maths test.py", line 6,
in <module>
answer_1 = int (answer_1)
ValueError: invalid literal for int() with base 10: 'Y'
>>>
Can anyone tell me what I have done wrong
sass @for directive - how to use steps in loops?
sass @for directive - how to use steps in loops?
in SASSS, this is very cool
@for $i from 1 through 100 {
//stuff
}
This would yield 1, 2, 3, 4....
but how would you make the loop go in intervals of two units?
something like
@for $i from 1 through 100 *step 2*{
//stuff
}
So the result is 1, 3, 5, 7....
I cannot find it in the documentation!
Thanks a lot in advance!
in SASSS, this is very cool
@for $i from 1 through 100 {
//stuff
}
This would yield 1, 2, 3, 4....
but how would you make the loop go in intervals of two units?
something like
@for $i from 1 through 100 *step 2*{
//stuff
}
So the result is 1, 3, 5, 7....
I cannot find it in the documentation!
Thanks a lot in advance!
too many nested calls to #Tcl_EvalObj (infinite loop?) ,got this error while executing a #tcl #recursive procedure..please tel me how to...
too many nested calls to #Tcl_EvalObj (infinite loop?) ,got this error
while executing a #tcl #recursive procedure..please tel me how to...
this proc is for traversing a hash map...and identify the connected nodes
proc search { search_var list_no } { global a;
set y $a($search_var)
if { [kernel_get_attribute $y property]=="flip_flop general"
} {
append list_no " " $y
search $y $list_no
}
set first [ lindex $list_no 0 ]
set last [ lindex $list_no [ expr [ llength $list_no ]
-1 ] ]
if { $first != " " } {
append $list_no " " $first
}
if { $last != " " } {
append $last " " $list_no
}
# puts "here"
} foreach i [array names a] { list $i $i search $i $i }
while executing a #tcl #recursive procedure..please tel me how to...
this proc is for traversing a hash map...and identify the connected nodes
proc search { search_var list_no } { global a;
set y $a($search_var)
if { [kernel_get_attribute $y property]=="flip_flop general"
} {
append list_no " " $y
search $y $list_no
}
set first [ lindex $list_no 0 ]
set last [ lindex $list_no [ expr [ llength $list_no ]
-1 ] ]
if { $first != " " } {
append $list_no " " $first
}
if { $last != " " } {
append $last " " $list_no
}
# puts "here"
} foreach i [array names a] { list $i $i search $i $i }
Friday, 13 September 2013
JQuery Autocomplete Custom Lookup Function
JQuery Autocomplete Custom Lookup Function
I want to use jquery.autocomplete.js plugin for an input in my form. I
want to search on the client side and can't use ajax. But I don't want
some simple "Contains"-based search algorithm within an array. What I want
to do is to write a custom search function in javascript to search and
order the results. Is this even possible and how?
Thanks for your time.
I want to use jquery.autocomplete.js plugin for an input in my form. I
want to search on the client side and can't use ajax. But I don't want
some simple "Contains"-based search algorithm within an array. What I want
to do is to write a custom search function in javascript to search and
order the results. Is this even possible and how?
Thanks for your time.
Calling a local WCF service via Scriptish or Greasemonkey
Calling a local WCF service via Scriptish or Greasemonkey
I'm trying to expose a local WCF service that checks to see if a file
exists in my database that can be accessed from a Scriptish script.
Is it possible to call a local URL from Scriptish or Greasemonkey? I've
created a WCF service hosted in IIS on my local machine, and the service
is working fine. However, when I try to call the service from Scriptish
the Network tab in Chrome/Firefox just says the following:
Request URL: http://localhost/service/service.svc/MatchPartial
Request Method: OPTIONS
Status code: 405 Method Not Allowed
Here is my ajax call:
$.ajax({
url: 'http://localhost/service/service.svc/MatchPartial',
type: 'POST',
contentType: 'application/json; charset=UTF-8',
dataType: 'json',
processData: true,
data: '{ "partialFilename": "testing" }',
success: function (result) {
console.log(result);
}
});
My method is decorated with:
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
public int MatchPartial(string partialFilename)
{
...
}
I have the following above my service class:
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
I've tried adding the following to my service with no luck:
[WebInvoke(Method = "OPTIONS", UriTemplate = "*")]
public void GetOptions()
{
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin",
"*");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods",
"POST, GET, OPTIONS");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers",
"Content-Type");
}
I feel like I've tried everything. Any help would be appreciated!
I'm trying to expose a local WCF service that checks to see if a file
exists in my database that can be accessed from a Scriptish script.
Is it possible to call a local URL from Scriptish or Greasemonkey? I've
created a WCF service hosted in IIS on my local machine, and the service
is working fine. However, when I try to call the service from Scriptish
the Network tab in Chrome/Firefox just says the following:
Request URL: http://localhost/service/service.svc/MatchPartial
Request Method: OPTIONS
Status code: 405 Method Not Allowed
Here is my ajax call:
$.ajax({
url: 'http://localhost/service/service.svc/MatchPartial',
type: 'POST',
contentType: 'application/json; charset=UTF-8',
dataType: 'json',
processData: true,
data: '{ "partialFilename": "testing" }',
success: function (result) {
console.log(result);
}
});
My method is decorated with:
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
public int MatchPartial(string partialFilename)
{
...
}
I have the following above my service class:
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
I've tried adding the following to my service with no luck:
[WebInvoke(Method = "OPTIONS", UriTemplate = "*")]
public void GetOptions()
{
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin",
"*");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods",
"POST, GET, OPTIONS");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers",
"Content-Type");
}
I feel like I've tried everything. Any help would be appreciated!
My Schema is not the same as my Database
My Schema is not the same as my Database
i'm new using Php Cake. I'm using version 1.3. width Mysql. So I had been
making some modifications in a web system. So, i had added a new column in
one of the tables, and when i try to save i had noticed the column didn't
appear in the schema. So i had run the console command "cake schema
generate" but in the schema.php generated file i don't see the column i
had added in the database, so i think that's the reason why was not
saving. So... How could i do to update this Schema... ?
Thank you in advance
i'm new using Php Cake. I'm using version 1.3. width Mysql. So I had been
making some modifications in a web system. So, i had added a new column in
one of the tables, and when i try to save i had noticed the column didn't
appear in the schema. So i had run the console command "cake schema
generate" but in the schema.php generated file i don't see the column i
had added in the database, so i think that's the reason why was not
saving. So... How could i do to update this Schema... ?
Thank you in advance
How to implement long polling in Java with Struts 2?
How to implement long polling in Java with Struts 2?
I want to implement long polling in a java web application. Basically,
when a user logs in, I want him to be hooked into a notification service.
I want to push out new notifications to him from the server as they occur,
and I want him to see those notifications in real time. ( so short polling
or periodically checking with server from the client aren't good enough).
How can I do this? Essentially, I want a way to push a string message from
the server, and for the client to receive it immediately.
I've heard some references that this could be done using a 'http chunk
transfer' header from the server. But how would that be set up on the
client?
I want to implement long polling in a java web application. Basically,
when a user logs in, I want him to be hooked into a notification service.
I want to push out new notifications to him from the server as they occur,
and I want him to see those notifications in real time. ( so short polling
or periodically checking with server from the client aren't good enough).
How can I do this? Essentially, I want a way to push a string message from
the server, and for the client to receive it immediately.
I've heard some references that this could be done using a 'http chunk
transfer' header from the server. But how would that be set up on the
client?
how to send value from view to template in javascript backbone
how to send value from view to template in javascript backbone
I have a jquery ajax post and when a user write and press enter in a
textbox this ajax triggers then it fetches a value from backend and show
the result in a <pre> html element. http://jsfiddle.net/LQg7W/2133/
obviuosly this jsfiddledoes not show anything because I sis not put the
ajax post inside it.
I want this text value have a default value when I load the page. like
"Enter your value:" but how can I send this value to the textbox which is
in template? So what I want to do is to send this defult value from my
view to template.
here is my view code when the user hit enter:
if(e.keyCode == 13) {
var currentLine = $('#terminal').text();
var inputData = $(e.currentTarget).val();
$('#terminal').text(currentLine + "\r\n" + inputData + "\r\n");
AjaxPost(inputData);
}
}
and this is how I render my template (textbox is inside this template)
this.$el.html(this.cliTerminalTemplate());
and this is my template:
<div class="row" id="box">
<div class="large-12 columns" >
<pre id="terminalPre" width="2">
<code id="terminal" style="color: #fff; padding: 1em;" ></code>
</pre>
<input type="text" id="textInput" name="" border: none;" autofocus>
</div>
</div>
I have a jquery ajax post and when a user write and press enter in a
textbox this ajax triggers then it fetches a value from backend and show
the result in a <pre> html element. http://jsfiddle.net/LQg7W/2133/
obviuosly this jsfiddledoes not show anything because I sis not put the
ajax post inside it.
I want this text value have a default value when I load the page. like
"Enter your value:" but how can I send this value to the textbox which is
in template? So what I want to do is to send this defult value from my
view to template.
here is my view code when the user hit enter:
if(e.keyCode == 13) {
var currentLine = $('#terminal').text();
var inputData = $(e.currentTarget).val();
$('#terminal').text(currentLine + "\r\n" + inputData + "\r\n");
AjaxPost(inputData);
}
}
and this is how I render my template (textbox is inside this template)
this.$el.html(this.cliTerminalTemplate());
and this is my template:
<div class="row" id="box">
<div class="large-12 columns" >
<pre id="terminalPre" width="2">
<code id="terminal" style="color: #fff; padding: 1em;" ></code>
</pre>
<input type="text" id="textInput" name="" border: none;" autofocus>
</div>
</div>
Is it possible to monitor a channel using Astersik AMI
Is it possible to monitor a channel using Astersik AMI
I am using asterisk I would like to debug a channel
I want to track the channel activities Like Dialing, Ringing, Call
established and Hangup etc
Is there any cli commands available ??? or any other way to do this
Thanks in advance
I am using asterisk I would like to debug a channel
I want to track the channel activities Like Dialing, Ringing, Call
established and Hangup etc
Is there any cli commands available ??? or any other way to do this
Thanks in advance
Thursday, 12 September 2013
Which technology to choose as mobile developer?
Which technology to choose as mobile developer?
As a Mobile Developer One can have many options to go with like,
1) Native App Development using iPhone or Android SDK
2) Platform independent App with Sencha or Jquery etc
3) Hybrid App development using Phonegap etc
Today Mobile development market is booming and there are lots of project
available.
Currently I am an iPhone developer. I want to ask one thing that As a
mobile developer, should I learn all these technologies or should I stick
with any one of them ? And Which one is the best of all this technologies
?
As a Mobile Developer One can have many options to go with like,
1) Native App Development using iPhone or Android SDK
2) Platform independent App with Sencha or Jquery etc
3) Hybrid App development using Phonegap etc
Today Mobile development market is booming and there are lots of project
available.
Currently I am an iPhone developer. I want to ask one thing that As a
mobile developer, should I learn all these technologies or should I stick
with any one of them ? And Which one is the best of all this technologies
?
Niceforms throw me ugly elements
Niceforms throw me ugly elements
I used NiceForms in my project intend to save my time on form's designing.
but when I applied the theme on my form, everything got changed. below is
the screenshot:
there are gray lines between button left and right, as well as text input
left and right. I have tested my page in firefox, chrome , IE 8, and found
that in firefox, the left side and the right side of the button and input
text are missing, in chrome and ie8, they are shown as above image.
here is my test html code:
<link href="Scripts/niceForms/niceforms-default.css" rel="stylesheet"
type="text/css" />
<script src="Scripts/niceForms/niceforms.js" type="text/javascript"></script>
<fieldset>
<legend>temperature functionality with jquery </legend>
<dl>
<dd><input type="button" id="Button2" value="Current Temperature" />
<input id="Text1" type="text" value="300" />
<div
style="width:109px;height:394px;background:url('Images/ThermometerMain.png')
no-repeat;position:relative; text-align:center">
<div id="temp"
style="width:10px;height:0px;margin-bottom:35px;background-color:Green;bottom:0;position:absolute;margin-left:52px;background:url('Images/ThermometerStep.png')
repeat-y;font-size:7pt;"></div>
</div>
</dd></dl>
</fieldset>
Any one can help me ? thx.
I used NiceForms in my project intend to save my time on form's designing.
but when I applied the theme on my form, everything got changed. below is
the screenshot:
there are gray lines between button left and right, as well as text input
left and right. I have tested my page in firefox, chrome , IE 8, and found
that in firefox, the left side and the right side of the button and input
text are missing, in chrome and ie8, they are shown as above image.
here is my test html code:
<link href="Scripts/niceForms/niceforms-default.css" rel="stylesheet"
type="text/css" />
<script src="Scripts/niceForms/niceforms.js" type="text/javascript"></script>
<fieldset>
<legend>temperature functionality with jquery </legend>
<dl>
<dd><input type="button" id="Button2" value="Current Temperature" />
<input id="Text1" type="text" value="300" />
<div
style="width:109px;height:394px;background:url('Images/ThermometerMain.png')
no-repeat;position:relative; text-align:center">
<div id="temp"
style="width:10px;height:0px;margin-bottom:35px;background-color:Green;bottom:0;position:absolute;margin-left:52px;background:url('Images/ThermometerStep.png')
repeat-y;font-size:7pt;"></div>
</div>
</dd></dl>
</fieldset>
Any one can help me ? thx.
Grab Body contents and wrap it within an element to show sort of like an iframe
Grab Body contents and wrap it within an element to show sort of like an
iframe
Ok, so I want all of the html within the body tag to be wrapped within a
<div class="wrap" /> that should be created on-the-fly. This code needs to
run from within the <body> tag itself, so am thinking we'll need to append
the code to the head or the first <script> tag and run it from there.
I want it to basically output the entire body contents into a div on that
same page, with scrollbars as needed ofcourse, so overflow: auto; and will
most likely need to use .wrapInner, but am not sure how to handle it
completely. I don't want to wrap any elements besides all elements within
the body tag. So it should than be inserted into a <div class="wrap" />
and will sort of mimic the idea of an iframe, but not exactly.
Any ideas or code would be greatly appreciated!
iframe
Ok, so I want all of the html within the body tag to be wrapped within a
<div class="wrap" /> that should be created on-the-fly. This code needs to
run from within the <body> tag itself, so am thinking we'll need to append
the code to the head or the first <script> tag and run it from there.
I want it to basically output the entire body contents into a div on that
same page, with scrollbars as needed ofcourse, so overflow: auto; and will
most likely need to use .wrapInner, but am not sure how to handle it
completely. I don't want to wrap any elements besides all elements within
the body tag. So it should than be inserted into a <div class="wrap" />
and will sort of mimic the idea of an iframe, but not exactly.
Any ideas or code would be greatly appreciated!
configure sql server 2008
configure sql server 2008
I tried to configure SQL Server 2008 Management Studio by using configure
tools and configure the firewall, but when I connect using SQL Server an
error occurs saying that you must configure or the name of local server is
incorrect.
I wrote my hostename/sqlexpress but even that didn't work. I followed this
video in this link but I found I do not have SQL Services as the video
does, I only have SQL Server agent(sqlexpress), SQL Server(sqlexpress) and
when I want to stat one of them it said:
computer can not start the SQL Server service on Local computer
What can I do?
I tried to configure SQL Server 2008 Management Studio by using configure
tools and configure the firewall, but when I connect using SQL Server an
error occurs saying that you must configure or the name of local server is
incorrect.
I wrote my hostename/sqlexpress but even that didn't work. I followed this
video in this link but I found I do not have SQL Services as the video
does, I only have SQL Server agent(sqlexpress), SQL Server(sqlexpress) and
when I want to stat one of them it said:
computer can not start the SQL Server service on Local computer
What can I do?
clone vs copying Array in Java?
clone vs copying Array in Java?
I have this bit of code, where I am making a copy of an array. using
System.arraycopy seems more verbose than clone(). but both give the same
results. are there any advantages of one over the other? here is the code:
import java.util.*;
public class CopyArrayandArrayList {
public static void main(String[] args){
//Array copying
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e'};
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 0, copyTo, 0, 7);
char[] copyThree = new char[7];
copyThree=copyFrom.clone();
}
}
I have this bit of code, where I am making a copy of an array. using
System.arraycopy seems more verbose than clone(). but both give the same
results. are there any advantages of one over the other? here is the code:
import java.util.*;
public class CopyArrayandArrayList {
public static void main(String[] args){
//Array copying
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e'};
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 0, copyTo, 0, 7);
char[] copyThree = new char[7];
copyThree=copyFrom.clone();
}
}
How Do I Change Output Resolution On Existing Image With RMagick/ImageMagick?
How Do I Change Output Resolution On Existing Image With RMagick/ImageMagick?
ImageMagick and RMagick both have a setting/attribute for "density", which
is what they call resolution. I can pass it a value of 200 and it should
set the resolution to 200x200 when the image is written to either a file
or to_blob.
In the Rails console I can load the image, then set the density, and if I
check it, it will tell me the density (originally 300x300) is now 200x200,
but when I write it out to a file, the resolution is 300x300.
The only way I've successfully been able to change the resolution is by
creating a new image of the same width and height, then overlay the
original image. This, however, distorts the output, no matter what
settings I use (I tried setting the original to fully opaque, the "new" to
fully transparent, and even used the CopyCompositeOperation, which should
fully replace the "new" image).
I have tried setting density like this: image.density = "200"
And like this image.write("test.jpg") {self.density="200"} And both.
Nothing works... any ideas?
ImageMagick and RMagick both have a setting/attribute for "density", which
is what they call resolution. I can pass it a value of 200 and it should
set the resolution to 200x200 when the image is written to either a file
or to_blob.
In the Rails console I can load the image, then set the density, and if I
check it, it will tell me the density (originally 300x300) is now 200x200,
but when I write it out to a file, the resolution is 300x300.
The only way I've successfully been able to change the resolution is by
creating a new image of the same width and height, then overlay the
original image. This, however, distorts the output, no matter what
settings I use (I tried setting the original to fully opaque, the "new" to
fully transparent, and even used the CopyCompositeOperation, which should
fully replace the "new" image).
I have tried setting density like this: image.density = "200"
And like this image.write("test.jpg") {self.density="200"} And both.
Nothing works... any ideas?
Accepting callbacks of arbitrary type
Accepting callbacks of arbitrary type
I'm trying to implement a JsonRpc client class in C# which executes a
given method / delegate / callback whenever the JsonRpc is responded (to
explain why I need the thing I'm going to ask).
To this end I want a method to register a callback of arbitrary type
(arbitrary argument list). This callback will be called / evaluated
whenever the response arrives. This means that at registration time
whatever the callback might be it is accepted and it's at execution time
which its type might cause an exception, once it is checked with
response's type.
I've seen codes implementing a similar concept like this:
//Defining a delegate based on a method signature
Delegate d = Delegate.CreateDelegate(delegate_type, context, methodInfo);
//Executing the delegate when response arrives
d.DynamicInvoke(parameters);
If I'm to implement the same, all I need to do is to accept an argument of
type Delegate for registering a callback. But this won't do for me since I
want it to be much easier to register a callback than creating its
Delegate (it takes a dozen of lines to come up with a Delegate of a
method).
At last here goes my question:
How would you implement registering a callback of arbitrary type in C#?
I'm trying to implement a JsonRpc client class in C# which executes a
given method / delegate / callback whenever the JsonRpc is responded (to
explain why I need the thing I'm going to ask).
To this end I want a method to register a callback of arbitrary type
(arbitrary argument list). This callback will be called / evaluated
whenever the response arrives. This means that at registration time
whatever the callback might be it is accepted and it's at execution time
which its type might cause an exception, once it is checked with
response's type.
I've seen codes implementing a similar concept like this:
//Defining a delegate based on a method signature
Delegate d = Delegate.CreateDelegate(delegate_type, context, methodInfo);
//Executing the delegate when response arrives
d.DynamicInvoke(parameters);
If I'm to implement the same, all I need to do is to accept an argument of
type Delegate for registering a callback. But this won't do for me since I
want it to be much easier to register a callback than creating its
Delegate (it takes a dozen of lines to come up with a Delegate of a
method).
At last here goes my question:
How would you implement registering a callback of arbitrary type in C#?