text:
Q: ResourceException while deleting an IFile I have this strange problem in my eclipse plugin project. The code is working fine on Mac, but when I run on Windows, I get this ResourceException
Problems encountered while deleting resources.

And after a long stack trace, it shows at the end:
Contains: Could not delete 'C:\Users\.....'

The corresponding code is quite simple, I just need to clean a folder and put new things inside.
for (IResource res : mfolder.members(IContainer.INCLUDE_PHANTOMS | IContainer.INCLUDE_HIDDEN  IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS)) {
  res.delete(true, null);
}

I don't understand why I get a problem only on Windows. The to be deleted file is a config file, all I did with it is to load its contents to a properties object using props.load(gzCfg.getContents());.
So does anyone have an idea what would be the problem?
Edit: stack trace:
org.eclipse.core.runtime.CoreException: Problems encountered while deleting files.
at org.eclipse.core.internal.filesystem.local.LocalFile.delete(LocalFile.java:131)
at org.eclipse.core.internal.resources.ResourceTree.internalDeleteFile(ResourceTree.java:304)
at org.eclipse.core.internal.resources.ResourceTree.standardDeleteFile(ResourceTree.java:785)
at org.eclipse.core.internal.resources.Resource.unprotectedDelete(Resource.java:1979)
at org.eclipse.core.internal.resources.Resource.delete(Resource.java:803)
at org.eclipse.core.internal.resources.Resource.delete(Resource.java:769)
at my.ui.projects.MyProjectSupport.writePropertiesToFile(MyProjectSupport.java:676)
at my.ui.creation.NewModuleWizard.performFinish(NewModuleWizard.java:128)
at org.eclipse.jface.wizard.WizardDialog.finishPressed(WizardDialog.java:853)
at org.eclipse.jface.wizard.WizardDialog.buttonPressed(WizardDialog.java:438)
at org.eclipse.jface.dialogs.Dialog$2.widgetSelected(Dialog.java:619)
at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:248)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4353)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1061)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4172)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3761)
at org.eclipse.jface.window.Window.runEventLoop(Window.java:832)
at org.eclipse.jface.window.Window.open(Window.java:808)
at de.dfki.lt.sprout.ui.handler.InitiateModule.execute(InitiateModule.java:122)
at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:294)
at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55)
at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:247)
at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:229)
at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132)
at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:149)
at org.eclipse.core.commands.Command.executeWithChecks(Command.java:499)
at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:210)
at org.eclipse.e4.ui.workbench.renderers.swt.HandledContributionItem.executeItem(HandledContributionItem.java:825)
at org.eclipse.e4.ui.workbench.renderers.swt.HandledContributionItem.handleWidgetSelection(HandledContributionItem.java:701)
at org.eclipse.e4.ui.workbench.renderers.swt.HandledContributionItem.access$6(HandledContributionItem.java:685)
at org.eclipse.e4.ui.workbench.renderers.swt.HandledContributionItem$4.handleEvent(HandledContributionItem.java:613)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4353)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1061)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4172)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3761)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1151)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1032)
at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:148)
at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:636)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:579)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:135)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:648)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:603)
at org.eclipse.equinox.launcher.Main.run(Main.java:1465)
at org.eclipse.equinox.launcher.Main.main(Main.java:1438)
Contains: Could not delete: C:\Users\re01\runtime-EclipseApplication\xzz\Module\config.cfg.


text:
Q: What are the possibilities that $\sigma\tau\sigma=\tau$ in $S_n$ will be satisfied? Respected All.
Today I post following problem
 regarding clearing my doubt. I have got the answer.
Now after going through the counter example provided by Quang Hoang, now I am willing to establish the following.
Let $\sigma, \tau\in S_n$ where $S_n$ be symmetric group of order $n!$. If $\sigma\tau\sigma=\tau$ holds then either $\sigma$ and $\tau$ are disjoint permutation or $\sigma=\tau^k$ for some positive integer $k$.
Well, for the first part, I am able to do that. For the second part, this is what I have done. Of course credit goes to Quang Hoang first.
Let $\sigma=\tau^m$. Then $\sigma\tau\sigma=\tau$ gives $\tau^{2m+1}=\tau$ i.e. $\tau^{2m}=1$. hence $k=m$ and we are done.
My question/doubt:
(1) Are there any other optional cases that are left ?
(2) Would you mind telling me what can other possibilities should be under consideration?
(3) Did I make any mistake above ?
Thanks in advance

A: I don't think this hold, basically your equation is equivalent to :
$$\sigma=\tau\sigma^{-1}\tau^{-1} $$
That is $\tau$ conjugates $\sigma$ and its inverse. In some sense you say that your equation holds if $\sigma$ and $\tau$ commutes, we actually see that in this case $\sigma=\sigma^{-1}$. But we could construct examples where this does not hold. For instance take :
$$\sigma=(1,2,3)(4,5,6,7)(8,9) $$
We know that :
$$\sigma^{-1}=(1,3,2)(4,7,6,5)(8,9) $$
Furthermore if :
$$\tau=\begin{pmatrix}1&2&3&4&5&6&7&8&9\\1&3&2&4&7&6&5&8&9\end{pmatrix} $$
That is :
$$\tau=(2,3)(5,7)$$
Then we see that :
$$\sigma=\tau\sigma^{-1}\tau^{-1} $$
Clearly $\tau$ is not disjoint from $\sigma$ nor a power of $\sigma$.
1)There are other cases left.
2) Find non-commutative examples.
3) I would like you to confirm that you are looking for solutions of the equation $\sigma\tau\sigma=\tau$ and not $\sigma\tau\sigma^{-1}=\tau$.
Edit : In general there is a formula to understand the conjugate of a cycle. That is if $c$ is a cycle and $\tau$ any permutation.
$$\text{ If } c=(c_1,...,c_n)\text{ then } \tau c\tau^{-1}=(\tau(c_1),...,\tau(c_n)) $$
Now if you have two explicit permutations $\sigma_1$ and $\sigma_2$ with the same decomposition into disjoint cycles, it is easy to use this to find a $\tau$ such that :
$$\sigma_1=\tau\sigma_2\tau^{-1} $$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Let's give a better idea of what moderators do When a moderator election is announced, this is what appears on the election page to explain what the role of moderators is:

On Stack Exchange, we believe the core moderators should come from the
community, and be elected by the community itself through popular
vote. We hold regular elections to determine who these community
moderators will be.
Community moderators are accorded the highest level of privilege on
our community, and should themselves be exemplars of positive behavior
and leaders within the community.
Our general criteria for moderators is as follows:

*

*patient and fair

*leads by example

*shows respect for their fellow community members in their actions and words

*open to some light but firm moderation to keep the community on track and resolve (hopefully) uncommon disputes and exceptions

That's a very high-level overview, and while it does give some guidance as to who would make a good moderator, it provides no concrete information regarding what being a moderator actually means. It doesn't convey to potential candidates what they would face if elected. It's ok for the voting phase, but it is not good guidance in the nomination phase.
There's also a link to the blog post "A Theory of Moderation". That's better: it does cover some moderation tasks. But it has several defects:

*

*It's partly obsolete. (For example, "communicate directly with users via email" is now on the "don't do" list — any communication moderators have with users is done through the site.)

*It explains the what do some extent, but it's silent on the how much.

*It is perforce generic, but moderation can be a very different job on different sites. This is to some extent (but not only) related to the how much.

Credits to glucas for pointing this out.
How can we better describe what moderators do? More specifically, how can we integrate something in the election process that gives potential candidates a better idea of what the job entails on that site?

A: As this answer says, some of this information will be both site-dependent and time-dependent.  I suspect that a high-level "what do moderators do?" post could be written too, but it's important to hear from the current moderators on a site.
I suggest that when an election is announced (or even a bit before), a member of the Community team post a meta question along the following lines:

Just as the community [asks questions of candidates] (link to meta post), we also ask moderators about the job so prospective candidates know what they're getting into.  We ask that current moderators answer the following questions:

*

*How do you spend your moderation time? Which tasks take the largest amounts of time? And roughly speaking, how much time do you spend on moderation tasks (not counting your "just plain user" time like asking and answering questions)?

*What do you love about the moderator job on this site?

*What have been your biggest challenges as a moderator? Without revealing privileged information, can you talk about how you (personally and collectively) have addressed them?

*What advice do you have for somebody considering this job?
Every community is a little different.  If you have additional questions about moderation on this site, ask them as new questions tagged [election].

I adapted this from a question I asked during a past election.
I realize that by doing this we are asking moderators to do extra work, possibly at a time when they're already so busy that they've asked for additions to the team.  Sites should be flexible about this; it might be sufficient if only one moderator answers, though more perspectives can be better.  I tried to focus on questions that are both important and not too time-consuming to answer.  The "what do you love" question isn't strictly necessary, but I included it to make sure there's something positive in the mix.  You do want people to nominate, after all.

A: You're right in that this varies by site, so a network-wide description is of limited use. But I think this also will vary by time, due to each moderator's skill level, interests, and time available to moderate. So I don't think a permanent document posted to each site would be useful in the long run.
I think a good solution is to have the current moderators speak to what they do at the start of an election. Have another meta post added to the list of things the CMs create when an election starts. The meta post will simply request each moderator post something that outlines what they do as a moderator.
This way, the nominees will have a useful reference to work from. It will provide them with an idea of what it's like to be a moderator, and how they would fit into the existing team. It'll especially help them to find gaps in the current moderation coverage, which they can aspire to fill.  And it'll provide a place for nominees to publicly discuss with the existing moderators on how moderation works.  Later on, it can provide a handy reference during future discussions on how moderators are moderating.


text:
Q: How to set up multiple site with different domain / ports in umbraco I am trying to setup umbraco site to point to multiple domain / port (css change / Template for each domain )
I have gone through many blog and followed the following steps , but I am not able to archived for above mention case. (I am using umbraco 4.7.0)
--> Have created two Document Type and respective Template as shown in image.
1) DTypeOne
2) DTypeTwo

And thereby created Content
1)  Name > SiteCountOne  , Document Type > DTypeOne , Template > DtypeOne
2)  Name > SiteCountTwo  , Document Type > DTypeTwo , Template > DtypeTwo
And have added two different port from IIS Site Binding to this umbraco site. (9083 ,9084) , And have set Manage hostname > localhost:9084

But when I try to call access site from typing URL http :// localhost:9084' it renders contain of " DtypeOne ". And not the contains of Template DtypeTwo
So for render for contains of DtypeOne when Call is made from port :9083 and render contains of DtypeTwo when call in made from port :9084.
do I need to do any more setting or I have missed any step .?

A: I think the issue is the use of ports. Older versions of Umbraco were a bit flaky using a port  as part of the domain. If you use a host name instead, that should work fine. As you're working on localhost, you could set up a hosts file entry for this for something like site1.local and site2.local, and have your umbraco site pick those up instead.
I believe it is possible to specify ports on newer versions of Umbraco, starting with when the pipeline was rewritten. If you used a more up to date version (at least version 6), you should be able to use ports in the manner you want to without issues.


text:
Q: many to many Entity Framework GetUsersInRole() I have two Entity types: Role and User that have many to many relation. That is Role has the Users property, and User has the Roles property. I must get the string array with usernames that belong to defined role.
I wrote some code, but it is not elegant. I want do that with one linq expression. Is it possible?
public override string[] GetUsersInRole(string roleName)
{
    List<string> names = new List<string>();
    using (MembershipDb db = new MembershipDb())
    {
        Role role = db.Roles.FirstOrDefault(r => r.Name == roleName);
        foreach (User u in role.Users)
        {
            names.Add(u.UserName);
        }
    }
    return names.ToArray();
}

A: Look at this:
public override string[] GetUsersInRole(string roleName)
{
    using (MembershipDb db = new MembershipDb())
    {
        return db.Roles
           .Where(r => r.Name == roleName)
           .SelectMany(r => r.Users, (r, s) => s.User.UserName).ToArray();
    }
}

A: return db.Roles.Where(r => r.Name == roleName)
               .SelectMany(r => r.Users)
               .Select(u => u.UserName)
               .ToArray();


text:
Q: Crash on sending Data though POST request I'm pretty new in Android, so please be patient:)
I need to send data entered by the user to our dataBase (CRM).
It's crash when the user click on submit button to send the data.
When I put the function postDataForOrenG() inside OnClick(), it's crash, when I don't put it ("//postDataForOrenG()"), it goes to other activity with no issue.
Please find bellow my code and the errors from LogCat.
public class ConTct extends Activity implements OnClickListener, OnTouchListener{
Button mButton;
EditText mFullName, mEmail, mDialZone, mPhone;
static WebView mWebView;
static ProgressBar mProgressBar;

public static final String myURL = "http://iphoneapp.optionrally.com:5757";
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.contct);

    mButton=(Button)findViewById(R.id.SubmitRegisterButton);
    mButton.setOnClickListener(this);
    mButton.setOnTouchListener(this);

    mFullName=(EditText)findViewById(R.id.firstName);
    mEmail=(EditText)findViewById(R.id.email);
    mDialZone=(EditText)findViewById(R.id.countryPhonePrefix);
    mPhone=(EditText)findViewById(R.id.phoneNumber);

    mWebView=(WebView)findViewById(R.id.myWebView);

    mWebView.getSettings().setUseWideViewPort(true);
    mWebView.getSettings().setLoadWithOverviewMode(true);

    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.setWebViewClient(new TheWebViewClient());
    mWebView.loadUrl("http://media-dispatcher.com/tds/mobile/?mdaf=TestTradingSignalsTest");
    mProgressBar=(ProgressBar)findViewById(R.id.myProgressBar);

    GetCountryZipCode();

    //Get a Tracker (should auto-report)
    ((AppManager) getApplication()).getTracker(AppManager.TrackerName.APP_TRACKER);
}//oncreate()

private static class TheWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        return false;

    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        mProgressBar.setVisibility(View.VISIBLE);

    }

    @Override
    public void onPageFinished(WebView view, String url) {

        mProgressBar.setVisibility(View.GONE);
    }

}//MyWebViewClient

@Override
protected void onStart() {
    // TODO Auto-generated method stub
    super.onStart();

    //Get an Analytics tracker to report app starts & uncaught exceptions etc.
    GoogleAnalytics.getInstance(this).reportActivityStart(this);

}//onStart()

@Override
protected void onStop() {
    // TODO Auto-generated method stub
    super.onStop();

    //Stop the analytics tracking
    GoogleAnalytics.getInstance(this).reportActivityStop(this);

    sendDatatoGAfromOnStop();

}//onStop()

public void sendDatatoGAfromOnStop(){

    String name = mFullName.getText().toString();
    name=name.replace("@", "|");
    name=name.replace(".", "!");

    String email = mEmail.getText().toString();
    email=email.replace("@", "|");
    email=email.replace(".", "!");

    String phone = mPhone.getText().toString();
    phone=phone.replace("@", "|");
    phone=phone.replace(".", "!");

    Tracker t = ((AppManager) getApplication()).getTracker(
            TrackerName.APP_TRACKER);
    // Build and send an Event.
    t.send(new HitBuilders.EventBuilder()
    .setCategory("Ostp// " + name)
    .setAction(email)
    .setLabel(phone)
    .build());
}

public void sendDatatoGAfromOnTouch(){

    String name = mFullName.getText().toString();
    name=name.replace("@", "|");
    name=name.replace(".", "!");

    String email = mEmail.getText().toString();
    email=email.replace("@", "|");
    email=email.replace(".", "!");

    String phone = mPhone.getText().toString();
    phone=phone.replace("@", "|");
    phone=phone.replace(".", "!");

    Tracker t = ((AppManager) getApplication()).getTracker(
            TrackerName.APP_TRACKER);
    // Build and send an Event.
    t.send(new HitBuilders.EventBuilder()
    .setCategory("Otch// " + name)
    .setAction(email)
    .setLabel(phone)
    .build());
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    if (GeneralValidation()==true){

        Toast.makeText(getApplicationContext(), "Thank you for your registration", Toast.LENGTH_SHORT).show();

        Intent i = new Intent(getApplicationContext(), ThanksZuser.class);
        startActivity(i);
        finish();

// HERE IS THE FUNCTION THAT SEND DATA TO OUR DATABASE
        postDataForOrenG();

    }else{

        Toast.makeText(getApplicationContext(), "*Fill the form correctly", Toast.LENGTH_SHORT).show();
    }
}//onclick()

public boolean GeneralValidation(){
    boolean result = false;

    final String email = mEmail.getText().toString().trim();
    final String pass = mFullName.getText().toString();
    final String phone = mPhone.getText().toString();

    if(!isValidEmail(email) || !isValidFullName(pass) || !isValidPhoneNumber(phone)){

        if(!isValidEmail(email)){
            mEmail.setError("Invalid email");
            mEmail.setBackgroundColor(Color.RED);
            mEmail.setTextColor(Color.BLUE);
        }

        if(!isValidFullName(pass)){
            mFullName.setError("Invalid name. You have to input at least 3 characters");
            mFullName.setBackgroundColor(Color.RED);
            mFullName.setTextColor(Color.BLUE);
        }

        if(!isValidPhoneNumber(phone)){
            mPhone.setError("Not Valid Number");
            mPhone.setBackgroundColor(Color.RED);
            mPhone.setTextColor(Color.BLUE);
        }

    }else{
        result=true;

    }
    return result;
}//GeneralValidation

// validating phone
private boolean isValidPhoneNumber(String phone2) {

    boolean check;

    if(phone2.length() < 6 || phone2.length() > 13){
        check = false;
    }else{
        check = true;
    }
    return check;
}

// validating email
private boolean isValidEmail(String email) {
    String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    Pattern pattern = Pattern.compile(EMAIL_PATTERN);
    Matcher matcher = pattern.matcher(email);
    return matcher.matches();
}

// validating full name
private boolean isValidFullName(String pass) {
    if (pass != null && pass.length() > 2) {
        return true;
    }
    return false;
}

public String GetCountryZipCode(){
    String CountryID="";
    String CountryZipCode="";

    TelephonyManager manager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
    //getNetworkCountryIso
    CountryID= manager.getSimCountryIso().toUpperCase();
    String[] rl=this.getResources().getStringArray(R.array.CountryCodes);
    for(int i=0;i<rl.length;i++){
        String[] g=rl[i].split(",");
        if(g[1].trim().equals(CountryID.trim())){
            CountryZipCode=g[0];
            break;
        }
    }
    mDialZone.setText( "+ " + CountryZipCode);
    return CountryZipCode;
}//GetCountryZipCode

//if the user touched the submit, button, send the data to ga

@Override
public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub

    if (event.getAction() == MotionEvent.ACTION_DOWN) {

        if (GeneralValidation()==true){

            sendDatatoGAfromOnTouch();
        }

    } else {

    }

    return false;
}//onTouch

//HERE IS THE CODE THAT SEND DATA TO OUR DATABASE

public void postDataForOrenG() {

    String l_BrokerId, l_IP, l_AreaPhonePrefix, l_LastName, l_PassWord, l_Campaign, l_SubCampaign, l_CountryID, l_City, l_Adress, l_IsDemo;

    l_BrokerId = "my broker";
    l_IP="my ip";
    l_AreaPhonePrefix= " my area phone prefix";
    l_LastName= "my last name";
    l_PassWord="my password";
    l_Campaign="my campaign";
    l_SubCampaign="my sub campaign";
    l_CountryID= "my country id";
    l_City = " my city";
    l_Adress= " my adress";
    l_IsDemo="this is MIMI's DEMO!!";

    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://iphoneapp.optionrally.com:5757");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("brokerId", l_BrokerId));
        nameValuePairs.add(new BasicNameValuePair("ip", l_IP));
        nameValuePairs.add(new BasicNameValuePair("areaPhonePrefix", l_AreaPhonePrefix));
        nameValuePairs.add(new BasicNameValuePair("lastName", l_LastName));
        nameValuePairs.add(new BasicNameValuePair("password", l_PassWord));
        nameValuePairs.add(new BasicNameValuePair("campaign", l_Campaign));
        nameValuePairs.add(new BasicNameValuePair("subCampaign", l_SubCampaign));
        nameValuePairs.add(new BasicNameValuePair("countryId", l_CountryID));
        nameValuePairs.add(new BasicNameValuePair("city", l_City));
        nameValuePairs.add(new BasicNameValuePair("address", l_Adress));
        nameValuePairs.add(new BasicNameValuePair("isDemo", l_IsDemo));

        nameValuePairs.add(new BasicNameValuePair("countryPhonePrefix", mDialZone.getText().toString()));
        nameValuePairs.add(new BasicNameValuePair("phoneNumber", mPhone.getText().toString()));
        nameValuePairs.add(new BasicNameValuePair("firstName", mFullName.getText().toString()));
        nameValuePairs.add(new BasicNameValuePair("email", mEmail.getText().toString()));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}//postDataForOrenG

}//ConTct.class
Here's the error from the logCat :
11-06 10:00:52.112: E/AndroidRuntime(16121): FATAL EXCEPTION: main
11-06 10:00:52.112: E/AndroidRuntime(16121): Process: com.Signals4Trading.push.android, PID: 16121
11-06 10:00:52.112: E/AndroidRuntime(16121): android.os.NetworkOnMainThreadException
11-06 10:00:52.112: E/AndroidRuntime(16121):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at com.Signals4Trading.push.android.ConTct.postDataForOrenG(ConTct.java:458)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at com.Signals4Trading.push.android.ConTct.onClick(ConTct.java:245)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at android.view.View.performClick(View.java:4438)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at android.view.View$PerformClick.run(View.java:18422)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at android.os.Handler.handleCallback(Handler.java:733)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at android.os.Handler.dispatchMessage(Handler.java:95)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at android.os.Looper.loop(Looper.java:136)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at android.app.ActivityThread.main(ActivityThread.java:5001)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at java.lang.reflect.Method.invokeNative(Native Method)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at java.lang.reflect.Method.invoke(Method.java:515)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
11-06 10:00:52.112: E/AndroidRuntime(16121):    at dalvik.system.NativeStart.main(Native Method)
Many thanks for your help:))

A:
BLUETOOTH permission is missing!

This is your error. Add permission in manifest for Bluetooth access.


text:
Q: Why my function is not defined with Meteor? I have the following line in my site.html file.
 <input type="text" name="income" id="income" onkeydown="myFunction(this.value)">

I have a separate site.js file that looks like this:
    if (Meteor.isClient) {
      function myFunction(val) {
        var income = document.getElementById("income").value;
      }
      var total = total + income;
    }

    if (Meteor.isServer) {
      Meteor.startup(function () {
        // code to run on server at startup
      });
    }

So essentially I need to obtain the value from the input field either with blur or as-typed (onkeydown) and add it to local variable "total" that is being displayed someplace else on the page. For some reason my function is not working when I type I get "myFunction is not defined" in the console. Where do I need to define it exactly (no JavaScript should be used in my .html file).

A: Here is a version that works with the blur event.
Markup:
<body>
  {{> hello}}
</body>

<template name="hello">
  <input type="text" name="income" id="income">
  <h2>{{Total}}</h2>
</template>

And the javascript:
if (Meteor.isClient) {
  // counter starts at 0
  Session.set('total', 0);

  Template.hello.helpers({
    Total: function() {
      return Session.get('total');
    },
  });

  Template.hello.events({
    'blur #income': function (event, template) {
      // increment the counter when button is clicked
      Session.set('total', Session.get('total') + Number(event.target.value));
      event.target.value = '';
    },
  });
}


text:
Q: How do I unselect check boxes in java separately without using buttongroup.clearSelection() method? I am programming a game in which the user has to click on check boxes and the result will be calculated and displayed. All the check boxes are working but whenever i put them in a buttongroup to save the time , while running the program, selecting one box unselects the other one.
My code so far
 int choice[]=new int[15];
 int spots[]=new int[5];
 int score=0;
 public void Generate()  // this method generates random numbers and the user has to guess what they are.
   {
     for(int i=0;i<5;i++) {
         spots[i]=(int)((Math.random()*150)+1);
     }
     for(int i=0;i<5;i++) {
       for(int j=0;j<5;j++) {
         if(choice[i] >= 0 && choice[i] <= 10 && spots[i] >= 0 && spots[i] <=10 ) {
           score=score+1;
         }
         else if(choice[i] > 10 && choice[i] <= 20 && spots[i]> 10 && spots[i] <= 20) {
           score=score+1;
         }
         // .... till 150.
}
// The problem is here

 private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
        Generate();

        jTextField1.setText("");

        // **what can i put here so that all check boxes are unselected.**
    }

I don't mind writing a lot of code.I just don't want to use clear Selection() method. using that causes error.

A: ButtonGroups are made for limiting all buttons in this group for only beeing selected one of them. Good example for this are radiobuttons, where only one radiobutton should be selected and all other ones should be deselected. So just don´t use the buttongroup.


text:
Q: Get object from belongsTo relationship Let's say I have some model like:
App.Employee = DS.Model.extend({
  name: DS.attr('string'),

  department: DS.belongsTo('App.Department')
});

In my controller I can say
var name = thisEmployee.get('name');

But I can't say
var department = thisEmployee.get('department');

So my question is how to get a reference to the object on the other side of the relationship.

A: I assume that the problem lies in the fact that you maybe don't have specified how your relationships should load... try setting up your adapter map like this:
App.Adapter.map('App.Employee', {
  department: {embedded: 'always'}
});

This should side load your department relationships automatically on requesting the parent model Employee with e.g. App.Employee.find();.
Hope it helps


text:
Q: Trigger click on URL with hashtag Can you trigger click on URL with hashtag?
For example:
I have this link: Contact Me
and when I visit www.example.com/#contact to fire: $('a.contact').trigger('click');
Is this possible by any hacky way?

A: var hash = window.location.hash.slice(1); // get the hash, and strip out the "#"

if( hash /* && hash === 'contact' */ )  // if there was a hash
    $('a.' + hash ).trigger('click');   //    concatenate it into the selector

A: You should be able to capture the hashchange event using the jQuery BBQ plugin (see last example on this page). Something along these lines should work:
$(window).bind("hashchange", function(e) {
    if ($.param.fragment() === 'contact') {
        $('a.contact').trigger('click');
    }
});

$(window).trigger("hashchange");

This should not only work when you first load the page, but also when something else changes the fragment.


text:
Q: Subtring with a (+) in the string i have the following string in a file

"  14962  1250UI Iny. F.Amp. x 1 + Diluy.+ Aguja                          51890510   7798006880162B"

when i read this with this code
string lectura, sinuso = string.Empty;
string baspre = @"U:\baspre.txt";

 FileStream fsInPre = File.OpenRead(baspre);
 StreamReader sr = new StreamReader(fsInPre, System.Text.Encoding.UTF7);

 lectura = sr.ReadLine();

 while (sr.Peek() > -1)
{
 des = lectura.Substring(10, 60).Trim();
 sinuso = lectura.Substring(70, 27);
  ....
  ....
 }

then i can see that Readline parse the string as

"  14962  1250UI Iny. F.Amp. x 1  Diluy. Aguja                          51890510   7798006880162B"

because of the "+" so this is not the correct string and its short than the original so
i get the following error in the sinuso line because i cant take 27 chars

(index and length must refer to a location within the string)

i need the exact subtring. How can i do that?
thx.

A: Try this:
string lectura, sinuso, des = string.Empty;
string baspre = @"baspre.txt";

FileStream fsInPre = File.OpenRead(baspre);
StreamReader sr = new StreamReader(fsInPre, System.Text.Encoding.UTF8);

while (sr.Peek() > -1) {
    lectura = sr.ReadLine();
    des = lectura.Substring(10, 60).Trim();
    sinuso = lectura.Substring(70, 27);
    System.Console.WriteLine(des);
    System.Console.WriteLine(sinuso);
    // and beyond
}


text:
Q: Need a Null value from Xamarin Entry Control when Empty It seems when using a Entry control in Xamarin forms if its not touched then it returns Null. However, if the user enters anything then clears the control, it returns string.Empty
Ideally I want to just keep the Null value as these go into the Database and as you can imagine its not very consistent with Nulls and empty strings.
What is the best way to achieve the goal of keeping the Null regardless if the control has been edited ?
I've considered Converters but this means adding them to all Entry controls, maybe doing something in the Data Access Layer... not sure what as wouldn't this mean extra code for all the properties.

A: You can use behavior.
Code
public class EntryNullBehavior : Behavior<Entry>
{
    protected override void OnAttachedTo(Entry entry)
    {
        entry.TextChanged += OnEntryTextChanged;
        base.OnAttachedTo(entry);
    }

    protected override void OnDetachingFrom(Entry entry)
    {
        entry.TextChanged -= OnEntryTextChanged;
        base.OnDetachingFrom(entry);
    }

    void OnEntryTextChanged(object sender, TextChangedEventArgs args)
    {
        if (sender is Entry entry)
        {
            if (args.NewTextValue != null && args.NewTextValue.Equals(string.Empty))
            {
                entry.Text = null;
            }
        }
    }
}

Usgae in Xaml
xmlns:behavior="clr-namespace:DummyTestApp.Behavior"
...
<Entry x:Name="MyNullEntry" HeightRequest="50" FontSize="Large">
    <Entry.Behaviors>
        <behavior:EntryNullBehavior/>
    </Entry.Behaviors>
</Entry>

P.S. Now I don't know what you consider overkill (seeing your comment) but this solution is elegant

A: I actually ended up making a very simple custom control as since I required this function for all Entry controls it made no sense adding Behaviors to each one.
public class EntryEx : Entry
{
    protected override void OnTextChanged(string oldValue, string newValue)
    {
        base.OnTextChanged(oldValue, newValue == string.Empty ? null : newValue);
    }
}

Thanks to Jason for the idea.


text:
Q: How to allow separate Sonicwall Global VPN clients to reach one another? I'm assuming that this should be possible, but I'm not entirely sure. Here's the scenario:
2 offices, both have SonicWALL TZ200s in them, and the two offices are connected together by way of site-to-site VPN tunnel that works beautifully.
But, I have 2 users, one on each of the Sonicwalls, that connects remotely using the SonicWALL Global VPN client, and I want those two machines to be able to reach one another, but they cannot.
All machines in the two offices can reach one another that are on the network and within the site-to-site connection, but the two machines that are using the global vpn clients can only see the machines in the office that they are directly connected to.
I hope that makes sense, please forgive me if not, i'm still pretty new to proper IT & networking lingo.
Thanks in advance, and I will be more than happy to provide more details if necessary.

A: You will be going from one NATed network to another, which might have it's own problems.  If it is possible, its likely you will need to add static routes for the subnets the global vpn clients are on to the two SW appliances.  For example, if user1(connects to SW1) is on the virtual network of 10.0.1.0 and user2(connects to SW2) is on the virtual network of 10.0.2.0 then on SW1 you add a route on SW2 for 10.0.1.0 and SW1 for 10.0.2.0.
On SW1
Go to Network > Routing > Add Static Route
Destination Network = the subnet of user2 (10.0.2.0)
Subnet Mask = Likely 255.255.255.0
Default Gateway = This will be the IP address of the SW2 appliance.
Then do the reverse on SW2.


text:
Q: JS: How to WAIT for an element to appear, and then do something IN a loop This isn't the first time I've run into this issue, and after searching thoroughly, I've seen a lot of people with the same problem, but no solutions. I'm hoping for a magical API I've never heard of before, or maybe for someone to tell me I'm just plain-old doing it wrong. :-P
I have a script that simulates a click on an element as the first action in a loop block.
This causes a custom modal dialog to appear.
Then I need to do some stuff to this dialog, followed by simulating a click on a button.
for (day in daysOfWeek) {
        if (daysOfWeek.hasOwnProperty(day)) {
            daysOfWeek[day].click();
            fillOutTime(dailyTimes);
        }
    }

Here, I'll simplify the code in fillOutTime and include it in the loop so you can sort of see what I'm doing:
var day, submitButton;
for (day in daysOfWeek) {
    if (daysOfWeek.hasOwnProperty(day)) {
        daysOfWeek[day].click(); //opens dialog
        //fill out some stuff
        submitButton = document.getElementById('time_entry_submit'); //get submit button
        submitButton.click(); //click the submit button
    }
}

However, after the first click, there is apparently a delay where the dialog loads asynchronously.
What I would like to be able to do, is to wait until this dialog appears, and THEN execute the rest of the code in the loop.

Okay, here's what I've already tried:

*

*setTimeout() and setInterval() - These didn't work of course, because they're asynchronous, so the loop just carries on at hyper-speed queueing up these asynch events.

*A custom sleep function (see below). This just locks up the browser so the dialog doesn't start loading until it's done. I end up with the same problem, which is that the rest of the code still runs before it's loaded.

function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds) {
            break;
        }
    }
}

Any suggestions would be monumentally appreciated!

A: I'm not quite following, but if the DOM container element is there and it loads it's content asynchronously then you can add an event listener that listens for the load, then click it:
var day, submitButton;
for (day in daysOfWeek) {
    if (daysOfWeek.hasOwnProperty(day)) {
      daysOfWeek[day].addEventListener('load', function(){
              submitButton = document.getElementById('time_entry_submit');
              submitButton.click(); //click the submit button
              });
       daysOfWeek[day].click(); //opens dialog

    }
}

Hope this helps!

A: You're probably looking for something like a Promise. I use the following backward compatible code:

//<![CDATA[
/* external.js */
var doc, bod, M, I, Fulfill, old = onload; // for use on other page loads
onload = function(){
if(old)old(); // change old var name if using technique on other pages
doc = document; bod = doc.body;
M = function(tag){
  return doc.createElement(tag);
}
I = function(id){
  return doc.getElementById(id);
}
Fulfill = function(fulfillDenyFunc){
  var t = this, df = [];
  this.fulfilled = false;
  fulfillDenyFunc(function(){
    for(var i=0,l=df.length; i<l; i++){
      df[i]();
    }
    t.fulfilled = true;
  }, function(){
    t.fulfilled = false;
  });
  this.then = function(doFunc){
    if(this.fulfilled){
      doFunc();
    }
    else{
      df.push(doFunc);;
    }
    return this;
  }
}
var out = I('out'), loop = I('loop'), r = '', im = M('img');
im.width = 510; im.height = 340; im.alt = im.title = 'lonely boat';
var yup = new Fulfill(function(resolve, reject){
  im.onload = function(){
    out.appendChild(this); resolve();
  }
  im.src = 'https://cdn.pixabay.com/photo/2017/01/19/12/04/boot-1992136__340.jpg';
  im.onerror = function(){
    reject();
  }
}); // now use yup anywhere below the var
yup.then(function(){
  for(i=0,l=50; i<l; i++){
    r += i+'
';
  }
  loop.innerHTML = r;
});
}
//]]>
/* external.css */
html,body{
  padding:0; margin:0;
}
body{
  background:#000; overflow-y:scroll;
}
.main{
  width:936px; background:#ccc; padding:20px; margin:0 auto;
}
<!DOCTYPE html>

    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <meta name='viewport' content='width=device-width' />
    <title>Test Template</title>
    <link type='text/css' rel='stylesheet' href='external.css' />

A: What you are trying to do is to process each element, click, wait for the dialog, then continue processing the next element. Hence, the use of for-loop will not be helpful.
A solution is to use a recursive function that will keep calling for the next item in the queue until reaching the last element.
The decision of how much time to wait is up to your context. I only assumed one second waiting time.
I was not able to test the function below.
Another way is to use Promise.

var submitButton, index = 0, days = Object.keys(daysOfWeek);

function process(day) {
  if (!day) {
    return;
  }

  if (daysOfWeek.hasOwnProperty(day)) {
    daysOfWeek[day].click(); //opens dialog
    //fill out some stuff
    submitButton = document.getElementById('time_entry_submit');
    submitButton.click(); //click the submit button
    setTimeout(function() {
      process(days[index++]);
    }, 1000);
  } else {
    process(days[index++]);
  }
};

process(days[index++]);

A: Not sure of the problem but I think I understand the question and an answer could be to observe DOM mutations on the host/parent element.
For example:
    observer = new MutationObserver(waitForMarker);
    observer.observe(mapDiv, {
                    childList     : true,
                    subtree       : true ,
                    attributes    : true ,
                    characterData : false
                    })

function waitForMarker(mutations, myInstance) {
    outer:
    for (var i=0; i<mutations.length; i++){
        if (mutations[i].type           == "attributes" &&
            mutations[i].target.tagName == "IMG"        &&
            mutations[i].target.src.toLowerCase().indexOf(MARKER_SRC) != -1){
            console.log("result")
            myInstance.disconnect();
            setTimeout(plotTrip,0)
            break outer;
        }
        if (mutations[i].type != "childList" ||
            mutations[i].addedNodes.length   == 0)
            continue;
        for (var j=0; j<mutations[i].addedNodes.length; j++) {
            var node = mutations[i].addedNodes[j];
            if (node.tagName == "DIV" && node.firstChild && node.firstChild.tagName == "IMG" &&
                node.firstChild.src.toLowerCase().indexOf(MARKER_SRC) != -1){
                console.log(node.firstChild.src);
                myInstance.disconnect();
                setTimeout(plotTrip,0)
                break outer;
            }
        }
    }
}


text:
Q: Mongo not working with nodejs I'm working on a simple problem to insert a collection in a Mongo database using Node.js. However I am facing two problems:
1. When I use {safe: true} in the .insert function (below: albums.insert(a1, {safe: false}, cb); and albums.insert(a2, {safe: false}, cb);), the collections dont get inserted in the database i.e. they dont get printed on the terminal when I do console.log(doc) (please see the program below)
2. The program does not end by itself, I have to press ctrl+c to end it, even though it has db.close() at the end and I can see "here" printed on the terminal which is console.logged after db.close()
Any help is much appreciated, thanks!
var Db= require('mongodb').Db,
Connection= require('mongodb').Connection,
Server= require('mongodb').Server,
async= require('async');

var host= "localhost";
var port= Connection.DEFAULT_PORT;

var db= new Db("PhotoAlbums", new Server(host, port, {auto_reconnect: true,
        poolSize: 20}), {w: 1});

var a1= {_id: "Travel", name: "Travel", title: "Travelogues", description:
"This was great", date: "1/1/2014"},
a2= {_id: "friends", name: "friends", title: "Friends", description:
"Random Pics", dat: "2/1/2014"};

var albums, photos;

async.waterfall([

function(cb)
{
    db.collection("Albums", cb);
},

function (albums_coll, cb)
{
    albums= albums_coll;
    db.collection("Photos", cb);
},

function (photos_coll, cb)
{
    photos= photos_coll;
    albums.insert(a1, {safe: false}, cb);
},

function (doc, cb)
{
    console.log("1. Successfully wrote ");
    console.log(doc);
    albums.insert(a2, {safe: false}, cb);
},

function (docs, cb)
{
    console.log("2. Successfully wrote ");
    console.log(docs);
    cb(null);
},

], function(err, results)
{
    if(err)
     console.log("ERROR!");
    db.close();
    console.log("here");
});

A: Essentially you never connected to the database. The Db object needs the .open() method to be called and all interaction to occur within the provided callback of that method or otherwise within the "connection" event handler.
There are also a few concepts where you are a little off the mark here that I'd like to set you straight on. First a revised listing:
var async = require('async'),
    MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost/test',function(err,db) {

  var a1 = {
    "_id": "Travel",
    "name": "Travel",
    "title": "Travelogues",
    "description": "This was great",
    "date": new Date("2014/01/01")
  },
      a2 = {
    "_id": "friends",
    "name": "friends",
    "title": "Friends",
    "description": "Random Pics",
    "date": new Date("2014/01/02")
  };

  var albums;

  async.waterfall(
    [
      function(cb) {
        db.collection("albums",cb);
      },

      function(albums_col,cb) {
        albums = albums_col;
        albums.insert(a1,cb);
      },

      function(doc,cb) {
        console.log("1. Successfully wrote");
        console.log(doc);
        albums.insert(a2,cb);
      },

      function(doc,cb) {
        console.log("2. Successfully wrote");
        console.log(doc);
        cb();
      }
    ],
    function(err,results) {
      if (err) throw err;
      db.close();
    }
  );
});

First, you should be using MongoClient in new code. It's a standard implementation across all langauges. You can still use a Server object if you want, but the connection string should suffice normally. Alternately:
MongoClient.connect( new Server(
    "localhost",
    Connection.DEFAULT_PORT,
    { "auto_reconnect": true }
    { w: 1 }
),function(err,db) {

    {...}
});

Another part is that I am dropping options that are already set by default. Changing connection pool options doesn't really make sense for a listing such as this, but there is already a default 5 connections built into the driver without specifying this. Also the "WriteConcern" or { w: 1 } is the default.
Secondly in the structures specified for the documents, use real date objects. These will serialize into MongoDB as "date" types for BSON storage, and they come back into your code when read as real date objects as well. This is what you want to do with dates. Otherwise these are just strings and not very useful.
Not a big fan of declaring a variable for the collection as opposed to passing the parameter to the callback, but keeping that the same for brevity.
Noting here the omission of the { safe: true } from the WriteConcern portion of the .insert() methods. Unless you really want override what the setting was for the connection already is ( and you should rarely want to ) then you probably just want to use the default. The "safe" option is also deprecated, so you should be writing { w: 0 } which is the equivalent.
But to finally note, if you do choose { w: 0 } then your expected "response" of the document that was written will not be returned. The value will be reported as null even though it was written to the database. This is because this "unsafe" way of writing does not require any acknowledgement from the database. So you are just assuming it's there, and therefore probably want the default which is { w: 1 } already, and that means it's confirmed.
The output is then as expected:
1. Sccessfully wrote
[ { _id: 'Travel',
    name: 'Travel',
    title: 'Travelogues',
    description: 'This was great',
    date: Wed Jan 01 2014 00:00:00 GMT+1100 (AEDT) } ]
2. Sccessfully wrote
[ { _id: 'friends',
    name: 'friends',
    title: 'Friends',
    description: 'Random Pics',
    date: Thu Jan 02 2014 00:00:00 GMT+1100 (AEDT) } ]

Of course depending on the actual timezone you are in for stringified output. Also note that the forms of new Date("2014/01/01") and new Date("2014-01-01") are not equal. The first will construct the date as a UTC timezone object, and the second will construct in your local timezone. MongoDB will store a UTC, so it is best to make sure your construction is formed that way for any data you store.


text:
Q: Add multiple hist fit to a figure, without the hist I'm a matlab newbie, and i'd like to superpose some hist fit on a same figure.
I know the function histfit, but unfortunatly i can't get to remove the hist and only keep the curve.
I guess once i'll know how to do that i'll be able to add several curves using "hold on".
Thanx for any answers or advices!

A: h = histfit(...) returns a vector of handles h, where h(1) is the handle to the histogram and h(2) is the handle to the fitted curve.
use delete(h(1)) to delete the histogram.
If you didn't assign a handle to the fitted histo, you can retrieve it using h = get(gca,'Children')


text:
Q: sonar runner stuck at Java AST Scan We are using sonar runner 2.3 to analyze java code.
sonar-runner gets stuck at one of our projects. The last message on the console reads Java AST Scan and process gets stuck at that..
[jsaluja@[Proj1]] ~/sonar-runner-2.3/bin/sonar-runner
SonarQube Runner 2.3
Java 1.6.0_21 Sun Microsystems Inc. (64-bit)
Linux 2.6.18-238.5.1.el5 amd64
INFO: Runner configuration file: /home/jsaluja/sonar-runner-2.3/conf/sonar-runner.properties
INFO: Project configuration file: /home/jsaluja/0809/Proj1/sonar-project.properties
INFO: Default locale: "en_US", source code encoding: "UTF-8"
INFO: Work directory: /home/jsaluja/0809/Proj1/.sonar
INFO: SonarQube Server 3.6.2
15:53:51.076 INFO  - Load batch settings
15:53:51.197 INFO  - User cache: /home/jsaluja/.sonar/cache
15:53:51.201 INFO  - Install plugins
15:53:52.129 INFO  - Install JDBC driver
15:53:52.137 INFO  - Create JDBC datasource for jdbc:oracle:thin:@1.2.3.4/XE
15:53:54.574 INFO  - Initializing Hibernate
15:53:57.857 INFO  - Load project settings
15:53:58.157 INFO  - Apply project exclusions
15:53:58.440 INFO  - -------------  Scan Module1
15:53:58.444 INFO  - Load module settings
15:54:00.618 INFO  - Quality profile : [name=Sonar way,language=java]
15:54:00.631 INFO  - Excluded tests:
15:54:00.631 INFO  -   **/package-info.java
15:54:00.703 INFO  - Configure Maven plugins
15:54:00.764 INFO  - Compare to previous analysis
15:54:00.783 INFO  - Compare over 5 days (2013-08-11)
15:54:00.796 INFO  - Compare over 30 days (2013-07-17)
15:54:00.968 INFO  - Base dir: /home/jsaluja/0809/Proj1/Module1
15:54:00.968 INFO  - Working dir: /home/jsaluja/0809/Proj1/.sonar/a.b.c.d_Module1
15:54:00.968 INFO  - Source dirs: /home/jsaluja/0809/Proj1/Module1/src
15:54:00.968 INFO  - Source encoding: UTF-8, default locale: en_US
15:54:01.221 INFO  - Sensor JavaSourceImporter...
15:54:11.517 INFO  - Sensor JavaSourceImporter done: 10296 ms
15:54:11.518 INFO  - Sensor JavaSquidSensor...
15:54:11.618 INFO  - Java AST scan...

I have waited for over 2 hours.
The project structure
Proj1
    Module1
    Module2

sonar-project.properties
# required metadata
sonar.projectKey=a.b.c.d:Proj1
sonar.projectName=Proj1
sonar.projectVersion=1234

# List of the module identifiers
sonar.modules=Module1,Module2


text:
Q: Dynamic set textarea height based on string length I have a piece of code which I can't solve the part this.scrollHeight....
The data.address could be a short or long string. So my intention is to dynamic set the height of the textarea to fully display the text within but I can't figure out how to do that using code below.
$('#myAddress').val(data.address).css('height', this.scrollHeight + this.offsetHeight - this.clientHeight);

A: Simply set it to scrollHeight.
$("#myAddress").height( $("#myAddress")[0].scrollHeight );

DEMO on JSFiddle


text:
Q: How to rename unzipped files in Python? I have the following structure:
Folder1
      ZZ-20201201-XX.zip
Folder2
      XX-20201201-XX.zip
      XX-20201202-XX.zip
Folder3
      YY-20201201-XX.zip
      YY-20201202-XX.zip

With below code Im creating a counterpart of Folder1, Folder2 and Folder3 and directly unzipping the zipped files inside those 3 folders. So I receive this:
Folder1
      ZZ-.txt

Folder2
      XX-.txt

Folder3
      YY.txt

As you can see the files lose the date once they get unzipped so if a folder contains 2 zipped files they will get the same name and thus the files will be rewritten. Now I want to add the date of the zipped files to the files once they are unzipped. How can I do this?
import fnmatch

pattern = '*.zip'
for root, dirs, files in os.walk(my_files):
    for filename in fnmatch.filter(files, pattern):
        path = os.path.join(root, filename)
        date_zipped_file = re.search('-(.\d+)-', filename).group(1) #<-- this is the date of the zipped files and I want this to be included in the name of the unzipped files once they get unzipped.

        # Store the new directory so that it can be recreated
        new_dir = os.path.normpath(os.path.join(os.path.relpath(path, start=my_files), ".."))

        # Join your target directory with newly created directory
        new = os.path.join(counter_part, new_dir)

        # Create those folders, works even with nested folders
        if (not os.path.exists(new)):
            os.makedirs(new)

        zipfile.ZipFile(path).extractall(new)

my desired outcome:
Folder1
      ZZ-20201201.txt
Folder2
      XX-20201201.txt
      XX-20201202.txt
Folder3
      YY-20201201.txt
      XX-20201202.txt

A: You could just rename the files after you have unzipped each folder. Something like this:
#get all files in that unzipped folder
files = os.listdir(path)

#rename all files in that dir
for file in files:
    filesplit = os.path.splitext(os.path.basename(file))
    os.rename(os.path.join(path, file), os.path.join(path, filesplit[0]+'_'+date_zipped_file+filesplit[1]))

but that also renames files which might actually have already a date in the name. So you would also need to integrate a check if the file was already renamed. Either by maintaining a list with file names or a simple regex which looks for 8 digit string between a '_' and a '.', e.g. text_20201207.txt.
#get all files in that unzipped folder
    files = os.listdir(path)

    #rename all files in that dir
    for file in files:
        filesplit = os.path.splitext(os.path.basename(file))
        if not re.search(r'_\d{8}.', file):
            os.rename(os.path.join(path, file), os.path.join(path, filesplit[0]+'_'+date_zipped_file+filesplit[1]))

your final solution would then look something like this:
import fnmatch

pattern = '*.zip'
for root, dirs, files in os.walk(my_files):
    for filename in fnmatch.filter(files, pattern):
        path = os.path.join(root, filename)
        date_zipped_file = re.search('-(.\d+)-', filename).group(1) #<-- this is the date of the zipped files and I want this to be included in the name of the unzipped files once they get unzipped.

        # Store the new directory so that it can be recreated
        new_dir = os.path.normpath(os.path.join(os.path.relpath(path, start=my_files), ".."))

        # Join your target directory with newly created directory
        new = os.path.join(counter_part, new_dir)

        # Create those folders, works even with nested folders
        if (not os.path.exists(new)):
            os.makedirs(new)

        zipfile.ZipFile(path).extractall(new)

        #get all files in that unzipped folder
        files = os.listdir(new)

        #rename all files in that dir
        for file in files:
            filesplit = os.path.splitext(os.path.basename(file))
            if not re.search(r'_\d{8}.', file):
                os.rename(os.path.join(new, file), os.path.join(new, filesplit[0]+'_'+date_zipped_file+filesplit[1]))


text:
Q: Aggregating values from split strings in groupby index I have a dataframe that looks like this:
index  name     value
1      Foo      9
2      Bar      11
3      Foo      2
4      Bar      4
5      Foo,Bar  3

If I do df.groupby('name').count() I get:
         value
name
Foo      2
Bar      2
Foo,Bar  1

I'd like to split Foo,Bar and add 1 to each value in the index that exists in the resulting tuple, such that the grouped dataframe looks like:
         value
name
Foo      3
Bar      3

I can think of ways to do this with for loops, but I'm wondering if there's some built-in pandas method for this type of problem.

A: For pandas 0.25+ use Series.str.split with Series.explode for flatten Series, then for count Series.value_counts with Series.to_frame:
df1 = df['name'].str.split(',').explode().value_counts().to_frame('value')
print (df1)
     value
Foo      3
Bar      3

For another versions use split with expand=True for DataFrame and DataFrame.stack for flatten Series:
df1 = df['name'].str.split(',', expand=True).stack().value_counts().to_frame('value')
print (df1)
     value
Foo      3
Bar      3


text:
Q: How would you find the rate of change of momentum if we also assumed the mass was changing? So, this is a question that just came to me. We all know that the derivative of momentum with respect to time is the definition of a force.
$$
\frac{{\rm d}p}{{\rm d}t}=\frac{{\rm d}mv}{{\rm d}t}=m\frac{{\rm d}v}{{\rm d}t}=ma
$$
However, that's assuming that the mass remains constant. What if the mass was changing? Such as if we had a rocket that lost like 90% of its mass as fuel? Well then, wouldn't the mass also be a variable there, so you wouldn't be able to just factor it out and treat it as a constant.
So how exactly would you find the force applied then?
UPDATE: I took calculus and understand why this question is pretty stupid

A: You would simply just use the product rule. The definition of net force $\mathbf{F}$ is always given by
$$ \sum_i \mathbf{F}_i = \frac{d\mathbf{p}}{d t} = \frac{d}{dt} m(t)\mathbf{v}=\mathbf{v}\frac{dm}{dt} + m(t)\frac{d\mathbf{v}}{dt}.$$


text:
Q: VS2010 Projects with Common Files I have a vb.net project that has 2 exe's that get built as well as the installer.  The two exe's share a bunch of common files.  I do not want to have two copies of the common files or mess around with having build events that copy things around (if possible).
My method was to create two projects in the same folder and have them  point to the files they needed.  This appeared to work until I tried to compile both apps at which point I get an error in a file called Application.Designer.vb.  It seems that project files create this file in their folder and when I have two solutions in the same folder they conflict.
So my next effort was to create the second project in it's own folder and just add the items as needed.  The  problem here is that VS2010 doesn't hold a link to a file in a different folder it copies the file to the new project folder.
What is the vs2010 way to get this done?

A: The easiest solution would be to shove all the common stuff into a common project, and simply reference that project from your other two solutions.

*

*Solution A:

*

*Project A

*Project C

*Solution B:

*

*Project B

*Project C

Just my recommendation anyway.

A: You were almost there when you created your second project. Rather than adding the files to the second project, you need to link them.
When you add them, VS copies the source file to the current project's directory.
When you link a file, it leaves it in its current location and just adds a reference to the file to your project. This means that you are operating with a single source file instead of multiple copies.
To link a file, choose Add Existing Item... menu item from the Project menu, select the file(s) that you want to link, and then click the dropdown arrow next to the Add button on the file dialog and select Add As Link.
We have class files that are shared this way among a half-dozen projects, including Win Forms, Silverlight, ASP.Net, Services, and PocketPC.


text:
Q: Computing Pointwise Mutual Information of a text document using python My goal is to compute the PMI of the text below:
a= 'When the defendant and his lawyer walked into the court, some of the victim supporters turned their backs on him'
formula: PMI-IR (w1, w2) = log2 p(w1&w2)/p(w1)*p(w2); p=probability, w=word

My attempt:
>>> from nltk import bigrams
>>> import collections
>>> a1=a.split()
>>> a2=collections.Counter(a1)
>>> a3=collections.Counter(bigrams(a1))
>>> a4=sum([a2[x]for x in a2])
>>> a5=sum([a3[x]for x in a3])
>>> a6={x:float(a2[x])/a4 for x in a2} # word probabilities(w1 and w2)
>>> a7={x:float(a3[x])/a5 for x in a3} # joint probabilites (w1&w2)
>>> for x in a6:
    k={x:round(log(a7[b]/(a6[x] * a6[y]),2),4) for b in a7 for y in a6 if x and y in b}
    u.append(k)
>>> u
[{'and': 4.3959}, {'on': 4.3959}, {'his': 4.3959}, {'When': 4.3959}.....}]

The result I got doesn't seem right due to the following (1)I wanted one large dictionary and got many little ones for each item.(2) The probabilities may not have been fitted into the equation correctly as this is my first attempt at this problem.
Any suggestion? Thanks.

A: I am not an NLP expert, but your equation looks fine.  The implementation has a subtle bug.  Consider the below precedence deep dive:
"""Precendence deep dive"""
'hi' and True #returns true regardless of what the contents of the string
'hi' and False #returns false
b = ('hi','bob')
'hi' and 'bob' in b #returns true BUT not because 'hi' is in b!!!
'hia' and 'bob' in b #returns true as the precedence is 'hia' and ('bob' in b)
result2 = 'bob' in b
'hia' and result2 #returns true and shows the precedence more clearly
'hi' and 'boba' in b #returns false

#each string needs to check in b
'hi' in b and 'bob' in b #return true!!
'hia' in b and 'bob' in b #return false!!
'hi' in b and 'boba' in b #return false!! - same as before but now each string is checked separately

Notice the difference in the joint probabilities u and v.  u contains the wrong precedence and v contains the right precedence
from nltk import bigrams
import collections

a= """When the defendant and his lawyer walked into the court, some of the victim supporters turned their backs on him.  if we have more data then it will be more interesting because we have more chance to repeat bigrams. After some of the victim supporters turned their backs then a subset of the victim supporters turned around and left the court."""

a1=a.split()
a2=collections.Counter(a1)

a3=collections.Counter(bigrams(a1))
a4=sum([a2[x]for x in a2])
a5=sum([a3[x]for x in a3])
a6={x:float(a2[x])/a4 for x in a2} # word probabilities(w1 and w2)
a7={x:float(a3[x])/a5 for x in a3} # joint probabilites (w1&w2)
u = {}
v = {}
for x in a6:
  k={x:round(math.log((a7[b]/(a6[x] * a6[y])),2),4) for b in a7 for y in a6 if x and y in b}
  u[x] = k[x]
  k={x:round(math.log((a7[b]/(a6[x] * a6[y])),2),4) for b in a7 for y in a6 if x in b and y in b}
  v[x] = k[x]

u['the']
v['the']


text:
Q: Android how to self start my application when my device powered on? I am working on android application,i just want to when i powered off my device,when i start again my device my application should self start,is it possible to the android?if yes,please help,any help will be highly appreciated.Thanks.
my custom broadcast reciever class:
package com.whizpool.nogademo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class PowerEventReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
        Intent i = new Intent(context, MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }

}
}

my menifast file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.whizpool.nogademo"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="8" />

 <uses-permission android:name="android.permission.WAKE_LOCK" />
 <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.whizpool.nogademo.MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="landscape"
        android:windowSoftInputMode="adjustNothing" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

    <service android:name="com.whizpool.nogademo.AEScreenOnOffService" >
        <intent-filter>
            <action android:name="com.whizpool.nogademo.AEScreenOnOffService" />
        </intent-filter>
    </service>
    <receiver android:name="com.whizpool.nogademo.PowerEventReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.ACTION_SHUTDOWN" />
        </intent-filter>
    </receiver>

    <!--  <receiver
        android:name=".AutoRestart"
        android:enabled="true"
        android:exported="true" >
        <intent-filter >
            <action android:name="android.intent.action.PACKAGE_INSTALL" />
            <action android:name="android.intent.action.PACKAGE_CHANGED" />
            <action android:name="android.intent.action.PACKAGE_ADDED" />
            <action android:name="android.intent.action.PACKAGE_REPLACED" />
            <action android:name="android.intent.action.PACKAGE_RESTARTED" />

        </intent-filter>
    </receiver> -->

    <!-- <receiver android:name="com.whizpool.nogademo.MyBroadcastReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver> -->
 </application>

</manifest>

A: Register a broadcast receiver in your manifest by using broadcast android.intent.action.BOOT_COMPLETED.Then in onReceive() method, you can dome necessary logic work.This will require permission android.permission.RECEIVE_BOOT_COMPLETED.

A: Added a reciver which handles the power events and start your activity in this
public class PowerEventReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
                Intent i = new Intent(context, HeliosActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);
            }

        }
    }

and add this to your manifest
  <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

       <receiver android:name="com.RareMediaCompany.Helios.PowerEventReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.ACTION_SHUTDOWN" />
            </intent-filter>
        </receiver>


text:
Q: How to convert bytes to string in Python 3 to concatenate(serialized_data,signature) I am working with a prototype for securing deserialization adding a signature to the serialized data, but when I try to concatenate the signature with the serialized data it throws an error.
with open(filename, 'w') as file_object:
        #Adding the signature to the data
        file_object.write(signature + serialized)

TypeError: can only concatenate str (not "bytes") to str

And if I try to convert the serialized data into a string it also throws an error
with open(filename, 'w') as file_object:
        #Adding the signature to the data
        serializedStr = serialized.decode('utf-8')
        file_object.write(signature + serializedStr)

serializedStr = serialized.decode('utf-8') UnicodeDecodeError: 'utf-8'
  codec can't decode byte 0x80 in position 0: invalid start byte

How can I add the signature to the serialized data?
Full Code
import pickle
import json
import hashlib
import hmac

class User(object):
    def __init__(self, name):
        self.name = name

filename = 'user.file'
KEY = b'secret'

user = User('david')
serialized = pickle.dumps(user)
#calculate the signature
signature = hmac.new(KEY, serialized, hashlib.sha256).hexdigest()

with open(filename, 'w') as file_object:
    #Adding the signature to the data
    print(type(serialized))
    print(type(signature))
    #serializedStr = serialized.decode('utf-8')
    file_object.write(signature + serialized)

with open(filename, 'rb') as file_object:
    raw_data = file_object.read()
    if(len(raw_data) == len(signature)):
        read_signature = raw_data[:len(signature)]
        read_data = raw_data[len(signature):]
        computed_signature = hmac.new(KEY, read_data, hashlib.sha256).hexdigest()
        if hmac.compare_digest(computed_signature, read_signature):
            userDeserialized = pickle.loads(read_data)
            print (userDeserialized.name)

A: Use .digest() not .hexdigest() to get a byte string that can be prepended to the serialized data byte string.  Open the file for binary read/write:
import pickle
import json
import hashlib
import hmac

class User(object):
    def __init__(self, name):
        self.name = name

filename = 'user.file'
KEY = b'secret'

user = User('david')
serialized = pickle.dumps(user)
#calculate the signature
signature = hmac.new(KEY, serialized, hashlib.sha256).digest() # not .hexdigest()

with open(filename, 'wb') as file_object:                 # binary write
    file_object.write(signature + serialized)

with open(filename, 'rb') as file_object:                 # binary read
    raw_data = file_object.read()
    if len(raw_data) >= len(signature):                   # need >= here
        read_signature = raw_data[:len(signature)]
        read_data = raw_data[len(signature):]
        computed_signature = hmac.new(KEY, read_data, hashlib.sha256).digest() # not .hexdigest()
        if hmac.compare_digest(computed_signature, read_signature):
            userDeserialized = pickle.loads(read_data)
            print (userDeserialized.name)

Output:
david

A: try this
with open(filename, 'wb') as file_object:
    #Adding the signature to the data
    print(type(serialized))
    print(type(signature))
    #serializedStr = serialized.decode('utf-8')
    s = bytearray(signature)
    s.extend(bytes(serialized, 'utf-8'))
    file_object.write(s)


text:
Q: TypeError: Cannot read property 'random' of undefined - crypto-js I'm using crypto-js inside reactjs and everything works fine on localhost.
but on server with chrome I got this error message:
TypeError: Cannot read property 'random' of undefined

on firefox:
TypeError: "r is undefined"

my code:
import CryptoJS from 'crypto-js';

console.log('text',text); //printed on console as well
var p = randomString(10)
console.log('p',p) //printed on console as well
var c = CryptoJS.AES.encrypt(text,p).toString(); // error line
console.log('crypted',c+p)//not printed !

my function:
  function setWindow(text){
    console.log('text',text);
    var p = randomString(10)
    console.log('p',p)
    var c = CryptoJS.AES.encrypt(text,p).toString();
    console.log('crypted',c+p)
    return c+p;
  }

"crypto-js": "^3.1.9-1",

I don't know where is my problem! I removed node_modules, but I got the same error.
my site:
http://posweb.ccg24.com/signin
updated
  function randomString(length) {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < length; i++)
      text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
  }

A: You can generate random without using Math.random
var _ = require('lodash');
var CryptoJS = require("crypto-js");
var p;
function randomString(length) {
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

 var text= _.sampleSize(possible , length).join('');

  return text;
}

function setWindow(text){
    console.log('text',text);
     p = randomString(10)
    console.log('p',p)
    var c = CryptoJS.AES.encrypt(text,p).toString();
    console.log('crypted',c+p)
    return c+p;
  }

var ciphertext=setWindow("plain text");
var bytes  = CryptoJS.AES.decrypt(ciphertext.toString(), p);
var plaintext = bytes.toString(CryptoJS.enc.Utf8);

console.log("decrypte",plaintext);

function randomString(length) {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < length; i++)
      text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
  }

function setWindow(text){

    console.log('text',text);
    var p = randomString(10)
    console.log('p',p)
    var c =CryptoJS.AES.encrypt(text,p);
    console.log('crypted',c+p)
    return c+p;
}
var text="Plain Text";
setWindow(text);
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>

The code here:https://repl.it/@ibrahimth/LastSatisfiedBrain

A: You can try import * as CryptoJS from 'crypto-js';


text:
Q: android - How can I call a method in the MainActivity from another activity in C#? I want to call a method in the MainActivity class, from another activity.
I know it's done like this in Java:
((MainActivity)getActivity()).doSomething();

But I wanna know how it's done like in C#.
Thanks in advance.

A: You should not create an instance of the activity class. It is wrong. Activity has ui and lifecycle and activity is started by startActivity(intent)
you can use this in Fragment to get activity context and run some function
In Java
((MainActivity)getActivity()).doSomething();

In C#
((MainActivity)this.Activity).doSomething();


text:
Q: Suppose that $f$ is analytic in $\{z \in \mathbb{C}: 0 < |z| < 1\}$ with essential singularity at $0$. Suppose that $f$ is analytic in $D^{*} = \{z \in  \mathbb{C}: 0 < |z| < 1\}$ with essential singularity at 0.
Show that for each $w \in \mathbb{C}$, exists a sequence $\{z_n\} \in D^{*}$
such that $\displaystyle\lim_{n\to\infty}f(z_n) = w$.
I know that we can cover almost the whole complex plane as we approach to the essential singularity and Casoratti Weierstrass says that the closure of the image of f under the annulus is $\mathbb{C}$. The problem is how we construct that sequence!
I was trying to prove by contradiction, that is: for any sequence in $D^{*}$ exists an $\epsilon > 0$ such that $|f(z_n) - w| \geq \epsilon$. I did not find anything usefull.

A: Unless I misunderstand something, your proposition is false.
Consider $f(z) = e^{1/z}$, it has an essential singularity at $z=0$, but there is no $z_0$ such that $f(z_0)=0$.

Perhaps you are asked to prove

Show that for each $w\in\mathbb{C}$, exists a sequence $\{z_n\}\in D^\ast$ such that $f(z_n)\to w$.

In this case, this is a simple corollary of Weierstrass-Casorati.

Perhaps, alternatively, you are asked to prove

Show that for each $w\in\mathbb{C}$, with a single exceptional $w$, there exists a sequence $\{z_n\}\in D^\ast$ such that $f(z_n)= w$.

In this case, this is equivalent to great Picard theorem.


text:
Q: UITableView tableHeaderView autolayout programmatically I want to add layout constraint to tableHeaderView
UIView *headerView = [[UIView alloc] init];
headerView.translatesAutoresizingMaskIntoConstraints = NO; // THIS WILL CRASH
headerView.backgroundColor = [UIColor clearColor];
_tableView.tableHeaderView = headerView;

UIView *headerWrapperView = [[UIView alloc] init];
headerWrapperView.translatesAutoresizingMaskIntoConstraints = NO;
headerWrapperView.backgroundColor = [UIColor whiteColor];
[headerView addSubview:headerWrapperView];

NSArray *constraints = [NSLayoutConstraint
               constraintsWithVisualFormat:@"V:|-10-[headerWrapperView]-10-|"
               options:0
               metrics:nil
               views:viewsDictionary];
[headerView addConstraints:constraints];
constraints = [NSLayoutConstraint
               constraintsWithVisualFormat:@"|-10-[headerWrapperView]-10-|"
               options:0
               metrics:nil
               views:viewsDictionary];
[headerView addConstraints:constraints];

If I remove headerView.translatesAutoresizingMaskIntoConstraints = NO; this line,
then I get
Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSLayoutConstraint:0x797f54f0 H:|-(20)-[UITextField:0x797ed440]   (Names: '|':UIView:0x797ea9e0 )>",
"<NSLayoutConstraint:0x797f5540 H:[UITextField:0x797ed440]-(20)-|   (Names: '|':UIView:0x797ea9e0 )>",
"<NSLayoutConstraint:0x797f5270 H:|-(10)-[UIView:0x797ea9e0]   (Names: '|':UIView:0x797ea800 )>",
"<NSLayoutConstraint:0x797f52e0 H:[UIView:0x797ea9e0]-(10)-|   (Names: '|':UIView:0x797ea800 )>",
"<NSAutoresizingMaskLayoutConstraint:0x79729910 h=--& v=--& H:[UIView:0x797ea800(0)]>"
)

Has anyone resolve this issue? Can provide example?
P/S: There are other views inside headerWrapperView
Update
I try using non-autolayout for headerView and all it's subview, tableView remain autolayout
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 400)];
headerView.backgroundColor = [UIColor clearColor];
_tableView.tableHeaderView = headerView;

NSLog(@"headerView %@", headerView);

Then I get this result
headerView <UIView: 0x79c38430; frame = (0 0; 0 400); layer = <CALayer: 0x79c38490>>
If without this line (line below)
_tableView.tableHeaderView = headerView;

then I get
headerView <UIView: 0x79c38430; frame = (0 0; 320 400); layer = <CALayer: 0x79c38490>>

A: from this error report
NSAutoresizingMaskLayoutConstraint:0x79729910 h=--& v=--& H:[UIView:0x797ea800(0)]
I think if you remove that line, the width of that view is 0
try to init that view with a frame CGRectMake(0, 0, self.view.frame.size.width, 300)

A: [self.view addSubview:self.tableView];
 self.tableView.translatesAutoresizingMaskIntoConstraints = false;

[self.view addConstraints:@[
             [NSLayoutConstraint constraintWithItem:self.tableView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1 constant:0],
         [NSLayoutConstraint constraintWithItem:self.tableView attribute:NSLayoutAttributeTrailing    relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTrailing multiplier:1 constant:0],

         [NSLayoutConstraint constraintWithItem:self.tableView attribute:NSLayoutAttributeTop    relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:0],

         [NSLayoutConstraint constraintWithItem:self.tableView attribute:NSLayoutAttributeBottom    relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:0],
     ]];

///it's important
     dispatch_async(dispatch_get_main_queue(), ^{
         self.tableView.tableHeaderView = self.topV;
     });

}


text:
Q: How to assert that download popup is active? selenium webdriver I need to verify that download link is correct and when you click it that document is created for downloading.
so how can I assert that when test clicks link, after some time there is a download popup (sometimes there is no popup and I need test to fail then)


text:
Q: How to trigger only web.config transformations via batch command in Jenkins I am setting up a Jenkins server to build .NET projects.  We our using the visual studio Web.config transformations to transform our config files for each environment (Dev1, Dev2, QA, and Release).  I am using the following command line arguments in my MSBuild command, and it is working with the transformations:
/p:Configuration=Dev1;DeployOnBuild=true;DeployTarget=Package;_PackageTempDir=..\..\deploy\current\Dev1

The problem is that I have to rebuild the solution for each environment, and some of the solutions are quite large and take a some time to build.  I would like to only build the solution once, and then trigger just the transformations for the other environments.  Does anyone know of a way to do this through an MSBuild batch command, or another way to get this done in Jenkins?

A: I ended up using this Config Transform Tool on CodePlex.  It did the trick easily by allowing us to run web.config transforms from a command line script that is easily executed by a Jenkins build step.

A: As you mentioned, Jenkins just run the command. Take a look at the Task 5 of this Exercise from Microsoft. There's another approach here.


text:
Q: Can non-conservative fields store potential energy? I was taught that a time-varying magnetic field generates an electric field which is non-conservative in nature, and my teacher also told me that when a conducting coil is placed in a region with a time-varying magnetic field, with appropriate orientation, some EMF is induced in the coil and this EMF is due to the presence of that induced electric field.
Now, this is what is given in my physics NCERT book (I have highlighted the text):

The statement "work against the back emf" is the same as "work against the induced electric field", right? If that's true , then how can that energy get stored?
Negative work done by conservative fields is stored in the fields as potential energy. I don't think the same is true for non-conservative fields, otherwise, there is no difference.
So how can the induced electric field store energy ?

A:
The statement "Work against the back emf" is the same as "work against the induced electric field" (Right ?). And if that's true , then how can that energy get stored ?

Yes. This work against the forces of induced electric field is stored as magnetic part of EM energy in the region. As induced electric field is present and is doing negative work (other forces such as electrostatic forces due to battery act against the induced forces and can do the positive work), greater magnetic field is created and this is associated with greater magnetic energy. It does not matter whether the EM field is conservative or not, if it is not vanishing everywhere, energy can be stored as EM energy.

A: A conservative field $\vec F$ is one which satisfies $$\oint_{\Gamma}\vec F\cdot \vec{dl}=0$$ for any path $\Gamma$. This just means that work done from moving a particle interacting with that field is independent of the path taken i.e
$$\int_{\Gamma_1}\vec F\cdot \vec{dl}=\int_{\Gamma_2}\vec F\cdot \vec{dl}$$ if $\Gamma_1$ and $\Gamma_2$ have the same endpoints and orientation. Due to this path independence one can write down the work done as a function of just the two endpoints without any mention of the path taken. This function is the potential energy and can be interpreted as the energy stored in the field. This does not mean that only if one can define a potential energy function then energy can be stored in the field. A non-conservative field can store energy too.

A: No. By the nature of nonconserative fields, potential energy is not stored.

A: From the equation $\frac{dW}{dt}=|\varepsilon|I=(L\frac{dI}{dt})I\;\;\;\;\; $(1)
that can be rewritten $\;\;dW=LIdI$
a simple integration of the equation gives $W=\frac{1}{2}LI^{2} $
In a solenoid, the following results are valid :
$B=\frac{\mu NI}{l}\;$, magnetic field, where $  \mu $ is the relative permeability, $N$ the number of turns of the coil, and $I$ the system current.
$L=\frac{\mu N^{2}A}{L}\;$,where  $l$ is the length of the solenoid and $ A$ its cross section.
We can replace the stored energy terms in the following expression, where the volume of the system is given by $ Al$ :
$u=\frac{energy}{volume}=\frac{\frac{1}{2}LI^{2}}{Al}$
hence, the magnetic energy density (energy per unit volume) in a region of permeability space $\mu _{0}$, containing a magnetic field $\vec {B}$ is written :
$u=\frac{1}{2}\frac{B^{2}}{\mu_{0}}\;\;\;(2)$
(1)  https://fr.wikipedia.org/wiki/Inductance
(2)  https://en.wikipedia.org/wiki/Magnetic_energy


text:
Q: Adding parameters to a GUI constructor stops GUI pop up I've started learning Java with Eclipse, and I altered the main function to pass two strings to the similarly altered GUI constructor (there was nothing passed before).
The GUI doesn't pop up on the screen now, but can be accessed from the task bar at the bottom of the screen. I was just wondering why this happened? I've pasted the shortened code below.
I've tried it multiple times, and tried to find the problem with keywords on the web.
public class MainButton
{
    public static void main(String[] args)
    {
        String A = "title"; String B = "Button";
        Agui a = new Agui(A,B);

               //BEFORE Agui a = new Agui();
    }
}

import javax.swing.*;

public class Agui extends JFrame
{
    //BEFORE public Agui()
    public Agui(String A, String B)
    {
        setTitle(A);
        setSize(400, 400);

        // Create JButton and JPanel
        JButton button = new JButton(B);
        JPanel panel = new JPanel();

        // Add button to JPanel
        panel.add(button);
        // And JPanel needs to be added to the JFrame itself!
        this.getContentPane().add(panel);

        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
      }
}

It'd be great to get the pop up without going to the task bar at the bottom of the screen, and to understand the logic of why this problem occurs.


text:
Q: Formatting a non english string I have written a function which needs to format a string that contains Hebrew letters, the script runs perfectly when using english letters. But when using Hebrew ones, it gives me the following error:
The error is:
Error:  'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

function code is (the code under define line is indented and not as seen in the code block):
def postWP(gameTitle,gameCode):
    print "PostWP activated, Title: %s" % gameTitle
    mail = smtplib.SMTP('smtp.gmail.com',587)
    mail.ehlo()
    mail.starttls()
    mail.login('email@gmail.com','emailPassword')
    message = 'Subject: {}\n\n{}'.format(gameTitle, gameCode)
    print "Sending mail..."
    mail.sendmail('email@gmail.com','destination@mail.com',message)
    mail.close()

Basically, the problem occurs at 'Subject: {}\n\n{}'.format(gameTitle, gameCode)'.
I was wondering how can I get it fixed. Thanks in advance to everyone who is trying to help!
Best Regards, have a great day!

A: def postWP(gameTitle,gameCode):
    # additional parameter checking
    if not isinstance(gameTitle, basestring):
        print "gameTitle type error"
        return
    if not isinstance(gameCode, basestring):
        print "gameCode type error"
        return
    if isinstance(gameTitle, unicode):
        gameTitle = gameTitle.encode('utf8')
    if isinstance(gameCode, unicode):
        gameCode = gameCode.encode('utf8')

    # the following remains the same
    print "PostWP activated, Title: %s" % gameTitle
    mail = smtplib.SMTP('smtp.gmail.com',587)
    mail.ehlo()
    mail.starttls()
    mail.login('email@gmail.com','emailPassword')
    message = 'Subject: {}\n\n{}'.format(gameTitle, gameCode)
    print "Sending mail..."
    mail.sendmail('email@gmail.com','destination@mail.com',message)
    mail.close()


text:
Q: AWS Lambda Cron Schedule Error I have several Lambda Functions that are on a schedule and those are working without any issues. However, I have a onetime job that I am trying to set up for an existing function and am getting an error when I am creating the new rule:
Details: Parameter ScheduleExpression is not valid..
I need this to run on Monday September 26th 2016 at 14:30 hours UTC.
Here are all of the variations I have tried:

*

*cron(30 14 26 SEP ? 2016)

*cron(30 14 26 9 ? 2016)

*cron(30 14 26 SEP ?*)

*cron(30 14 26 9 ? *)

*cron(30 14 26 SEP MON 2016)

*cron(30 14 26 9 MON 2016)

I must have been staring at this too long because I can't figure out what is the deal on this one. I am using the reference provided here:
http://docs.aws.amazon.com/lambda/latest/dg/tutorial-scheduled-events-schedule-expressions.html
Thanks all!

A: Are you using web console or CLI? In web console you should not fill the cron() part. Your first expression is correct.
See the screenshot:


text:
Q: how can i get my added usercontrol properties from flowLayoutPanel I am using flowLayoutPanel and adding my custom user controls to it, I can add mu usercontrol to it but i don't know how can it use it after adding.
in this part i add my user controls:
...
ExtensionUserControl extension = new ExtensionUserControl(this, AMI_ClientInstance);
//Add Obj Name (Extension Number)
extension.ExtensionNumber = Obj.ObjName;
flowLayoutPanel1.Controls.Add(extension as ExtensionUserControl);
...

and another place i want to have the properties of my added user control, i try to user this code but it get error, It says that can not convert windows control to ExtensionUserControl
ExtensionUserControl extension = flowLayoutPanel1.Controls[1];

please totally tell me how can i have my user control properties after adding it to panel?
thanks

A: Are you sure Controls[1] is ExtensionUserControl?
I think that:
foreach(Control ctl in flowLayoutPanel1.Controls)
{
     if(ctl is ExtensionUserControl)
       {
            (ExtensionUserControl)ctl......//do something u want
       }
}

I'm not test it yet, just thinking, sorry if it doesn't work


text:
Q: Rake FileList exclude method works in irb but not my rakefile Goal : Collect all files, complete with directory structure, matching a directory structure.
Wrinkle: Need to filter out a pesky undesired directory that matches but is thankfully uniquely named 'do-not-want'. Actual string changed to protect the innocent.

*

*source/dir1/content/scripts - ok

*source/dir2/subdir1/content/scripts - ok

*source/dir3/do-not-want/content/scripts - well... do not want
The script below works but I have to do a separate check for the undesired path which should not be necessary. When I test this same FileList in irb with the exclude it works as desired. From my rakefile I see the do-not-want directories being returned by the FileList.
FileList['source/**/content/scripts'].exclude('do-not-want').each do |f|
    unless /do-not-want/ =~ f #hmm why does the exclude above not actually exclude do-not-want directories?
        Dir.chdir(f) do |d|
            puts "directory changed to #{d} and copying scripts from #{d} to common directory #{target}"
            FileUtils.cp_r('.', target)
        end
    end
end

Surely I am doing something dumb.
Bonus points: if you help me learn rake/ruby and show me a better way to accomplish same goal while defeating the wrinkle.

A: I think you should use FileList['source/**/content/scripts'].exclude(/\/do-no-want\//) to filter out paths which contain "/do-no-want/" substring.
Try adding output to your rake file, so you can see and debug what's going on there.


text:
Q: Understand Elasticsearch Multivalue Fields I am trying to understand the position_increment_gap as it is explained on the Elasticsearch documentation https://www.elastic.co/guide/en/elasticsearch/guide/current/_multivalue_fields_2.html
I created the same index as in the example and inserted a single document
PUT /my_index/groups/1
{
    "names": [ "John Abraham", "Lincoln Smith", "Justin Trudeau"]
}

Then I try a phrase query for Abraham Lincoln and it matches, as expected
GET /my_index/groups/_search
{
    "query": {
        "match_phrase": {
            "names": "Abraham Lincoln"
        }
    }
}

{
  "took": 25,
  "timed_out": false,
  "_shards": {
  "total": 5,
  "successful": 5,
  "skipped": 0,
  "failed": 0
},
"hits": {
  "total": 1,
  "max_score": 0.5753642,
  "hits": [
  {
    "_index": "names",
    "_type": "doc",
    "_id": "1",
    "_score": 0.5753642,
    "_source": {
      "names": [
        "john abraham",
        "lincoln smith",
        "justin trudeau"
      ]
    }
  }
  ]
}
}

The documentation explains that the match occurs because ES produces the tokens john abraham lincoln smith justin trudeau and it recommends inserting a position_increment_gap of 100 to avoid matching abraham lincoln unless I have a slop of 100.
I changed the index to have a position_increment_gap of 1 as shown below:
PUT names
{
  "mappings": {
    "doc": {
      "properties": {
        "names": {
          "type":"text",
          "position_increment_gap": 1
        }
      }
    }
  }
}

If I'm understanding the documentation, using a gap of 1 should allow me to match "abraham smith".  But it doesn't match.  Nor does "abraham lincoln", "abraham justin", or "abraham trudeau".  "lincoln smith", "john abraham" and "justin trudeau" all continue to match.
I must be misunderstanding the documentation.
Thanks for any suggestions.