text:
Q: Intermittent connectivity to a SunOS 4.1.4 virtual machine I am running SunOS 4.1.4 (those were the days...) under QEMU, networked via a tap device on the host. I'm starting the vm like this...
qemu-system-sparc \
    -rtc base=utc \
    -drive file=sunos-root.img,format=raw,bus=0,unit=0 \
    -drive file=sunos-home.img,format=raw,bus=0,unit=1 \
    -drive file=sunos-gnu.img,format=raw,bus=0,unit=2 \
    -nic tap,br=virbr0,helper=/usr/libexec/qemu-bridge-helper \
    -nographic

...and everything works great, except for networking, which seems to work only sporadically.
When SunOS comes up, it is running, among other things, a telnet server and and rshell server via inetd. The tap interface is attached to bridge virbr0 (192.1681.22.1), and the SunOS vm is assigned 192.168.122.103:
bash-3.2# ifconfig le0
le0: flags=63<UP,BROADCAST,NOTRAILERS,RUNNING>
        inet 192.168.122.103 netmask ffffff00 broadcast 192.168.122.255
        ether 52:54:0:12:34:56

If I'm lucky, I can simply  telnet 192.168.122.103 (or rsh) from the host and it Just Works. Other times, it doesn't, and I can't figure out why. If I run this in a loop...
while ! rsh -l root 192.168.122.103 /bin/true; do
  sleep 1
done

...it will eventually work.
Outbound traffic from the virtual machine always works (I can, e.g., reliably telnet 192.168.122.1 22 to get the SSH-2.0-OpenSSH... banner from my host). Running tcpdump on the tap interface when failing to telnet to the vm, I see:
18:39:07.584861 IP 192.168.122.1.40270 > 192.168.122.103.telnet: Flags [S], seq 2038492576, win 64240, options [mss 1460,sackOK,TS val 2376785260 ecr 0,nop,wscale 7], length 0
18:39:07.585177 IP 192.168.122.103.telnet > 192.168.122.1.40270: Flags [S.], seq 2034944001, ack 2038492577, win 4096, options [mss 1460], length 0
18:39:07.585205 IP 192.168.122.1.40270 > 192.168.122.103.telnet: Flags [.], ack 1, win 64240, length 0
18:39:07.585279 IP 192.168.122.1.40270 > 192.168.122.103.telnet: Flags [P.], seq 1:28, ack 1, win 64240, length 27 [telnet DO SUPPRESS GO AHEAD, WILL TERMINAL TYPE, WILL NAWS, WILL TSPEED, W
ILL LFLOW, WILL LINEMODE, WILL NEW-ENVIRON, DO STATUS, WILL XDISPLOC [|telnet]
18:39:07.773325 IP 192.168.122.103.telnet > 192.168.122.1.40270: Flags [.], ack 28, win 4069, length 0
18:39:10.323018 IP 192.168.122.1.40270 > 192.168.122.103.telnet: Flags [P.], seq 28:30, ack 1, win 64240, length 2
18:39:10.373287 IP 192.168.122.103.telnet > 192.168.122.1.40270: Flags [.], ack 30, win 4067, length 0
18:39:11.401927 IP 192.168.122.1.40270 > 192.168.122.103.telnet: Flags [P.], seq 30:32, ack 1, win 64240, length 2
18:39:11.573256 IP 192.168.122.103.telnet > 192.168.122.1.40270: Flags [.], ack 32, win 4065, length 0
18:39:12.672424 IP 192.168.122.1.40270 > 192.168.122.103.telnet: Flags [P.], seq 32:34, ack 1, win 64240, length 2
18:39:12.773266 IP 192.168.122.103.telnet > 192.168.122.1.40270: Flags [.], ack 34, win 4063, length 0

So you can see that there appears to be traffic passing back and forth, but it's still not working. This is what it looks like when things are successful:
18:41:38.435167 IP 192.168.122.1.40282 > 192.168.122.103.telnet: Flags [S], seq 404147648, win 64240, options [mss 1460,sackOK,TS val 2376936111 ecr 0,nop,wscale 7], length 0
18:41:38.435489 IP 192.168.122.103.telnet > 192.168.122.1.40282: Flags [S.], seq 2054336001, ack 404147649, win 4096, options [mss 1460], length 0
18:41:38.435525 IP 192.168.122.1.40282 > 192.168.122.103.telnet: Flags [.], ack 1, win 64240, length 0
18:41:38.435585 IP 192.168.122.1.40282 > 192.168.122.103.telnet: Flags [P.], seq 1:28, ack 1, win 64240, length 27 [telnet DO SUPPRESS GO AHEAD, WILL TERMINAL TYPE, WILL NAWS, WILL TSPEED, W
ILL LFLOW, WILL LINEMODE, WILL NEW-ENVIRON, DO STATUS, WILL XDISPLOC [|telnet]
18:41:38.459878 IP 192.168.122.103.telnet > 192.168.122.1.40282: Flags [P.], seq 1:4, ack 28, win 4069, length 3 [telnet DO TERMINAL TYPE [|telnet]
18:41:38.459971 IP 192.168.122.1.40282 > 192.168.122.103.telnet: Flags [.], ack 4, win 64237, length 0
18:41:38.460564 IP 192.168.122.103.telnet > 192.168.122.1.40282: Flags [P.], seq 4:34, ack 28, win 4096, length 30 [telnet WILL SUPPRESS GO AHEAD, DONT NAWS, DONT TSPEED, DONT LFLOW, DONT LI
NEMODE, DONT NEW-ENVIRON, WONT STATUS, DONT XDISPLOC, SB TERMINAL TYPE SEND SE [|telnet]

You can see that this time the Telnet protocol exchange compltes successfully.
It's not a firewall issue (I added a -j ACCEPT rule at the top of the INPUT chain, there are no restrictions on OUTPUT, and this traffic won't hit the FORWARD chain).
Maybe the QEMU lance ethernet driver is just buggy?


text:
Q: How do I resolve webpage encoding issues when using a proxy? Unless I disable proxy, webpages show up as characters like
|ˆSš˜mð{ýîsqÐ|0MVà|ð|}}}0}@}P}`}p}€}P} }°}À}Ð}à}ð}~~ ~0~@~P~`~p~€~P~ ~°~À~Ð~à~€€ €0€@€P€`€p€€€P€ €°€À€Ð€à€ð€AA A0A@APA`ApA€APA A°AÀAÐAàAðA''

or else as a .bin file available for download. For example https://dpaste.de/epVx is what http://stumblingandmumbling.typepad.com/stumbling_and_mumbling/2014/03/ex-growth.html looks like if I go through the system proxy.

If I use w3m through an ssh connection then webpages display fine. TTYtter works fine. vlc can even play the same youtube video at the same time as firefox can't load the site. I infer from this that those programs must use proxies differently.
Once I change the proxy from "system default" to "none" this problem goes away in Firefox. Aliasing w3m to w3m -no-proxy works for naked w3m but not in wrappers like surfraw. However, curl and by extension R still can't fetch data—and even sudo apt-get install is having problems.
I'm not even sure where the system default proxy settings are coming from. If I try to google about it I end up being directed to squid -- which I'm not sure is what I want.

A: The problem was that I had installed anon-proxy but not configured it. anon-proxy uses 127.0.0.1:4001. So either configure it or kill it.

*

*How to configure anon-proxy.

*To kill it use sudo su; netstat -tlp to find the process number of mix (it's called an anonymous mix for some reason) and then from su issue kill -9 to the process id number.

*If killing doesn't work, then don't just sudo apt-get remove anon-proxy; also sudo apt-get purge anon-proxy; this will unset shell variables like $HTTP_PROXY and some files in /etc/ or /var/ that it may have changed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: standardised random variable least square regression $X$ against $Y$, $Y$ against $X$ Let $X$ and $Y$ be mean 0 and variance 1 random variables such that we choose $\alpha$ and $\beta$ to minimise
$$\mathbb{E}(X-\beta Y)^2$$
and
$$\mathbb{E}(Y-\alpha X)^2$$
after not so difficult derivation, I arrive at $\alpha = \mathbb{E}(XY)/\mathbb{E}X^2$ and $\beta = \mathbb{E}(XY)/\mathbb{E}Y^2$, so $\alpha = \beta$.
This seems very strange, because if $y=mx$ is regression line, then surely $x = \frac{1}{m }y$.

A: So I will answer my own question. The reason the two regression lines are different is this:
The regression line of $Y$ against $X$ minimises the total squared distance of the $Y$ COORDINATES to the $y$ COORDINATES of the line, where as $X$ against $Y$ minimise the total squared distance of $X$ COORDINATES to the $x$ COORDINATES line.
The confusion I had with regards to the line should be unique comes from the mistaken assumption the regression line minimise the total squared (PERPENDICULAR) distance of each point to the regression line. If this had been the case, my assumption would have been true. However, the two measure of distance never coincide unless there is perfect correlation.


text:
Q: Restoring a postgres database hangs - with no error I'm currently trying to restore a database from a backup created by pg_dump (which is small ~100mb) from a tar file.
However attempting to restore with
pg_restore -U postgres -f "example.tar"
just keeps hanging and never seems to work.
What's the best way to try to diagnose and fix the issue?

A: It's waiting for input on stdin.
-f specifies an output file, not an input file. With no input it's waiting for input on stdin. If you type ctrl-d to end input it will say something like pg_restore: error: input file is too short (read 0, expected 5).
The proper invocation is...
pg_restore --dbname=DatabaseName -Upostgres --format=tar example.tar

--dbname is the name of the database to restore to. If it does not exist, add --create to tell pg_restore to create it.
The --format=tar is not strictly necessary, pg_restore can guess the file type, but why risk it?
See the pg_restore docs.


text:
Q: How to access the global environment in R using rpy2 in Python? I am trying to access a dataframe from R global environment and import it into Python in Pycharm IDE. But, I am not able to figure how to do it.
I tried the following:
Since, I don't know how to access the global environment where my target data.frame is stored. I created another R script (myscript.R) where I converted to data.frame into a rds object and called it again.
save(dfcast, file = "forecast.rds")
my_data <- readRDS(file = "forecast.rds")

However, when I try to read the rds in python using the following code in Python:
import os
import pandas as pd
import rpy2.robjects as robjects
from rpy2.robjects import pandas2ri
from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage

cwd = os.getcwd()
pandas2ri.activate()
os.chdir('C:/Users/xx/myscript.R')
readRDS = robjects.r['readRDS']
df = readRDS('forecast.rds')
df = pandas2ri.ri2py(df)
df.head()

I get the following error:
Error in gzfile(file, "rb") : cannot open the connection
In addition: Warning message:
In gzfile(file, "rb") :
  cannot open compressed file 'forecast.rds', probable reason 'No such file or directory'

Please show the way to deal with this. I just want to access a data.frame from R in Python.
The data.frame is actually a forecast generated from another R script which takes about 7-8 minutes to run. So, instead of running it again on Python , i want it to process in R and import the forecast dataframe to python for further analysis. Since, I am in the midst of building further analysis module. I don't want the R forecast function to run again and again while I am debugging my analysis module. Hence, I want to directly access it from R.


text:
Q: Split the height of the screen to body and footer I need to split the screen to 2: body (around 90% of the screen) and footer (around 10% of the screen - fixed on bottom).
The footer should be transparent and the body should have a lot of text so would be a vertical scroll bar.
My problem is that the body's height isn't 90% of the height (but 100%) so I can see the text behind my footer.
How can I fix it?
Here's JSFiddle that shows my problem.
And the code:
HTML:

    texttext
text
text

    this is footer

CSS:
#body{
  height:80%;
}

#footer{
    width:100%;
    height:30px;
    position:fixed;
    bottom:0;
    left:0;
    color: blue;
    text-align: center;
    background: red;
    opacity: .5;
}

Thank you

A: Change your heights accordingly, but all you need is (CSS):
html, body {
    height: 100%;
}

#body {
    overflow: scroll;
}

Fiddle: https://jsfiddle.net/96jfew5s/4/

A: Use Viewport units: vw, vh, vmin, vmax

*{box-sizing: border-box}
body{
  margin: 0
}

#body{
  height: 90vh
}

#footer{
    height:10vh;
    color: blue;
    text-align: center;
    background: red;
    opacity: .5;
}

#body,#footer{
  display: block;
  overflow-x:hidden;
  overflow-y: scroll

}

    texttext
text
text

    this is footer

A: You have to set your parent (html and body tags) also to 100% of the height because if not you cannot set percentages to their childs (they try to get the percentage of their parents). Then, you can set your overflow-y: auto; to get the scroll in your body div.
Also, change the appropiate height to both body and footer divs.
Note: I would recommend you to change the name of your body div to other name that will not be related with reserved words to avoid confusions.

html, body{
  height: 100%;
  height: 100%;
  width: 100%;
  margin: 0;
}

#body{
  height:90%;
  max-height: 90%;
  overflow-y: auto;
}

#footer{
  width:100%;
  height:10%;
  position: fixed;
  bottom:0;
  left:0;
  color: blue;
  text-align: center;
  background: red;
  opacity: .5;
}

text
text
text
text
text
text
text
text
text
text
text
text
text
text
text
text
text
text
text
text
text
text
text
text
text
text

this is footer


text:
Q: Search for pattern and print them above certain pattern everytime If data i have is in below format
cell D
type seq
Cd
Input
Cp
Input
Q
Output
Func IQ
Sdn
Input
cell 23
----

I want output as I.e in cell , input, output,function , type format.
cell D
Cd
Input
Cp
Input
Sdn
Input
Q
Output
Func IQ
type seq
cell 23
---

I.e Func and type should come everytime before cell i.e at last.
I dont have any logic how to do it.
In the above output I want when ever there is type and funct in input I want it to be printed at last above cell line. --- for cell 23 represents data for this cell same as cell D format.

A: Could you please try following, based on shown samples only written in GNU awk. This is considering that cell is coming each time in blocks and if cell is not coming in very last occurrence in Input_file then those values will not be printed(you could print them in END block then in case you need those values too, left as an exercise for OP).
awk '
/^cell/{
  if(funcVal){
    print funcVal
  }
  if(typeVal){
    print typeVal
  }
  funcVal=typeVal=""
}
/^Func/{
  funcVal=(funcVal?funcVal ORS:"")$0
  next
}
/^type/{
  typeVal=(typeVal?typeVal ORS:"")$0
  next
}
1' Input_file

Explanation: Adding detailed explanation for above.
awk '                                   ##Starting awk program from here.
/^cell/{                                ##Checking if a line starts from cell then do following.
  if(funcVal){                          ##Checking if funcVal is NOT NULL then do following.
    print funcVal                       ##printing funcVal here.
  }
  if(typeVal){                          ##Checking if typeVal is NOT NULL then do following.
    print typeVal                       ##Printing typeVal value here.
  }
  funcVal=typeVal=""                    ##Nullifying values here.
}
/^Func/{                                ##Checking if line starts from Func then do following.
  funcVal=(funcVal?funcVal ORS:"")$0    ##Creating funcVal and keep adding value of current line to it.
  next                                  ##next will skip all further statements from here.
}
/^type/{                                ##Checking if line starts from type then do following.
  typeVal=(typeVal?typeVal ORS:"")$0    ##Creating typeVal and keep adding value of current line to it.
  next                                  ##next will skip all further statements from here.
}
1                                       ##Mentioning 1 will print current line.
' Input_file                            ##Mentioning Input_file name here.


text:
Q: How to verify stripe webhook signatures without endpoint secret? I'm building a "multiplatform" solution where each user could have it's "shop" and receive the founds directly on their stripe accounts.
So each user when creates it's shop provides public and secret stripe key which are stored on the server and used when some payments are made.
The problem comes when i have to use the webhooks where i have to verify the user webhook endpoint secret, i can't ask the users to provide and store the WH endpoint key...
(I use the webhook to send the order in preparation once the payment charge is succeeded)
So i was wondering if there was a way to manually verify the webhook signature without using the endpoint secret, i saw that here is possible manually verify signature but anyway i have to use the endpoint's signing secret as key..

A: It's not possible to verify Stripe webhook event payloads without a webhook signing secret.
However, it sounds like your use case fits Connect quite well, and a Connect webhook endpoint may work for your needs.
Connect webhooks will receive events from all connected accounts, and will avoid the need to manage individual webhook endpoints and secrets for each account.


text:
Q: Using Win32 API in Qt OSE project It is a messy question, hopefully you can figure out what I want :)
What is the best way to use Win32 functionality in a Qt Open Source Edition project?
Currently I have included the necessary Windows SDK libraries and include directories to qmake project file by hand. It works fine on a small scale, but its inconvenient and cumbersome.
So, should I separate the Win32 stuff into a library or is there a sensible way of combining these two? Or have I just overlooked some Qt aspect that simplifies this?
EDIT
Removed the syntax stuff, its not really relevant, just annoying.

A: You could build an interface layer to wrap the Win32 functionality and provide it in a DLL or static library. The DLL would minimize the need for linking directly to the Win32 libraries with your qmake project. It would be more in keeping with the portability of Qt to create generic interfaces like this and then hide the platform specific data in a private implementation. Trolltech has typically employed the pimpl idiom to accomplish such tasks. So, take a look at the Qt source code to see examples (i.e. look for the "d" pointers).

A: LPCWSTR should not be a problem; that's just a stupid name for wchar_t const*. LPARAM is not a problem either, you can store them in a long. Sure, those are just C++ types, not Qt. But Qt can still handle them.
VS integration, as I understand it is related to the Visual Studio IDE, not the (V)C++ language.

A: You could use win32 scopes in your .pro file;
win32:HEADERS+=mywinheader.h

or with .pri (pro include) files to compartmentalize it even more;
win32:include( mywinpri.pri )

You would typically use this apprpoach with the PIMPL idiom as monjardin describes


text:
Q: Intercepting the browser's basic authorization popup with nginx I am trying to intercept the basic popup with nginx and stuck at the user password.
I have a landing page where users would insert a username/password and the form gets posted to http://localhost/validate.
The following is the block that I got, If I hardcode the base64 encoded username:password, things are working but to do it in a programaticaly its not working.
location /validate/
{
set_form_input $username;
set_form_input $password;
set $auth_raw "$username:$password";
set_encode_base64 $digest $auth_raw; # $digest = some_hash_value

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Authorization "Basic <<<some_hash_value>>>"; # This works
#proxy_set_header Authorization "Basic $digest"; # This does not work
proxy_pass http://localhost:5601/;

}

As shown above,
Hardcoding the hash value allows me to bypass the basic authentication popup:
proxy_set_header Authorization "Basic <<<some_hash_value>>>";

But assigning it using a variable does not work:
proxy_set_header Authorization "Basic $digest";

Just by the looks of it, I am unable to dynamically assign the required values for proxy_set_header Authorization.
In short I want to be able to do the following,

*

*User enters username & password on a page & hit submit.

*Data get's posted to http://localhost/validate

*Nginx sees the request on /validate and start to process the form values and compose the URL (base64 encoded equivalent)     http : //username:password@localhost:5601

*Server listing on port 5601 sees the username/password and authenticates the user and let the user in.

What am I doing wrong here? Or is there a better way to handle this with nginx?

A: The form submission URL (action attribute) is missing the trailing slash.
Upon form submission POST request is made to /validate which causes nginx to respond with a redirect to /validate/. The browser foIlows the redirect by issuing a GET request which does not contain the original data. Effectively the nginx rules receive empty credentials.
The solution is to add trailing slash to the <form> element's action attribute so it looks like: action="http://localhost/validate/".


text:
Q: Text validation in Windows form Anyone please help, for text validation.
One field will be input for one Id.
Id should be "N######" where # is numbers.
Please let me know how to put it under validation when button is clicked.

A: Try this code :
private void button1_Click(object sender, System.EventArgs e)
{
    if (!System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[Nn]+[\d]+$"))
    {
         MessageBox.Show("Please enter valid input");
         return;
    }
}


text:
Q: Web starter kit & php how can I use php files using the Google web starter kit? I discovered today the Web-Starter-Kit from Google and I'm trying to get familiar with it. It works great but now I add some php code into the basic.html file and it does show in the preview file but in the /dist/ directory where the final code awaits it doesn't appear.
My question is how can I use php files using the Google web starter kit?

A: You should use files with extension (.php) for writing PHP code. Try changing basic.html to basic.php

A: Nope.
You should design the layout as normal html5 and css3 pages. Then make those static dynamic pages by replacing with php code.
Design different layout as static html pages first and then convert it to dynamic websites an easy way.


text:
Q: What is considered good programming practice in multi-threaded winform applications with delegate usage? I'm modifying an application written in C# that makes heavy-use of multi-threading to play audio files and display images to a user. Given that it is multi-threaded, I need to use the Invoke method often to change form elements. I'm running into a pattern that I'm not very comfortable with, where I find myself writing frequent, small, delegate methods that typically only do one thing. An example of this is as follows:
delegate void setImageCallback(Image img);
private void setImage(Image img)
{
    this.pictureBox1.Image = img;
}

private void someOtherMethod()
{
    ...
    if (this.pictureBox1.InvokeRequired)
    {
        this.Invoke(new setImageCallback(setImage), Image.FromFile("example.png");
    }
    else
    {
        this.pictureBox1.Image = Image.FromFile("example.png");
    }
    ...
}

How do people generally handle these situations, so that you don't find yourself writing an absurd number of delegates and methods just to remain thread-safe? Obviously, consolidation of similar methods is great, but if I potentially need to update every form element on my form, I don't want to have a "modify" delegate and method for each of these.
Thanks.

A: A good example is here.
this.BeginInvoke( (Action) (()=>
    {
        pictureBox1.Image = Image.FromFile("example.png");
    }));

A: You definitely don't need a separate delegate for each.  You can use Action delegates and lambda expressions to simplify it, like this:
private void SomeOtherMethod()
{
    Action action = () => pictureBox1.Image = Image.FromFile("example.png");
    if (pictureBox1.InvokeRequired)
    {
        Invoke(action);
    }
    else
    {
        action();
    }
}

Or you can separate out the if statement and InvokeRequired check and generalize it even more, like this:
public static void InvokeIfRequired(Control control, Action action)
{
    if (control.InvokeRequired)
    {
        control.Invoke(action);
    }
    else
    {
        action();
    }
}

private void SomeOtherMethod()
{
    InvokeIfRequired(() => pictureBox1.Image = Image.FromFile("example.png");
}

A: I would use the MethodInvoker type in conjunction with an anonymous method or lambda expression. I would also build the invocation logic into the method itself, rather than using a separate thread-safe method:
void SomeMethod(/* with whatever args */) {
    if (InvokeRequired)
        Invoke(new MethodInvoker(() => SomeMethod(/* args used to call method */)));
    else
        // the method body itself
}


text:
Q: HowTo Create First Viewcontroller Button Click to Call Second Viewcontroller Method Using Objective C? I am trying to create first viewcontroller button click to call second viewcntroller method without any navigation. I mean need to stay first view controller but need to cal method only on second viewcontroller and print there some NSLog.

A: Simply try this:
Second View Controller :
-(void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doClickIt:) name:@"notificationName" object:nil];
}

-(void)doClickIt:(NSNotification*)notification {
}

First View Controller:
On Button click IBAction method called:
-(IBAction) someMethod3:(id) sender{
[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:obj];
}

Thats it.
Hope it will help you.

A: If I understand your question right you could do the following:
In your firstviewcontroller:
#import "secondviewcontroller.h" - (Or the name of the viewcontroller)

In the (IBAction) method do the following:
Secondviewcontroller *sec = [Secondviewcontroller alloc]init]
[sec theMethod];

Then it will get called.
Can i ask, how come you want to call an action from a non-active viewcontroller?

A: Try Following:
In ViewControllerA.h declare a method.
In ViewControllerA.m Define a method.
like below:
-(NSMutableArray*) MethodOfA;

In ViewControllerB.h:
#import "ViewControllerA.h"
  .......
 @property (nonatomic, strong) ViewControllerA * viewControllerA;
 @property (nonatomic, strong) NSMutableArray * mutableArray;

In ViewControllerB.m:
in your Button action add below code:
self.mutableArray =[self.viewControllerA MethodOfA];


text:
Q: Custom Add to Cart With Products Custom Atribute In Magento I have tried to add the products to cart using custom module. Below is the code i used
    $product_id = $this->getRequest()->getParam('product');

    $product = Mage::getModel('catalog/product')->load($product_id);

    $param = array( 'product' => $product->getId(), 'qty' => 2,'options["'.$option_id.'"]' => $option_type_id );

  $cart = Mage::getModel('checkout/cart')->init();
  $cart->addProduct($product, new Varien_Object($param));
  Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
  $cart->save();

I can add the products name, quantity to cart using product id, But i cannot able to add the products custom options in cart.
Please give me a hand on this.
Thanks,
Prakash

A: You're so close! The main thing that you need to change is your $param, as it is not structured the way Magento would like. This should do the trick:
$param = array(
    'product' => $product->getId(),
    'qty' => 2,
    'options' => array(
                        $option_id => $option_value,
                        $option_id2 => $option_value2,
                      ),
);

Note that any required custom options on your product will need to have values to avoid a fatal error whilst adding to the cart. Also, no need to cast $param as a Varien_Object - Magento understands the array just fine.


text:
Q: no known conversion for argument 3 from 'void (MyClass::*)()' to 'void (*)()' when instantiating in constructor Supposedly a much asked question but I can't find any solutions searching high and low. I've come quite a bit, changing the way the members are declared and instantiating the Task object in the constructor now, but not there yet (and while I mostly know what I'm doing, I don't know the proper terms for many words - too new to this game).
In the actual script there are multiple such Task objects, all giving basically the same error message.
I'm trying to instantiate one class into another, and the problem is that I have to pass back a function.
The header file:
#ifndef HYDROMONITORMASTER_H
#define HYDROMONITORMASTER_H

#include <TaskScheduler.h>

class HydroMonitorMaster
{
  public:
    HydroMonitorMaster (void);

  private:
    void readSensors(void);
    Scheduler ts;
    Task tReadSensors;
};
#endif

The .cpp file:
#include <HydroMonitorMaster.h>

HydroMonitorMaster::HydroMonitorMaster() : tReadSensors(10*1000, TASK_FOREVER,  &HydroMonitorMaster::readSensors, &ts, false) {}

void HydroMonitorMaster::readSensors() {}

And finally of course the error message that I get:
Arduino: 1.8.1 (Linux), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 230400, 4M (3M SPIFFS)"

/home/wouter/Arduino/libraries/HydroMonitor/src/HydroMonitorMaster.cpp: In constructor 'HydroMonitorMaster::HydroMonitorMaster()':
/home/wouter/Arduino/libraries/HydroMonitor/src/HydroMonitorMaster.cpp:3:125: error: no matching function for call to 'Task::Task(int, int, void (HydroMonitorMaster::*)(), Scheduler*, bool)'
 HydroMonitorMaster::HydroMonitorMaster() : tReadSensors(10*1000, TASK_FOREVER,  &HydroMonitorMaster::readSensors, &ts, false) {}
                                                                                ^
/home/wouter/Arduino/libraries/HydroMonitor/src/HydroMonitorMaster.cpp:3:125: note: candidate is:
In file included from /home/wouter/Arduino/libraries/HydroMonitor/src/HydroMonitorMaster.h:4:0,
                 from /home/wouter/Arduino/libraries/HydroMonitor/src/HydroMonitorMaster.cpp:1:
/home/wouter/Arduino/libraries/TaskScheduler-master/src/TaskScheduler.h:347:1: note: Task::Task(long unsigned int, long int, void (*)(), Scheduler*, bool, bool (*)(), void (*)())
 Task::Task( unsigned long aInterval, long aIterations, void (*aCallback)(), Scheduler* aScheduler, bool aEnable, bool (*aOnEnable)(), void (*aOnDisable)() ) {
 ^
/home/wouter/Arduino/libraries/TaskScheduler-master/src/TaskScheduler.h:347:1: note:   no known conversion for argument 3 from 'void (HydroMonitorMaster::*)()' to 'void (*)()'
exit status 1

The real issue appears to be in the end of the error: no known conversion for argument 3 from 'void (HydroMonitorMaster::*)()' to 'void (*)()' And I have no idea how to accomplish this.


text:
Q: Silverlight 4 - send text to Notepad I try this tutorial
http://elegantcode.com/2010/02/20/silverlight-4-com-interop-and-the-cool-stuff-you-can-do-with-it/
I need open Notepad and send text into. I use this code:
using (dynamic shell = AutomationFactory.CreateObject("WScript.Shell"))
    {
        shell.Run(@"C:\windows\notepad.exe"); //you can open anything

        shell.SendKeys(txtTextToSend.Text);
    }

When I start aplication the notepad has appeared but there is no text in it.
What do I wrong. My system is W7 64bit.
Thanks

A: The problem is that Run is a non-blocking operation that will return as soon as it has spun up the process.  The UI for notepad probably hasn't appeared and put the focus into its input area by the time your code is calling SendKeys.
Try introducing a Thread.Sleep for a couple of seconds to prove whether this is true.


text:
Q: Is it possible to extract Global.asax into a common library outside of the websites bin directory? Using the solution in this question, I moved my MvcApplication logic to a SharedHttpApplication class in my common library that inherits from HttpApplication.
In my asp.net mvc 3 project, I have my Global.asax MvcApplication inherit from my SharedHttpApplication.
My common library Assembly lives on the server file system in a standard location, and I am trying to prevent having to copy local to keep it in one place.
I am not getting a parser error for line one of my Global.asax page. I've read this is because the DLL containing the application is not in the bin directory.
Does anyone have a solution for what I'm trying to do here?
Thanks in advance for any help!

A: The only way I believe you can do what you're talking about it by installing the shared DLL to the GAC. That will make it accessible to anything on the server. If you don't care about the security implications of that, then that could be the way to go.
http://msdn.microsoft.com/en-us/library/dkkx7f79.aspx
Otherwise, copying the dll to each of the application's bin folders is not really bad practice, as long as you have a good deployment strategy in place for that.


text:
Q: Using Xml add Home Icon in ToolBar and resize it I am trying to add an icon in place of Title icon (the leftmost icon) on ToolBar  Using XML .. tried several ways (android:logo, android:icon in manifest) unfortunately no success.
Is there any way to add icon, resize the icon & add spacing between icon and title using only xml on ToolBar?
This is my toolbar_e.xml

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    app:titleTextAppearance="@style/Toolbar_e.TitleText" />

This is in my styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="windowActionModeOverlay">true</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowActionBar">false</item>
        <item name="colorPrimary">@color/ColorPrimary</item>
        <item name="colorPrimaryDark">@color/ColorPrimaryDark</item>
        <item name="android:textColorPrimary">@color/textColorPrimary</item>

    </style>

    <style name="Toolbar_e.TitleText"   parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
        <item name="android:textSize">16sp</item>
    </style>

This is my Manifest

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".Splash"
            android:configChanges="keyboardHidden|orientation"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

A: Here you can add view inside ToolBar and
set ImageButton android:layout_gravity according to your need
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbarxmlns:android="http://schemas.android.com/apk/res/android"
style="@style/ToolBarStyle"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:paddingRight="12dp"
android:paddingEnd="12dp"
android:background="@color/black"
android:minHeight="@dimen/abc_action_bar_default_height_material" >

<ImageButton
    android:id="@+id/btnHome"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end"
    android:background="@drawable/btn_menu" />

</android.support.v7.widget.Toolbar>


text:
Q: What is the preferred way of getting value in swift, var vs. func? What's the preferred way of getting a value in swift?
Using a read-only variable
var getString: String? {
    return "Value"
}

or using a function?
func getString() -> String? {
    return "Value"
}

Also, is there a performance difference between the two?

A: First, neither of these would be appropriate names. They should not begin with get. (There are historical Cocoa meanings for a get prefix that you don't mean, and so even if you mean "go out to the internet and retrieve this information" you'd want to use something like fetch, but certainly not in the case you've given.)
These issues are addressed in various sections of the Swift API Design Guidelines. First, a property is a property, whether it is stored or computed. So there is no difference in design between:
let someProperty: String?

and
var someProperty: String? { return "string" }

You should not change the naming just because it's computed. We can then see in the guidelines:

The names of other types, properties, variables, and constants should read as nouns.

Furthermore, as discussed in The Swift Programming Language:

Properties associate values with a particular class, structure, or enumeration. Stored properties store constant and variable values as part of an instance, whereas computed properties calculate (rather than store) a value.

So if this is best thought of as a value associated with the type (one of its "attributes"), then it should be a property (computed or stored). If it is something that is not really "associated" with the type (something that the caller expects this type to retrieve from elsewhere for instance), then it should be a method. Again from the Design Guidelines:

Document the complexity of any computed property that is not O(1). People often assume that property access involves no significant computation, because they have stored properties as a mental model. Be sure to alert them when that assumption may be violated.

If "stored properties as a mental model" doesn't match what you mean to express, then it probably shouldn't be a property in the first place (and you need to document the discrepancies if you make it a property anyway). So, for instance, accessing a property should generally have no visible side effects. And if you read from a property immediately after writing to it, you should get back the value you wrote (again, as a general mental model without getting into the weeds of multi-threaded programming).
If you use a method, it can often result in a different appropriate name. See the "Strive for Fluent Usage" section of the Design Guidelines for more on that. There are several rules for selecting good method names. As a good example of when to use properties vs methods, consider the x.makeIterator(), i.successor() and x.sorted() examples and think about why these are methods and why they're named as they are. This is not to say there is exactly one answer in all cases, but the Design Guidelines will give you examples of what the Swift team intends.

A: With no discernible difference in performance, make the choice for readability:

*

*When an attribute behaves like a variable, use a property. Your example falls into this category.

*When reading an attribute changes object state, use a function. This includes

*

*Attributes that behave like a factory, i.e. returns new objects when you access them

*Attributes that produce new values, such as random number generators

*Peripheral readers

*Input iterators

Of course, if the attribute is computed based on one or more argument, you have no other choice but to use a function.

A: Just as a note: If you want to use both getters and setters in Swift you can do as follows:
var myString: String {
     get {
         return "My string"
     }
     set {
          self.myPrivateString = newValue
     }
}

This way you can access your value as if it was a regular variable, but you can do some "under-the-hood magic" in your getters and setters


text:
Q: slim3 distributed transaction on appengine from example
@Model
public class Account {

    @Attribute(primaryKey = true)
    private Key key;

    private Integer balance;
    ...
}

from example http://sites.google.com/site/slim3appengine/
i do not understand why doing money transfer need 2 different transaction as this is only one entity (same entity)
  Acount src = gtx.get(Acount.class, srcKey);    //arent src and des same entity? why do 2 trans?
    Acount dest = gtx.get(Acount.class, destKey);
    if (src.getBalance() >= amount) {
        src.setBalance(src.getBalance() - amount);
        dest.setBalance(dest.getBalance() + amount);
    }

A: src and dest are different entities - you're fetching them with separate keys (srcKey and destKey).


text:
Q: Unable to find the requested .Net Framework Data Provider. PostgreSQL and Mono I have a problem with my application wrote in Visual Studio. Build in Visual Studio is OK, but when I try to run on Mono. Server shows
System.ArgumentException
Unable to find the requested .Net Framework Data Provider.  It may not be installed.

I use EntityFramework 6 and dotConnect for PosgreSQL.
Here is my Web.Config:
    <?xml version="1.0" encoding="utf-8"?>

<configuration>
    <configSections>

    </configSections>
    <connectionStrings>

        <add name="EntityManager" connectionString="User Id=postgres;Password=****;Host=127.0.0.1;Database=postgres; Charset=utf8; Persist Security Info=True;Initial Schema=public" providerName="Devart.Data.PostgreSql" /></connectionStrings>
    <appSettings>
        <add key="webpages:Version" value="3.0.0.0" />
        <add key="webpages:Enabled" value="false" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    </appSettings>
    <system.web>
        <compilation debug="true" targetFramework="4.6" />
        <httpRuntime targetFramework="4.6" />
        <customErrors mode="Off" />
        <httpModules>
            <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
        </httpModules>
    </system.web>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <modules>
            <remove name="ApplicationInsightsWebTracking" />
            <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
        </modules>
    </system.webServer>
    <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
            <parameters>
                <parameter value="mssqllocaldb" />
            </parameters>
        </defaultConnectionFactory>
        <providers>
            <provider invariantName="Devart.Data.PostgreSql" type="Devart.Data.PostgreSql.Entity.PgSqlEntityProviderServices, Devart.Data.PostgreSql.Entity.EF6, Version=7.5.644.0, Culture=neutral, PublicKeyToken=09af7300eec23701" />
        </providers>
    </entityFramework>
    <system.codedom>
        <compilers>

        </compilers>
    </system.codedom>
    <system.data>
        <DbProviderFactories>

        </DbProviderFactories>
    </system.data>
</configuration>

A: Solution is uncomment

<configuration>
  <configSections>

  </configSections>
  <connectionStrings>

        <add name="EntityManager" connectionString="User Id=postgres;Password=*****;Host=127.0.0.1;Database=postgres; Charset=utf8; Persist Security Info=True;Initial Schema=public" providerName="Devart.Data.PostgreSql" /></connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.6" />
    <httpRuntime targetFramework="4.6" />
    <customErrors mode="Off" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
  </system.webServer>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="Devart.Data.PostgreSql" type="Devart.Data.PostgreSql.Entity.PgSqlEntityProviderServices, Devart.Data.PostgreSql.Entity.EF6, Version=7.5.644.0, Culture=neutral, PublicKeyToken=09af7300eec23701" />
    </providers>
  </entityFramework>
  <system.codedom>
    <compilers>

    </compilers>
  </system.codedom>

<system.data>
   <DbProviderFactories>
         <remove invariant="Devart.Data.PostgreSql"></remove>
      <add name="dotConnect for PostgreSQL" invariant="Devart.Data.PostgreSql" description="Devart dotConnect for PostgreSQL" type="Devart.Data.PostgreSql.PgSqlProviderFactory, Devart.Data.PostgreSql, Version= 7.5.644.0, Culture=neutral, PublicKeyToken=09af7300eec23701" />
    </DbProviderFactories>
  </system.data></configuration>

A: Make sure you have installed :
Npgsql PostgreSQL Integration Package
Install EntityFramework6.Npgsql or relevant NuGet package for you .net version in your startup project.
Add or replace these blocks in yor web.config in web project and app.config in class library.
  <entityFramework>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      <provider invariantName="Npgsql" type="Npgsql.NpgsqlServices, EntityFramework6.Npgsql" />
    </providers>
    <defaultConnectionFactory type="Npgsql.NpgsqlConnectionFactory, EntityFramework6.Npgsql" />
  </entityFramework>

<system.data>
    <DbProviderFactories>
      <remove invariant="Npgsql" />
      <add name="Npgsql Provider" invariant="Npgsql" description=".NET Framework Data Provider for PostgreSQL" type="Npgsql.NpgsqlFactory, Npgsql, Version=4.1.3.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7" />
    </DbProviderFactories>
  </system.data>


text:
Q: PHP not reading session id On my webpage, I have a login form that creates a session - but PHP doesn't seem to be acknowledging it:
require_once('globals.php');
require_once('header.php');
if(!isset($_SESSION) || session_id() == '')
{
    $x = (isset($_SESSION));
    var_dump($_SESSION['username']);
    ?>
<?PHP
    var_dump(session_id());
    ?>
<?PHP
    var_dump($x);
    require_once('system/default.php');
}
else
{
    require_once('system/' . $SystemScreens[$_SESSION['screen']]);
}
require_once('footer.php');

is producing:

NULL
  string(0) ""
  bool(false)

relavant part of login script (where $finalCheck is a boolean stating if the login was successful)
if($finalCheck)
    {
        session_start();

        $_SESSION['userID']         = $UserID;
        $_SESSION['username']           = $username;
        $_SESSION['accessLevel']        = $UserAccess;
        $_SESSION['screen']         = 1;

    }
    else
    {
        if(session_id() != '' || isset($_SESSION))
        {
            if (ini_get("session.use_cookies"))
            {
                $params = session_get_cookie_params();
                setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
            }

            session_destroy();
        }

    }

I know that the login function is returning true because I have visual confirmation (result is returned to an AJAX request, and the page reloaded if true - which it does)
I can't figure out why everything is running as if the login is successful, but the session isn't being recognised after the reload occurs?

A: Put it after your PHP start tag

  <?php
  session_start();
  //... your code....

  //more code....

A basic session example
   <?php
       session_start();
       echo 'Welcome to page #1';

       $_SESSION['favcolor'] = 'green';
       $_SESSION['animal']   = 'cat';
       $_SESSION['time']     = time();

      // Works if session cookie was accepted
      echo '
page 2';

     // Or maybe pass along the session id, if needed
       echo '
page 2';
     ?>

session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers. These will either be a built-in save handler provided by default or by PHP extensions (such as SQLite or Memcached); or can be custom handler as defined by session_set_save_handler(). The read callback will retrieve any existing session data (stored in a special serialized format) and will be unserialized and used to automatically populate the $_SESSION superglobal when the read callback returns the saved session data back to PHP session handling.
For More Info : http://us3.php.net/function.session-start


text:
Q: Redirecting from http to https with Nginx causes Google Search Console to report an issue I have a website built (in plain HTML) using letsencrypt certificates. The Nginx config is redirecting traffic from http to https. I submitted this website to Google's Search Console, and they are sending me emails that "Page with redirect" issue detected and "must remove to enable the best experience" (?).
This is my nginx configuration.
server {
        root /var/www/example/html;
        index index.html index.htm index.nginx-debian.html;
        server_name example.gr www.example.gr;
        location / {
                try_files $uri $uri/ =404;
        }

    listen [::]:443 ssl; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.gr-0001/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.gr-0001/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    listen 80;
    listen [::]:80;

    server_name example.gr;

    if ($host = example.gr) {
        return 301 https://$host$request_uri;  # <-- this line might be causing the issue
    } # managed by Certbot

    return 404; # managed by Certbot
}

What am I doing wrong?


text:
Q: Error in new Scanner I have a problem in my programm, I want the user of my programm to write the file he wants to use and then with loops, depending on the word he typed, a file will be used. Butmy programm never enters in one loop and I don't know where the problem comes from.
Here is my code:
        System.out.println("Nom du test case à lancer ? : ");
    Scanner saisieUtilisateur = new Scanner(System.in);
    //on rentre l'adresse du fichier texte :
    String str = saisieUtilisateur.next();
    System.out.println(str);
    //Integer val = saisieUtilisateur.nextInt();
    //System.out.println(val);
    String chaine = "";
    String File="";
    int i=1;

    //Choix du fichier a prendre en compte suivant le choix de l'utilisateur
    if (str == "hello"){
        File = "C:\\exempleANT\\helloWordTexte.txt";
        System.out.println("dans la boucle 1");
    }
    else if(str == "bye"){
        System.out.println("dans la boucle 2");
        File =  "C:\\exempleANT\\FichiersTestExempleHelloWord\\bye.txt";
    }
    else if(str == "fake"){
        System.out.println("dans la boucle 3");
        File =  "C:\\exempleANT\\FichiersTestExempleHelloWord\\helloWordTexteFake.txt";
    }
    else  {
        System.out.println("ErreurTexte!");
        System.out.println("dans la boucle 4");

    }

And here is the result in the console when I run the programm and I type hello.
hello
hello
ErreurTexte!
dans la boucle 4

A: Use .equals for string equality rather than '=='.
 if (str.equals("hello")){
     ...
 }

See - How do I compare strings in Java?

A: If you are using JAVA 7 than it will be done simple way
//str is your String to get match with
    switch (str) {
    case "hello":
        File = "C:\\exempleANT\\helloWordTexte.txt";
        System.out.println("dans la boucle 1");
        break;
    case "bye":
        System.out.println("dans la boucle 2");
    File = "C:\\exempleANT\\FichiersTestExempleHelloWord\\bye.txt";
        break;
    case "fake":
        System.out.println("dans la boucle 3");
        File="C:\\exempleANT\\FichiersTestExempleHelloWord\\helloWordTexteFake.txt";
        break;
    default:
        System.out.println("ErreurTexte!");
    System.out.println("dans la boucle 4");
    }

or you can use
 if (str.equals("hello")){
 ...// old way
 }

A: Try this:
 if (str.equals("hello"))
    {
        File = "C:\\exempleANT\\helloWordTexte.txt";
        System.out.println("dans la boucle 1");
    }


text:
Q: Onfocus shadow not working in IE Below code is not working in IE..
 input:focus,textarea:focus,select:focus
{
  border:1px solid #fafafa;
   -webkit-box-shadow:0 0 6px #007eff;
   -moz-box-shadow:0 0 5px #007eff;
  box-shadow:0 0 5px #007eff;
}

Instead it is not showing textbox border even.
 Here is the fiddle link
http://jsfiddle.net/3cKVp/1/

A: It will not work in IE 7 or earlier, as you can see on this page which shows you a compatibility levels for specific browsers.

A: :focus pseudoselector and box-shadow CSS property is not supported in IE7. To support focus style changes you will have to bind to focus and  blur events in javascript (possibly using jQuery) and add/remove respectively a CSS style that will indicate a "focused" appearance.


text:
Q: Netbeans 6.5 prevents adding breakpoints to Java files. Configuration issue? I'm not able to add breakpoints to any Java file.
It seems this problem has been reported in slightly varying contexts in the netbeans issuezilla. I could not find any concrete workarounds other than updgrade to NB6.7M2, which is currently not feasible.
Other things I've tried are a JDK updgrade, spicy bat wings and a bottle of silvermoon port (multiple system restarts ;))
I was just wondering if any of the gurus at SO had encountered this problem before and if it is some configuration that got messed up during ide updates/project svn updates etc.
NB build version : 20081110001
Java: 1.6.0__14

A: Did some more investigating and found that an error in Netbeans update had de-activated most of my Java plugins, one of which was ... "Java Debugging"
Activating the plugin solved the issue.
"Oh. Well I feel sheepish. [turns into a sheep]" - Genie (Aladdin)
For reference, the setting is found in Tools > Plugins > Installed (tab) , under the "Java" category


text:
Q: ExtJS: How to pass keystrokes from text field to Grid? I have following grid declaration:
quickSearchGrid = Ext.create('Ext.grid.Panel', {
        height: 500,
        collapsible: true,
        .....

Then, I have input element above it:
<input type="text" id="quickSearch" value="Search" style="height: 25px; width: 100%;" />

I want to pass specific keystrokes - Up, Down, PgUp, PgDown etc from input to grid. So that when user has focus in text field, he'll be able to navigate in the grid with keyboard.
What I'm trying is creating my own KeyNav:
var nav = Ext.create('Ext.util.KeyNav', Ext.get('quickSearch'), {
    scope: Ext.get('quickSearch'),
    down: function (e) {
        console.log(e)
        quickSearchGrid.fireEvent('keydown', quickSearchGrid, e)
    }
});

Function is being called (it writes to console) but grid does not react.

A: Found a workaround you could use. Create the text input in extJs instead of declaring it in html:
var quickSearch = Ext.create('Ext.form.field.Text', {
    id: 'quickSearch',
    name: 'quickSearch',
    fieldLabel: 'QuickSearch',
    allowBlank: true
});

You can then use it for navigation in the grid with arrows by selecting a record with index 1 higher/lower than the one currently selected:
var grid = quickSearchGrid;
var view = quickSearchGrid.getView();

var nav = Ext.create('Ext.util.KeyNav', Ext.getDoc(), {
    down: function(e) {
        var selectionModel = grid.getSelectionModel();
        var select = 0; // select first if no record is selected
        if ( selectionModel.hasSelection() ) {
            select = grid.getSelectionModel().getSelection()[0].index + 1;
        }
        view.select(select);
        quickSearch.focus(); // to get focus back to the input
    },
    up: function(e) {
        var selectionModel = grid.getSelectionModel();
        var select = grid.store.totalCount - 1; // select last element if no record is selected
        if ( selectionModel.hasSelection() ) {
            select = grid.getSelectionModel().getSelection()[0].index - 1;
        }
        view.select(select);
        quickSearch.focus(); // to get focus back to the input
    },
});

A: With ExtJS 6, it was really easy to simulate navigation with bufferedRenderer.scrollTo() method:
Here, I'm creating KeyNav but you can rewrite it to pure Javascript/jQuery:
quickSearchKeyNav = Ext.create('Ext.util.KeyNav', Ext.get('quickSearch'), {
        scope: Ext.get('quickSearch'),
        up: function (e) {
            quickSearchGrid.view.bufferedRenderer.scrollTo(
              quickSearchGrid.getStore().indexOf(quickSearchGrid.getSelection()[0]) - 1,
              true);
        },
        pageUp: function (e) {
            var rowsOnScreen = quickSearchGrid.getNavigationModel().getRowsVisible();
            quickSearchGrid.view.bufferedRenderer.scrollTo(
              quickSearchGrid.getStore().indexOf(quickSearchGrid.getSelection()[0]) - rowsOnScreen,
              true);
        },
        pageDown: function (e) {
            var rowsOnScreen = quickSearchGrid.getNavigationModel().getRowsVisible();
            quickSearchGrid.view.bufferedRenderer.scrollTo(
              quickSearchGrid.getStore().indexOf(quickSearchGrid.getSelection()[0]) + rowsOnScreen,
              true);
        },
        down: function (e) {
            quickSearchGrid.view.bufferedRenderer.scrollTo(
              quickSearchGrid.getStore().indexOf(quickSearchGrid.getSelection()[0]) + 1,
              true);
            }
    });


text:
Q: fill in blanks with exponential estimates I'm trying to fill in NA values with numbers that show exponential growth. Below is a data sample of what I'm trying to do.

library(tidyverse)

expand.grid(X2009H1N1 = "0-17 years",
            type = "Cases",
            month = seq(as.Date("2009-04-12") , to = as.Date("2010-03-12"), by = "month")) %>%
  bind_cols( data.frame(
    MidLevelRange = c(0,NA,NA,NA,NA,NA,8000000,16000000,18000000,19000000,19000000,19000000),
    lowEst = c(0,NA,NA,NA,NA,NA,5000000,12000000,12000000,13000000,14000000,14000000)
  ))

I have used %>% arrange(month, X2009H1N1) %>%
  group_by(X2009H1N1, type ) %>%
  mutate(aprox_MidLevelRange = zoo::na.approx(MidLevelRange, na.rm = FALSE)) but the result does not look exponential to me. Thanks

A: Sure your result is not exponential, you are using a function na.approx() to impute the values using linear interpolation. The zoo package you are using offers to interpolate using cubic spline interpolation using na.spline() function, but this function does not produce exponential curve either.
x <- expand.grid(X2009H1N1 = "0-17 years",
                 type = "Cases",
                 month = seq(as.Date("2009-04-12"),
                             to = as.Date("2010-03-12"),
                             by = "month")) %>%
  bind_cols(data.frame(MidLevelRange = c(0,NA,NA,NA,NA,NA,8000000,16000000,18000000,19000000,19000000,19000000),
                       lowEst = c(0,NA,NA,NA,NA,NA,5000000,12000000,12000000,13000000,14000000,14000000)))

x %>% arrange(month, X2009H1N1) %>%
  group_by(X2009H1N1, type) %>%
  mutate(aprox_MidLevelRange = zoo::na.spline(MidLevelRange))

The problem with cubic spline interpolation is that your lowest values will be interpolated as negative, depends whether this is a behavior you are looking for or not:
# A tibble: 8 x 6
# Groups:   X2009H1N1, type [1]
  X2009H1N1  type  month      MidLevelRange   lowEst aprox_MidLevelRange
  <fct>      <fct> <date>             <dbl>    <dbl>               <dbl>
1 0-17 years Cases 2009-04-12             0        0                  0
2 0-17 years Cases 2009-05-12            NA       NA          -18568160.
3 0-17 years Cases 2009-06-12            NA       NA          -25223342.
4 0-17 years Cases 2009-07-12            NA       NA          -22929832.
5 0-17 years Cases 2009-08-12            NA       NA          -14651914.
6 0-17 years Cases 2009-09-12            NA       NA           -3353875.
7 0-17 years Cases 2009-10-12       8000000  5000000            8000000.

A: Have a look at the imputeTS package.
It offers plenty of imputation functions for time series. Take a look at this paper to get a good overview of all offered options
In your case using Stineman interpolation ( imputeTS::na_interpolation(x, option ="stine") could maybe be a suitable option.
Here for the example you provided:
x <- expand.grid(
  X2009H1N1 = "0-17 years",
  type = "Cases",
  month = seq(as.Date("2009-04-12"),
    to = as.Date("2010-03-12"),
    by = "month"
  )
) %>%
  bind_cols(data.frame(
    MidLevelRange = c(0, NA, NA, NA, NA, NA, 8000000, 16000000, 18000000, 19000000, 19000000, 19000000),
    lowEst = c(0, NA, NA, NA, NA, NA, 5000000, 12000000, 12000000, 13000000, 14000000, 14000000)
  ))

x %>%
  arrange(month, X2009H1N1) %>%
  group_by(X2009H1N1, type) %>%
  mutate(aprox_MidLevelRange = imputeTS::na_interpolation(MidLevelRange, option = "stine"))

This gives you:
# A tibble: 12 x 6
# Groups:   X2009H1N1, type [1]
   X2009H1N1  type  month      MidLevelRange   lowEst aprox_MidLevelRange
   <fct>      <fct> <date>             <dbl>    <dbl>               <dbl>
 1 0-17 years Cases 2009-04-12             0        0                  0
 2 0-17 years Cases 2009-05-12            NA       NA             593718.
 3 0-17 years Cases 2009-06-12            NA       NA            1335612.
 4 0-17 years Cases 2009-07-12            NA       NA            2289061.
 5 0-17 years Cases 2009-08-12            NA       NA            3559604.
 6 0-17 years Cases 2009-09-12            NA       NA            5336975.
 7 0-17 years Cases 2009-10-12       8000000  5000000            8000000
 8 0-17 years Cases 2009-11-12      16000000 12000000           16000000
 9 0-17 years Cases 2009-12-12      18000000 12000000           18000000
10 0-17 years Cases 2010-01-12      19000000 13000000           19000000
11 0-17 years Cases 2010-02-12      19000000 14000000           19000000
12 0-17 years Cases 2010-03-12      19000000 14000000           19000000

So just comparing interpolation functions I guess this could be the best option.
Just plot yourself the different interpolation options, to see the differences.
In general this are the interpolation options:
imputeTS::na_interpolation(x, option ="linear")
imputeTS::na_interpolation(x, option ="spline")
imputeTS::na_interpolation(x, option ="stine")

linear / spline options from imputeTS are the same as zoo::approx()/ zoo::spline(). stine does not exist in zoo.

A: I do not think that exponential growth can come from zero. Should the question be reframed?
The following method does produce an exponential fill. The idea is that exponential growth is linear on a log-scale. So you can log-transform the data (which only works for strictly positive series), apply linear interpolation, and then transform back to the exponential scale.
The worked example below begins the series with 0.001 instead of 0.
x <- expand.grid(X2009H1N1 = "0-17 years",
                 type = "Cases",
                 month = seq(as.Date("2009-04-12"),
                             to = as.Date("2010-03-12"),
                             by = "month")) %>%
bind_cols(data.frame(MidLevelRange = c(0.001,NA,NA,NA,NA,NA,8000000,16000000,18000000,19000000,19000000,19000000),
                       lowEst = c(0,NA,NA,NA,NA,NA,5000000,12000000,12000000,13000000,14000000,14000000)))
x<-x %>% arrange(month, X2009H1N1) %>%
  group_by(X2009H1N1, type) %>%
  mutate(aprox_MidLevelRange = exp(na.approx(log(MidLevelRange))))

This produces:
# A tibble: 12 × 6
# Groups:   X2009H1N1, type [1]
   X2009H1N1  type  month      MidLevelRange   lowEst aprox_MidLevelRange
   <fct>      <fct> <date>             <dbl>    <dbl>               <dbl>
 1 0-17 years Cases 2009-04-12         0.001        0              0.001
 2 0-17 years Cases 2009-05-12        NA           NA              0.0447
 3 0-17 years Cases 2009-06-12        NA           NA              2.00
 4 0-17 years Cases 2009-07-12        NA           NA             89.4
 5 0-17 years Cases 2009-08-12        NA           NA           4000.
 6 0-17 years Cases 2009-09-12        NA           NA         178885.
 7 0-17 years Cases 2009-10-12   8000000      5000000        8000000
 8 0-17 years Cases 2009-11-12  16000000     12000000       16000000
 9 0-17 years Cases 2009-12-12  18000000     12000000       18000000
10 0-17 years Cases 2010-01-12  19000000     13000000       19000000.
11 0-17 years Cases 2010-02-12  19000000     14000000       19000000.
12 0-17 years Cases 2010-03-12  19000000     14000000       19000000.


text:
Q: How do I avoid applying spaceless to Django fields? I'm using {% spaceless %} in my base template which helps fix a fair bit of spacing issues while maintaining readability of the template code itself, further compounded because I'm using HamlPy.  However, I have some models with fields containing HTML, which are also 'despaced', leading to some incorrect rendering, e.g.
... Some Journal Issue, 1695 (2013)

where the Journal and Issue number get smashed together.  How can I avoid spaceless being applied to the fields themselves while maintaining it elsewhere?
A dumb hack of trying to prepend the field with {% endspaceless %} and after with {% spaceless %} just throws errors.

A: {% spaceless %} tag removes only spaces between HTML elements, and doesn't remove any spaces between text and elements nor spaces inside text. https://docs.djangoproject.com/en/1.6/ref/templates/builtins/#spaceless
Knowing that, a simple solution might be to move the space inside one of the HTML elements:
Some Journal Issue

Another option would be to use CSS to add the space:
.some_context em {
    margin-right: 0.5em;
}

or
.some_context em:after {
    content: " ";
}

Third option might be to use  :
Some Journal Issue

If "non-breaking" has some unwanted effects, try   instead.


text:
Q: functional way to iterate over range (ES6/7) What is the best way to do the below in more functional way (with ES6/ES7)
let cols = [];
for (let i =0; i <= 7; i++) {
   cols.push(i * i);
}
return cols;

I tried like,
return [ ...7 ].map(i => {
  return i * i;
});

but that translated to
[].concat(7).map(function (n) {
  return n * n;
});

which is not what I expected.
EDIT:
@pavlo. Indeed, that was a mistake. I was using JSX, and for example, I want 7 divs, (untested)
let cols = [];
    for (let i =0; i <= 7; i++) {
       cols.push(<div id={i}> ...  </div>)
    }
    return cols;

so the idea was indeed to reduce the number of temp variables and procedural feel.

A: ES7 Proposal
Warning: Unfortunately I believe most popular platforms have dropped support for comprehensions. See below for the well-supported ES6 method
You can always use something like:
[for (i of Array(7).keys()) i*i];

Running this code on Firefox:

[ 0, 1, 4, 9, 16, 25, 36 ]

This works on Firefox (it was a proposed ES7 feature), but it has been dropped from the spec. IIRC, Babel 5 with "experimental" enabled supports this.
This is your best bet as array-comprehension are used for just this purpose. You can even write a range function to go along with this:
var range = (u, l = 0) => [ for( i of Array(u - l).keys() ) i + l ]

Then you can do:
[for (i of range(5)) i*i] // 0, 1, 4, 9, 16, 25
[for (i of range(5,3)) i*i] // 9, 16, 25

ES6
A nice way to do this any of:
[...Array(7).keys()].map(i => i * i);
Array(7).fill().map((_,i) => i*i);
[...Array(7)].map((_,i) => i*i);

This will output:

[ 0, 1, 4, 9, 16, 25, 36 ]

A: Here's an approach using generators:
function* square(n) {
    for (var i = 0; i < n; i++ ) yield i*i;
}

Then you can write
console.log(...square(7));

Another idea is:
[...Array(5)].map((_, i) => i*i)

Array(5) creates an unfilled five-element array. That's how Array works when given a single argument. We use the spread operator to create an array with five undefined elements. That we can then map. See http://ariya.ofilabs.com/2013/07/sequences-using-javascript-array.html.
Alternatively, we could write
Array.from(Array(5)).map((_, i) => i*i)

or, we could take advantage of the second argument to Array#from to skip the map and write
Array.from(Array(5), (_, i) => i*i)

A horrible hack which I saw recently, which I do not recommend you use, is
[...1e4+''].map((_, i) => i*i)

A: One can create an empty array, fill it (otherwise map will skip it) and then map indexes to values:
Array(8).fill(0).map((_, i) => i * i);


text:
Q: How to send data to tcp server on 1 minute interval I am reading a csv file line by line and storing in an array. Now I want to send line by line csv data to tcp server on 1 minute interval. My code is below ...what should I change in my code?
var net = require('net');
var csv = require("fast-csv");
var querystring = require('querystring');
var i;
var client = new net.Socket();
var csvData=[];
client.connect(7001, '54.168.67.139', function() {
    console.log('Connected');
    csv
    .fromPath("wabco.csv")
    .on("data", function(data){
    var res = "";
    for (i = 2; i < data.length; i++) {
            if (i == data.length-1) res += data[i];
            else res += data[i]+",";
    }
    res = res.substring(1,res.length-1);
    //client.write(res);
    //console.log(res);
    csvData.push(res);
})
.on("end", function(){
    //client.write(csvData[5]);
    for (i = 0; i < csvData.length; i++) {
            client.write(csvData[i]);
    }
});
});

client.on('close', function() {
    console.log('Connection closed');
});

A: Assuming csvData is an array with the lines of that you want to send, you can do something like :
.on("end", function(){

    let interval = 0,
        i = 0;

    interval = setInterval( function() {

        // Send it
        client.write( csvData[ i++ ] );

        // Stop when we are on the last item
        if ( csvData.length === i ) { clearInterval( interval ); }

    }, 1000 * 60 )

});


text:
Q: _TypeError (type 'List' is not a subtype of type 'Map') in flutter Hello I am making an api call where I am getting array of banners. I am getting below error -
_TypeError (type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>')

banners_bloc.dart
class BannersBloc {
  late BannerRepository _bannerRepository;
  late StreamController _streamController;

  StreamSink get bannerListSink => _streamController.sink;

  BannersBloc() {
    _streamController = StreamController();
    _bannerRepository = BannerRepository();
    fetchBanners();
  }

  fetchBanners() async {
    bannerListSink.add('Fetching Banners');
    try {
      Banners banners = await _bannerRepository.getBanners();
      bannerListSink.add(banners);
    } catch (e) {
      bannerListSink.add(e.toString());
      print(e);
    }
  }

  dispose() {
    _streamController.close();
  }
}

banners.dart
class Banners {
  late String bannerImageUrl;
  late String bannerImageAlt;
  late bool isActive;
  late int order;
  late String id;

  Banners(
      {required this.bannerImageUrl,
      required this.bannerImageAlt,
      required this.isActive,
      required this.order,
      required this.id});

  Banners.fromJson(Map<String, dynamic> json) {
    bannerImageUrl = json['bannerImageUrl'];
    bannerImageAlt = json['bannerImageAlt'];
    isActive = json['isActive'];
    order = json['order'];
    id = json['id'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['bannerImageUrl'] = this.bannerImageUrl;
    data['bannerImageAlt'] = this.bannerImageAlt;
    data['isActive'] = this.isActive;
    data['order'] = this.order;
    data['id'] = this.id;
    return data;
  }
}

api_base_helper.dart
class APIHelper {
  final String _baseURL =
      "https://raw.githubusercontent.com/gautam-in/shopping-cart-assignment/master/server/";

  Future<dynamic> get(String url) async {
    try {
      final response = await http.get(Uri.parse(_baseURL + url));
      return json.decode(response.body);
    } catch (err) {
      throw new Exception("Something went wrong");
    }
  }
}

get_banners.dart
class BannerRepository {
  Future getBanners() async {
    final response = await new APIHelper().get("banners/index.get.json");
    return Banners.fromJson(response);
  }
}

A: If your response from the API is a List of Banners, then the error is being thrown by getBanners. As the fromJson method is expecting a of type Map<String, dynamic>. To solve this you'll need to iterate through the response and call Banners.fromJson for each item in the response list.
class BannerRepository {
  Future<List<Banners>> getBanners() async {
    final response = await new APIHelper().get("banners/index.get.json");
   // Sample Code, handler errors and other stuff
    return response.map((e) =>Banners.fromJson(e)).toList();
  }
}


text:
Q: how to exclude the non numerical integers from a data frame in Python I have a data frame which comprises of datatypes integer, string, numeric etc.
Something like below. I want to exclude all the variables which are non-numeric. is there any automated way in Python?
'data.frame':   891 obs. of  12 variables:
 $ PassengerId: int  1 2 3 4 5 6 7 8 9 10 ...
 $ Survived   : int  0 1 1 1 0 0 0 0 1 1 ...
 $ Pclass     : int  3 1 3 1 3 3 1 3 3 2 ...
 $ Name       : Factor w/ 891 levels "Abbing, Mr. Anthony",..: 109 191 358 277 16 559 520 629 417 581 ...
 $ Sex        : Factor w/ 2 levels "female","male": 2 1 1 1 2 2 2 2 1 1 ...
 $ Age        : num  22 38 26 35 35 NA 54 2 27 14 ...
 $ SibSp      : int  1 1 0 1 0 0 0 3 0 1 ...
 $ Parch      : int  0 0 0 0 0 0 0 1 2 0 ...
 $ Ticket     : Factor w/ 681 levels "110152","110413",..: 524 597 670 50 473 276 86 396 345 133 ...
 $ Fare       : num  7.25 71.28 7.92 53.1 8.05 ...
 $ Cabin      : Factor w/ 148 levels "","A10","A14",..: 1 83 1 57 1 1 131 1 1 1 ...
 $ Embarked   : Factor w/ 4 levels "","C","Q","S": 4 2 4 4 4 3 4 4 4 2 ...

After exclusion of numeric variables, my dataframe should look like the below:
'data.frame':   891 obs. of  12 variables:
 $ PassengerId: int  1 2 3 4 5 6 7 8 9 10 ...
 $ Survived   : int  0 1 1 1 0 0 0 0 1 1 ...
 $ Pclass     : int  3 1 3 1 3 3 1 3 3 2 ...
 $ Age        : num  22 38 26 35 35 NA 54 2 27 14 ...
 $ SibSp      : int  1 1 0 1 0 0 0 3 0 1 ...
 $ Parch      : int  0 0 0 0 0 0 0 1 2 0 ...
 $ Fare       : num  7.25 71.28 7.92 53.1 8.05 ...

A: We could use ._get_numeric_data()
import pandas as pd #import the pandas library
#creating a small dataset for testing
df1 = pd.DataFrame({'PassengerId' :  [1, 2, 3],
        'Name' : ['Abbing, Mr. Anthony', 'Ann, C', 'John, H'],
        'Fare' : [7.25, 71.28, 7.92]})
#extract only the numeric column types
df2 = df1._get_numeric_data()
print(df2)

Or another option is select_dtypes()
df3 = df1.select_dtypes(include = ['int64', 'float64'])
print(df3)


text:
Q: Wordpress speed slow after .5 million single image post via wp-cli I am trying to Creat Wordpress website that will contain 10 Million post, such that when i upload a single its become a post with it's own name as title.  and i am importing these images with Wp-cli. now the problem i am facing is that i have uploaded about half a million images and now Wordpress has become slow, its taking too much time to import images. please suggest me any solution for this
Images Importing goes slow down, Server usage only 1%
i am doing this Via WP-cli with this command
wp media import ~/Pictures/processed-images-medium/\*\*\/\*.jpg

every time when image upload its become a Unique post you can check it at here
http://www.wallpaper2k.com/naked-art-first/

A: You need to either read more about database optimization or hire a specialist and distribute those posts possibly on multiple database and file servers.
Even if you build a custom solution it would be slow so don't blame WP.


text:
Q: Decimal is rounded after insert into DB I've run into a problem upon inserting a decimal with PHP into MySQL.
The number is formatted as currency, stored in a session variable.
$_SESSION['total'];

Using number_format to replace the dot with a comma gives me the correct output:
$amount= number_format((float)$_SESSION['total'], 2, ",", '');
echo $amount;
//output = 2,85

Now I need to insert the variable $amount into the database, which is done like so:
$query = "INSERT INTO testtable VALUES" . "('$amount', 'NULL')";
$result = $con->query($query);

Upon insert, the number is inserted as "2,00" and not "2,85". I have also tried to do it without number_format but I get the same result.
The row is set as decimal(10,2).
How is it possible that the variable echo's correctly, but the insert rounds it?

A: The output of number_format() is a string and the problem is that MySQL / php do not know the comma , as a decimal separator so your string 2,85 is cast to a number by using the first characters of your string that are valid number characters.
You should convert your string to a real number before you do any calculations or database inserts by replacing the , with a . and casting it to a float:
$number = (float) str_replace(',', '.', $amount);

If your session variables contain actual numbers instead of strings, you should use these directly.
Note that using floats could lead to precision problems / rounding errors. If that is the case, you should use integers only (cents for the amounts for example, so 285 instead of 2.85).

A: You need to do the insert using a point separator , not comma.
$amount = number_format((float)$_SESSION['total'], 2, ".", '');
echo $amount; // prints 2.85
$query = "INSERT INTO money (total,second_field) VALUES" . "($amount, 'NULL')";
$result = $conn->query($query);

A: We use number_format() for user easy user readability. In statement
$amount= number_format((float)$_SESSION['total'], 2, ",", '');
$amount is string and insertion of string to mysql field with decimal type would insert record with warning

1 row inserted. Warning: #1265 Data truncated for column
  'decimal_test' at row 1

You can use str_replace to remove "," in number and insert value to mysql table as shown below
$_SESSION['total'] = "2,85";
$total_in_decimal = str_replace(',', '.', $_SESSION['total']);
$query = "INSERT INTO testtable VALUES" . "('$total_in_decimal', 'NULL')";
$result = $con->query($query);


text:
Q: EJB 3.0 TimerService - Run timer on 1st day of every month In EJB 3.0 TimerService.createTimer(initialDuration, intervalDuration, TimerID) method is accepting only initialDuration and intervalDuration arguments.
The problem is I want to run timer on 1st of every month and I can not set my timer using cron expression like in EJB 3.1 TimerService.
Some workaround is like run on daily base and check the date inside @Timeout method if its '1st of month' but that is not appropriate way.
I went through many example/tutorials online but no luck. Is there any other way to implement this scenario?

A: I suggest the following approaches:

*

*In the @Timeout method use JodaTime to calculate the next point-in-time. So every timer schedules the next call in its @Timeout method . This has the advantage that you are able to build an admin dialog that provides an overview of the scheduled timers in the system which you can't do if you just run the timer daily. I used this to implement a fairly complex, user-configurable timer configuration (Outlook style, i.e. something like "run this every two months on the third at 9:00 AM). Even with JodaTime, I ended up writing a lot of code, though. However, in your case it shouldn't be that complicated. Basically like

timerService.createTimer( new DateTime( System.currentTimeMillis()).plusMonths(1).withTimeAtStartOfDay().toDate(), null );

*

*Abandon TimerService and use Quartz directly for scheduling. Then you can feed cron expressions directly into the API. Quartz generally integrates nicely with Java EE, even in complex clustered environments.

A:     try {
        Scheduler scheduler;
        scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler.start();

        JobDetail job = new JobDetail("job name", "job group", (your class which will implement job interface).class);
        CronTrigger trigger = new CronTrigger("trigger name", "trigger group", "0 0 0 1 * ?");
        scheduler.scheduleJob(job, trigger);
    } catch (Exception e) {
        e.printStackTrace();
    }

Use above code it will run timer at 1st of every month.


text:
Q: Reorder Buffer commit When having an Out-of-Order execution processor with a reorder buffer (ROB) and branch speculation, I understand that the changes are not being made until the ROB has performed a commit.
The results of the functional units (FUs) write their result on lets say a common data bus (CDB) and on the ROB when finished executing. The ROB can then decide if the branch was successfully predicted and if so commit otherwise the ROB is flushed.
What I don't understand is what happens to the reservation station updates that came from the CDB broadcasts of the FUs, should they not be flushed/rolled back somehow?
An example I can up with (maybe not the best)
addi $s1, $zero, 8
addi $s2, $zero, 9

addi $s3, $zero, 0
bneq $s1, $s2, L1
addi $s3, $s3, 1     // first increment
L1:
addi $s3, $s3, 2     // second increment

$s3 is initialized to 0,
then a miss-prediction of the branch causes $s3 to increase by 1. The result is broadcasted to the RSs.
$s3 is now ready to start executing for the second increment of 2. At the same time the branch miss-prediction is detected and the ROB is flushed, however the RS of the adder is not changed, so $s3 now has a wrong value and was never in the ROB to be flushed.
How is this solved?
I suspect that I am missing something crucial, I am not very experienced, I just graduated and came up with this while revising.

A: When the branch is predicted as taken, the update to $s3 (the first increment) will not update the actual register $s3, that data will be buffered in the reorder buffer. When it is detected the misprediction, the reorder buffer will be flushed. Anyway the bottom line, to the best of my knowledge, is the original register will not be updated until the branch is resolved, hence reorder buffer is used.

A: As I understand it, on Intel CPUs at least, the ROB tracks all in-flight instructions inside the out-of-order part of the pipeline, including ones that are still in the RS waiting to execute. So instructions are added to both the ROB and the RS when they issue into the out-of-order part of the core.
I think this design is nearly universal. You're right that you need to be able to keep track of every instruction that's still speculative somehow.

Also, all instructions that depend on instructions discovered to have been mis-speculated need to be flushed.  It's certainly easier to flush the whole ROB as you describe, and get back to the last non-speculative state.
So even though the second add still needs to be executed, the mis-speculation means its input might be wrong.  So it needs to be flushed, to avoid exactly the problem you're talking about.


text:
Q: Illegal offset in array I am trying to check array using another loop.
     for(   $i=0;$i<count($allCheckBoxId);$i++  )       {
        if( $allCheckBoxId[$i] != ''){
            unset( $contactlist[$cntctnum] );
            }
     }

I have named $allCheckBoxId, having contactnumber as value. Second array I have named $contactlist having contactnumber as key element.
For particular condition I am retrieving values of first array. Means I would have contactnumber as value retrieve in first array. IF it is not null I am unsetting second element with value contactnumber. but its giving me error on unset( $contactlist[$cntctnum] ); as Illegal offset type in unset in

A: Here comes interesting part.
You know, programming is not just writing the code.
Most of time programming is looking for errors. Not by asking questions on stackoverflow, but by amending your code and studying it's output and error messages. Some sort of investigation.
If you have got such an error message, doesn't that mean that somewhing wrong with offset type? Why not to print the problem variable out? just print it out:
 for(   $i=0;$i<count($allCheckBoxId);$i++  )       {
    var_dump($cntctnum);
    var_dump($allCheckBoxId[$i]);
    var_dump($contactlist[$cntctnum]);
    if( $allCheckBoxId[$i] != ''){
        unset( $contactlist[$cntctnum] );
    }
 }

and see what's particularly wrong with your offset

A: Try casting your key into a string. Replace:
$contactlist[$cntctnum]

With
$contactlist[(string) $cntctnum]

OR
for($i = 0; $i < count($allCheckBoxId); $i++)       {
    if($allCheckBoxId[$i] != '') {
        $key = (string) $cntctnum;
        unset( $contactlist[$key] );
    }
}

PHP associative arrays, as of PHP 5.4 will issue a PHP Warning: Illegal Offset Type if you use something other than a string as a key.
Furthermore, if this doesn't help, head over to the PHP Array Manual and do a Ctrl/Cmd + F for "Illegal Offset Type."


text:
Q: Unable to close ssh-connection while running a remote Jupyter Notebook in tmux I use Jupyter Notebook on a remote machine, where I log in via ssh -L 8000:localhost:8888 <user@IP>. (Both my machine and the remote machine use Ubuntu). I start a detachable session via tmux (see here) on the remote machine, and execute jupyter notebook. Them I am able to run my remote notebooks in my local browser, at localhost:8000. The runtime of my notebook is several hours, so I want to be able to close the ssh-connection in the meantime. So I detach the current tmux-session (with ctrl-b d). Now, in my understanding, I should be able to simply close the ssh-connection to the remote machine by exit. If I leave my browser window open, I expect the (remote) Jupyter Notebook to be still running in the browser.
However: I am not able to close the ssh-connection. Typing exit does not close it (but just lets me wait), and if I force a quit via ctrl-c, the notebook in the browser looses the connection to the remote machine.
Am I making a mistake here? Or do I actually need the ssh-connection established so that the notebook in the browser stays connected?

A: I use following commands.
ssh -L 8000:localhost:8888 <user@IP> "jupyter notebook --no-browser --port=8888"

If you press Ctrl+C, it kills ssh only. I am not sure if it is error or not.
You can kill notebook by:
ssh <user@IP> "jupyter notebook stop 8888"

Or you can use: nohup


text:
Q: Symfony - Is it possible to disable output escaping per module (or per template)? I'm trying to output some HTML in an XML template and Symfony's escaping method is messing it up. So I tried making a copy of settings.yml in the module's config folder, but it seems to be completely ignored. Is there an easy way to change the escaping_strategy and/or escaping_method settings per module or even per template?

A: Just run into this problem today and i manage to solve it by setting sfConfig::set('sf_escaping_strategy', false) in my controller (either in preExecute method for all the actions in that module or in a specific action - executeWhatever).

A: While output escaping is turned on you still have access to the raw value through $sf_data.  For example, if the HTML you're trying to output was stored in a variable called html in your action:
$this->html = '<b>My HTML</b>';

You could get the unescaped value with this:
<?php echo $sf_data->getRaw('html') ?>

http://www.symfony-project.org/book/1_0/07-Inside-the-View-Layer#chapter_07_sub_activating_output_escaping
I don't believe there is a way to disable this functionality on a per-module basis.

A: getRaw only works if the variable is passed from the action. for variable within view use
sfOutputEscaperGetterDecorator::unescape($html)


text:
Q: Cannot disable debugging-AndroidManifest.xml I want to disable debugging so i can upload my android game, but "android:debugging" is nowhere to be seen.
<?xml version="1.0" encoding="utf-8"?>
<!-- GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN-->
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.unity3d.player"
    xmlns:tools="http://schemas.android.com/tools">
    <application>
        <activity android:name="com.unity3d.player.UnityPlayerActivity"
                  android:theme="@style/UnityThemeSelector">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
        </activity>
    </application>
</manifest>

A: Please be sure that the Development build checkbox is empty in Build Settings window before creating the build.


text:
Q: Trying to call a .NET function from VBA - using RUN in VBA I have a .Net class library and have done all things needed to include it in excel. (expoting as COM visible, for com-interop and regasm'ing the dll as well)
I use excel 2007. In the excel addins, I see my 'TestLib.Functions' as checked. I am able to access the function in my VBA code as :
Set lib = New TestLib.Functions
returnVal = lib.Add(5);

This works fine.
For other code review reasons, I also saw some functions from another library accessed using the RUN method as :
Run("avSomeFunction", paramvalue)

Now, in the VBA editor, if I try to access the 'Add' function in the same way,
Run("Add", 5)

I get an error saying 'Cannot find a macro with name Add'. Is it neccesary that I should
add tlb as a reference once again in the VB editot-tools-references again, apart from doing Regasm for the .net dll? Can someone please let me know what is the problem here.
p.s : for some very crazy reason, I just had this working once suddenly but again failed to work there after. very weird:(

A: Althought your question is not very straight-forward, I think that the links below will assist you in getting the solution to your problem.
First, I found a forum post explaining the same type of error you explain, "Cannot find Macro".
Second, if that doesn't work try researching using the links provided below:

*

*How to properly register your COM Library using RegAsm

*Beginners Guide to using .NET in VBA

*Create .NET COM Library for VBA
If this does not solve your problem, please edit your question to include additional information.

A: Difference between : adding a tlb as reference to invoke function VS using 'Run'? has the answer to this. Basically, I was missing the reference to the tlb in the VBA project. Apart from registering the dll, the tlb also needs to be added as a reference.


text:
Q: No "Add to library" button when on a file I am trying to add this fil(math parser) to my library, but there seems to be no "add to library" when i right click it. Any help?
Here's the website that I downloaded the files from idk if it will help but it's here: https://mathparser.org/mxparser-api/

I use JDK 8.

A: The easiest way to manage dependencies for a library is to use a build tool like Maven or Gradle. These tools help you to download and utilize dependencies in your own software and give attribution to the original authors as well as include the necessary license files. You tagged this with Android Studio so I assume this is going to be a library for Android applications. Most Android applications use Gradle as a build tool. Your application probably has a build.gradle where you can more easily manage your dependencies.

A: Instead of jar download I suggest just to add proper dependency to the gradle file
Maven – Gradle
implementation 'org.mariuszgromada.math:MathParser.org-mXparser:5.0.6'

Maven – Gradle (Kotlin)
implementation("org.mariuszgromada.math:MathParser.org-mXparser:5.0.6")


text:
Q: Is it possible to compile all the JSPs at build time and deliver them in the /classes folder of the WAR? I have a Java / Spring MVC web app in a WAR file.
The WAR file will be downloaded by corporate customers, so I need to obfuscate the classes in the WAR.  The obfuscater I'm using (Allatori) nicely obfuscates all of the classes in the /classes folder in the WAR.
The problem is, the JSPs (which are uncompiled) are referencing the Java classes by their original (unobfuscated) names.
I'm thinking if the JSPs were compiled and in the /classes folder, the obfuscater would get those too.
My question is ... is there a way to compile the JSPs at build time and have them included in the /classes folder?

A: You can use The Apache Sling JSPC Maven Plugin which does exactly what you need.


text:
Q: Logistic growth model applied a problem here is the exact question I'm having trouble with:
A rumor spreads through a school. Let ()
be the fraction of the population that has heard the rumor at time
and assume that the rate at which the rumor spreads is proportional to the product of the fraction  of the population that has heard the rumor and the fraction 1− that has not yet heard the rumor.
The school has 1000 students in total. At 8 a.m., 107 students have heard the rumor, and by noon, half the school has heard it. Using the logistic model explained above, determine how much time passes before 90% of the students will have heard the rumor.
Thank you in advance.


text:
Q: Signing a SOAP certificate in Delphi 2010 I'm working on signing some SOAP XML in Delphi 2010.
I've got most of it worked out (and I do have a .net working example)
I've got the c14n and digests all worked out 100%
I'm quite confident I'm doing the right thing with my signing certificate.
I just can't get the windows CryptoAPI to generate the actual rsa-sha1 signature.
For reasons to do with backward compatibiliity and support, I'm reluctant to use a .net or java solution.
What I'm looking for is one of:

*

*A working win32 example of xmldsig (using rsa/sha1) (any language)

*Delphi code to do same, using any mixture of readily available components

*A library I can use (must be royalty free and easy to distribute. Would prefer open source, but a commercial one would be acceptable if it works OK)

*Some hints on using the .net libraries from Delphi 2010

*Definitive confirmation that a later version of Delphi will handle signed soap.
Any hints appreciated.


text:
Q: python numpy machine epsilon I am trying to understand what is machine epsilon. According to the Wikipedia, it can be calculated as follows:
def machineEpsilon(func=float):
    machine_epsilon = func(1)
    while func(1)+func(machine_epsilon) != func(1):
        machine_epsilon_last = machine_epsilon
        machine_epsilon = func(machine_epsilon) / func(2)
    return machine_epsilon_last

However, it is suitable only for double precision numbers. I am interested in modifying it to support also single precision numbers. I read that numpy can be used, particularly numpy.float32 class. Can anybody help with modifying the function?

A: An easier way to get the machine epsilon for a given float type is to use np.finfo():
print(np.finfo(float).eps)
# 2.22044604925e-16

print(np.finfo(np.float32).eps)
# 1.19209e-07

A: It will already work, as David pointed out!
>>> def machineEpsilon(func=float):
...     machine_epsilon = func(1)
...     while func(1)+func(machine_epsilon) != func(1):
...         machine_epsilon_last = machine_epsilon
...         machine_epsilon = func(machine_epsilon) / func(2)
...     return machine_epsilon_last
...
>>> machineEpsilon(float)
2.220446049250313e-16
>>> import numpy
>>> machineEpsilon(numpy.float64)
2.2204460492503131e-16
>>> machineEpsilon(numpy.float32)
1.1920929e-07

A: Another easy way to get epsilon is:
In [1]: 7./3 - 4./3 -1
Out[1]: 2.220446049250313e-16


text:
Q: How to apply Win2D Blur effect to a picture from gallery? I have been searching something to blur an image and i found Win2D and Nokia Lumia Sdk. I wanna use Win2D to blur an image. But im unable to assign picture from gallery to [CanvasBitmap][1]. I just want to select an image from gallery and apply blur effect using Win2D. I tried this [tutorial][2] but I couldn't assign my own image and it gives an error:
Cannot implicitly convert type 'Windows.UI.Xaml.Controls.Image' to 'Microsoft.Graphics.Canvas.CanvasBitmap'[1]:


text:
Q: Android - Register a dynamic number of textviews I'm trying to figure out to how to tell which TextView is clicked. I have a different amount of them each time and I'm trying to figure out how to tell which one was clicked. Thanks
    ScrollView sv = new ScrollView(this);
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    sv.addView(ll);
    for (int i =0; i < myArray.size(); i++) {
        TextView tv = new TextView(this);
        tv.setText(myArray.get(i).toString());
        tv.setOnClickListener(this);
        ll.addView(tv);
    }

@Override
public void onClick(View v) {
    //how do I tell the textviews apart?
}

A: See this:
    ScrollView sv = new ScrollView(this);
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    sv.addView(ll);
    for (int i =0; i < myArray.size(); i++) {
        TextView tv = new TextView(this);
        tv.setText(myArray.get(i).toString());
        tv.setTag("myTag_"+i);
        tv.setOnClickListener(this);
        ll.addView(tv);
    }

@Override
public void onClick(View v) {

    String tag = v.getTag(); // is myTag_6 for example

    //how do I tell the textviews apart?
}

A: The View parameter of the onClickis the View that was clicked. So if the TextViews have different IDs you could do this
public void onClick(View v){
     switch(v.getId()){
         case R.id.text1: //textview with id text1 was clicked
     }
}