text:
Q: Convert from Price Im attempting to Convert a Price (from an API (code below)).
public class Price
{
    public Price();
    public Price(double data);
    public Price(double data, int decimalPadding);
}

What I would like to do is compare the price from this API to a Double. Simply trying to convert to Double isnt working as I would have hoped.
Double bar = 21.75;
Price price = new Price();

if (Convert.ToDouble(price) >= bar) {
//code
}

when I try something like this, I believe it says the value must be lower than infinity.
How can I convert this price so they can be compared?

A: You would need a property in your price object that returns the double and compare that.

A: Convert.ToDouble cannot magically convert a Price object to a double, unless Price implements IConvertible.

A: You could use an implicit operator to convert to double. This is as per the MSDN for "implicit" operator in C#.
E.g.
class Price
{
    public static implicit operator double (Price d)
    {
        return d.data;
    }
    public static implicit operator Price (double d)
    {
        return new Price(d);
    }
}

Alternatively, for your comparisons, implement IComparable<double> and IEquatable<double> on your Price class then use the CompareTo instead and/or another operator overload.


text:
Q: White Text in Select Box Options - HTML Dialog in Google App Script I am building some customer HTML dialog for Google Sheets.  The page in question will be a form for creating a work order.  I am using Bootstrap 4 for the styling and I have some added JS inside the document for showing and hiding some elements.  I am not finished with the code yet, I ran the script in Google Sheets and discovered two problems.
I have several select boxes within the form, they are populated with a blank (as the initial selected option), an option for "New" and when I am finished a script will dynamically populate the rest of the options(the option "Existing" is temporary). When I load the page from Google Sheets the select boxes are white text with white back ground.  When something is selected it will show up in the input box as black text but the user can't see the options.
The other problem is the date input.  I am using the browser input calendar popup.  Once the html is loaded the calendar is cut off and you can only see a few days to choose from.  Everyone using this will be on Desktop Chrome, so no worries with mobile or cross browser compatibility.
For the problem with the select box I have tried to add a color style tag to the options in the select box but that didn't help, and for the calendar I have no idea what the solution could be.
The code that loads the page
function createWO() {
  var html = HtmlService.createTemplateFromFile("createWO").evaluate().setTitle("Create Work Order").setWidth(1500).setHeight(1000);
   SpreadsheetApp.getUi()
      .showModalDialog(html, 'Create New WorkOrder');
}

The Snippets from the HTML
Metatags in head

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

Style Sheet Reference in head
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Select box causing problem

                                Customer Name
                                <select class="form-control" id="custID" onchange="customer(this.value);">
                                    <option selected></option>
                                    <option value="1">New</option>
                                    <option>Existing Customer</option>

                                </select>

Java Script for onChange event in select box

Bootstrap required script references

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spark Streaming progress partitions independently We have a scenario where we have partitioned our input Kafka topics by Account Number. Each partition directly writes to DB and have no dependency on the each other.
Currently, even if one partition completes the processing in 5 seconds, it has to wait for the slowest partition to complete to start processing the next batch. Let's say slowest partition takes 30 seconds then the partition that completed within 5 seconds has to remain idle for 25 seconds.
Is there a way to set up micro batch where in we process each partition sequentially and independent of other partitions? In my earlier e.g the partition that completed the batch in 5 seconds should pick up the next batch right away without being idle for 25 seconds.


text:
Q: Setting command of WiFi enabled in not working I created a timer which will check whether wifi is enabled or not (WiFiManager.isWifiEnabled()) and if it is not enabled then calling WiFiManager.setEnabled() method to enable device's WiFi, it starts timer in onCreate() method of Application's background service, timer will run every 1 seconds to verify wifi enabled or not.
When device is in active state,app runs properly but when device goes to sleep mode/locked state, wifi is getting disconnected even though I introduce timer to set wifi enabled in every 1 second. So not able to find out the way to keep wifi turned on even device goes to sleep/locked mode.

A: your problem is, that android will enter the sleep mode when the device is locked. this will put all services into the background.
i´m not sure if it is possible to lock the wifi connection.
Mark Murphy created the wakeful service demo to show how to wake up services while the device is sleeping. maybe this could solve your problem but i´m not sure.


text:
Q: Problems In JavaScript Arrow Function I'm a newbie
I've download some source in this link
https://github.com/the-road-to-learn-react/react-redux-example
i have some proplem
in file src/app.js line 4
const applyFilter = searchTerm => article =>
  article.title.toLowerCase().includes(searchTerm.toLowerCase());

why this can't work with
const applyFilter = searchTerm => article =>{
  article.title.toLowerCase().includes(searchTerm.toLowerCase());
}

or
const applyFilter = searchTerm => {article =>
  article.title.toLowerCase().includes(searchTerm.toLowerCase());
}

and in line 14 when call the funtion
articles.filter(applyFilter(searchTerm))

const applyFilter = searchTerm => article =>
  article.title.toLowerCase().includes(searchTerm.toLowerCase());

this in my mind is call an arrow function inside an arrow function?
How can they put var 'article' in??

A: Arrow function syntax is kinda like this
(a) => b(a);

is equivalent to

function(a) {
    return b(a);
}

However, when you add {} to an arrow function, it changes the meaning:
(a) => { b(a); }

is equivalent to

function(a) {
    b(a);
    // notice that this doesn't actually return anything,
    // it just calls a function and does nothing with the result
}

So you have to add a return statement when you add brackets
(a) => { return b(a); }


text:
Q: Metaquestion: how to find out why (e.g.) MatchQ[42, _?Function[x, True]] is False? Suppose you run into a bewildering Mathematica result (which happens to me several times per Mathematica session, even after a 20-year acquaintance), such as, for example:
MatchQ[42, _?Function[x, True]]
False

So you go pore over the docs, but you still can't figure out an explanation.  Then what?

What tool can one use to figure out why Mathematica's evaluation is different from what one expects?

PS. By sheer luck, I had read something a few days earlier that helped me figure out the answer to the one above, but I would have never guessed it without that prior hint.  Yes, after knowing the answer I can zero in the place in the docs where the mystery is solved, but only then.  This is why the documentation does not go as far in such situations as one would think: if one knew where in the documentation to look, one wouldn't have been puzzled by the original result in the first place.  Here's a different hint: when completely nonplussed, what could be more fitting than to interrogate the documentation for ?

A: Perhaps something along the lines of this helps visualize the FullForm, and would have made you realise that _?Function was being interpreted as a head of (_?Function)[x, True]
SetAttributes[f, HoldFirst];
f[h_[args___]] := OpenerView[{HoldForm@Panel@h, Column[f /@ Unevaluated /@ {args}]}];
f[sth_] := HoldForm@sth;

f@MatchQ[42, _?Function[x, True]]

In any case, Ctrl+. or mouse clicking seems to me the most useful tool to check precedence.
When you really want to know what's going on and have narrowed down your problem to a small line of code, a trace has all you need. In this case,
Trace[MatchQ[42, _?Function[x, True]], TraceOriginal -> True]

would show the problem in its output

A: My first instinct in such cases is usually to use Trace to figure out which part of the evaluation is behaving differently from what I expect. For the example you already have this point isolated. Then I typically try to dissect it and determine why it misbehaves. An important part of this dissection is using FullForm to remove all the shorthands that are sometimes interpreted differently then you expect due to precedence rules. Which is also the case here for this problem.
 MatchQ[42, _?Function[x, True]] // Trace

 {MatchQ[42,_?Function[x,True]],False}

This just shows us that we have already pinpointed the point of interest.
 MatchQ[42, _?Function[x, True]] // HoldComplete // FullForm

HoldComplete[MatchQ[42,PatternTest[Blank[],Function][x,True]]]

Here we can easily see that the problem is that the PatternTest (_?Function[x, True]) is bound differently then we expect, actually being interpreted as ((_?Function)[x, True])
Thus the solution is to insert proper grouping.
 MatchQ[42, _?(Function[x, True])]

True

Update
While writing this answer, I realised that my little mental exercise of putting in "invisible" parenthesis could be automated, and wrote a quick function for doing just that.
 SetAttributes[parenthesis, HoldAll]
 MakeBoxes[parenthesis[exp_], StandardForm] ^:= RowBox[{"(", MakeBoxes@exp, ")"}]

SetAttributes[Parenthesise, HoldAll]
 Parenthesise[expression_] :=
 HoldComplete[expression] //.
  f_[pre___, arg_, post___] /; ! (f === parenthesis) && ! (Head@arg === parenthesis) :>
     f[pre, parenthesis[arg], post] // Defer @@ # &

Which allows one to call:
 Parenthesise[MatchQ[42, _?Function[x, True]]]
 Parenthesise[MatchQ[42, _?(Function[x, True])]]

     (MatchQ[(42), ((_)?(Function)[(x), (True)])])
     (MatchQ[(42), ((_)?(Function[(x), (True)]))])

A better such function could most definitely be created, but I thought it was worth sharing.

A: I gave my answer to this question here: https://mathematica.stackexchange.com/a/3146/121
Let me show how those recommendations apply to this specific problem.
1. Expanding the selection with Ctrl+.
Using Ctrl+. on a few parts would quickly show something like this:

This would alert you that something strange is going on.
2. Displaying the expression with FullForm and TreeForm
Looking at the held FullForm:
MatchQ[42, _?Function[x, True]] // FullForm // HoldForm

MatchQ[42, PatternTest[Blank[], Function][x, True]]

We can see the precise way in which Mathematica is interpreting this expression.
We could also use TreeForm.  (Unevaluated is needed to handle an evaluation leak in TreeForm):
MatchQ[42, _?Function[x, True]] // Unevaluated // Unevaluated // TreeForm


text:
Q: singleTask activity not loading properly I have an activity 'A' defined in Manifest like below:
<activity
    android:name=".A"
    android:launchMode="singleTask"
    android:screenOrientation="portrait">

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

</activity>

When I launch my APP,  that activity is always loaded from the start. It wont start from my prev activity.
When I remove android:launchMode, then it works as I expect.

A: Since you set android:launchMode="singleTask", the activity A will always be the root of your activities.
From DOCS:

In contrast, "singleTask" and "singleInstance" activities can only begin a task. They are always at the root of the activity stack. Moreover, the device can hold only one instance of the activity at a time — only one such task.

Default mode is standard. So, when you remove android:launchMode="singleTask", your APP returns to standard launch mode.
That's why if you app is always starting Activity A.

A: If you would like to start a different Activity on launch replace that in the xml name attribute that contains LAUNCHER
<activity
    android:name=".ActivityB"
    android:launchMode="singleTask"
    android:screenOrientation="portrait"
  >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

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

</activity>

Where Activity B is an alternate activity.


text:
Q: Compiler skips try bracket? So I have this little App that should only show a JSON-Object(not even parse it) in the Textview "tvJsonItem" after you push the button "btnHit". I have built in multiple Toasts to follow its procedure, but if i push the button, i only get the Toast Test1 from the onPostExecute. It seems like the Programme skips the whole try bracket.
    public class MainActivity extends AppCompatActivity {

private TextView tvData;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btnHit = (Button) findViewById(R.id.btnHit);
    tvData = (TextView) findViewById(R.id.tvJsonItem);
}

public void onClick(View view) {
    new JSONTask().execute();
    Toast.makeText(getApplicationContext(), "onClick", Toast.LENGTH_LONG);
}

public class JSONTask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String...params) {

        HttpURLConnection connection = null;
        BufferedReader reader = null;
        URL url = null;
        try {
            url = new URL("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt");
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));
            Toast.makeText(MainActivity.this, "test2", Toast.LENGTH_LONG).show();
            StringBuffer buffer = new StringBuffer();

            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            String result = buffer.toString();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "Malformed", Toast.LENGTH_LONG);
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "IOException", Toast.LENGTH_LONG);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    }

    protected void onPostExecute(String result){
    super.onPostExecute(result);
        tvData.setText(result);
        Toast.makeText(getApplicationContext(), "test1", Toast.LENGTH_LONG).show();
    }
}
}

A: You can't call toast.show() in doInBackground, because toast.show() should call in Main UI Thread.
for the test, convert toast.show() to log.d()...


text:
Q: In python what is the procedure to import a module which takes sys.argv arguments to run? I try to import a module a.py in module b.py.
The module a.py takes sys.argv command line arguments to run.
So now when I import it in b.py and execute b.py where would I provide the sys.argv arguments required by the a.py module?
For example:
a.py
import sys
x = sys.argv[1]
print x

b.py
from a import *
print x

So now where would I provide the value of x?

A: I believe that you have to pass an argument to b.py and then pass it to a.py.

A: argv is filled by command line parameter python module sys.
calling this:  python b.py hello will print hello


text:
Q: When TestClass Name & Namespace length reaches 128 characters, the test class shows as 'Excluded' in Test Explorer when PostSharp is referenced I recently created a VS2015 solution to migrate projects & test projects from VS2010. I am experiencing odd behaviour with one particular test class which has a reference to PostSharp, where the combined namespace and test class name reaches 128 characters (which isn't many in my opinion). The tests show as 'excluded' in the test explorer window (When the tests are grouped by project). Also when I right click within the test class, the output window shows 'No tests found to run'.
When I try to select the test methods within the 'external' node, the following test is displayed: 'Source: no source available'.
I have tried creating another test project in a different solution, and purposely exceeded the 128 characters without postsharp and the problem goes away.
The obvious fix for this is to shorten the length of the namespace, however I am curious as to whether anyone has ever found a reason / solution for this?


text:
Q: Detect USB Drive in Java How can I detect when a USB drive is attached to a computer in Windows, Linux, or Mac?
The only way I have seen online to do this is to iterate the drives, but I don't think there is a very good way to do that cross-platform (e.g. File.listRoots() in Linux only returns "/"). Even in Windows this would cause problems reading from every device, such as a network drive that takes a long time to access.
There is a library called jUsb that sounds like it accomplishes this in Linux, but it doesn't work in Windows. There is also an extension to this called jUsb for Windows, but that requires users to install a dll file and run a .reg. Neither of these seem to be developed for several years, so I'm hoping a better solution exists now. They're also overkill for what I need, when I only want to detect if a device is connected that contains a file I need.
[Edit] Furthermore, jUsb apparently doesn't work with any recent version of Java, so this isn't even an option...
Thanks

A: Last time I checked there were no open source USB library for java and in windows. The simple hack that I used was to write a small JNI app for capturing WM_DEVICECHANGE event. Following links may help

*

*http://www.codeproject.com/KB/system/DriveDetector.aspx

*http://msdn.microsoft.com/en-us/library/aa363480(v=VS.85).aspx
In case you don't want to mess with the JNI then use any windows native library for USB with JNA ( https://github.com/twall/jna/ )
altough i would suggest using WM_DEVICECHANGE approach... because your requirement is just a notification message....

A: I've made a small library to detect USB storage devices on Java. It works on Windows, OSX and Linux. Take a look at: https://github.com/samuelcampos/usbdrivedetector

A: public class AutoDetect {

static File[] oldListRoot = File.listRoots();
public static void main(String[] args) {
    AutoDetect.waitForNotifying();

}

public static void waitForNotifying() {
    Thread t = new Thread(new Runnable() {
        public void run() {
            while (true) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (File.listRoots().length > oldListRoot.length) {
                    System.out.println("new drive detected");
                    oldListRoot = File.listRoots();
                    System.out.println("drive"+oldListRoot[oldListRoot.length-1]+" detected");

                } else if (File.listRoots().length < oldListRoot.length) {
    System.out.println(oldListRoot[oldListRoot.length-1]+" drive removed");

                    oldListRoot = File.listRoots();

                }

            }
        }
    });
    t.start();
}
}

A: I created the code that works on Linux and windows check this
 import java.io.BufferedReader;
 import java.io.File;
 import java.io.IOException;
 import java.io.InputStreamReader;

 public class Main{
 public static void main(String[] args) throws IOException{//main class
     Main m = new Main();//main method
     String os = System.getProperty("os.name").toLowerCase();//get Os name
     if(os.indexOf("win") > 0){//checking if os is *nix or windows
         //This is windows
         m.ListFiles(new File("/storage"));//do some staf for windows i am not so sure about '/storage' in windows
         //external drive will be found on
     }else{
         //Some *nix OS
         //all *nix Os here
         m.ListFiles(new File("/media"));//if linux removable drive found on media
         //this is for Linux

     }

 }

 void ListFiles(File fls)//this is list drives methods
             throws IOException {
     while(true){//while loop

 try {
    Thread.sleep(5000);//repeate a task every 5 minutes
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
     Process p = Runtime.getRuntime().exec("ls "+fls);//executing command to get the output
     BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));//getting the output
             String line;//output line
                while((line = br.readLine()) != null){//reading the output
                 System.out.print("removable drives : "+line+"\n");//printing the output
           }
          /*You can modify the code as you wish.
          * To check if external storage drivers pluged in or removed, compare the lenght
          * Change the time interval if you wish*/
           }

      }
 }

A: I wrote this program. At the beginning of the program, do DriverCheck.updateDriverInfo(). Then, to check to see if a usb has been plugged in or pulled out, use DriverChecker.driversChangedSinceLastUpdate() (returns boolean).
To check if a usb has been inserted, use newDriverDetected(). To check if a usb has been removed, use driverRemoved()
This pretty much checks for all disc drives from A:/ to Z:/. Half of them can't even exist, but I check for all of them anyways.
package security;

import java.io.File;

public final class DriverChecker {
    private static boolean[] drivers = new boolean[26];

    private DriverChecker() {

    }

    public static boolean checkForDrive(String dir) {
        return new File(dir).exists();
    }

    public static void updateDriverInfo() {
        for (int i = 0; i < 26; i++) {
            drivers[i] = checkForDrive((char) (i + 'A') + ":/");
        }
    }

    public static boolean newDriverDetected() {
        for (int i = 0; i < 26; i++) {
            if (!drivers[i] && checkForDrive((char) (i + 'A') + ":/")) {
                return true;
            }
        }
        return false;
    }

    public static boolean driverRemoved() {
        for (int i = 0; i < 26; i++) {
            if (drivers[i] && !checkForDrive((char) (i + 'A') + ":/")) {
                return true;
            }
        }
        return false;
    }

    public static boolean driversChangedSinceLastUpdate() {
        for (int i = 0; i < 26; i++) {
            if (drivers[i] != checkForDrive((char) (i + 'A') + ":/")) {
                return true;
            }
        }
        return false;
    }

    public static void printInfo() {
        for (int i = 0; i < 26; i++) {
            System.out.println("Driver " + (char) (i + 'A') + ":/ "
                    + (drivers[i] ? "exists" : "does not exist"));
        }
    }
}


text:
Q: Materials pink in new version of Unity I build assetbundles in unity 5.2. I load its assetbundles in scene in new version of Unity 5.3 - then all materials became pink (even if shaders in Standard) http://prntscr.com/ampdr3. If I set again shader Standard - its ok became.
in Editor log I got errors:
GpuProgram creation error: shader program type is unrecognised. You might have a precompiled shader asset from an old Unity version.
WARNING: Shader Unsupported: 'Standard' - Pass 'FORWARD' has no vertex shader
WARNING: Shader Unsupported: 'Standard' - Pass 'FORWARD_DELTA' has no vertex shader
WARNING: Shader Unsupported: 'Standard' - Pass 'SHADOWCASTER' has no vertex shader
WARNING: Shader Unsupported: 'Standard' - All passes removed
WARNING: Shader Unsupported: 'Standard' - Pass 'FORWARD' has no vertex shader
WARNING: Shader Unsupported: 'Standard' - Pass 'FORWARD_DELTA' has no vertex shader
WARNING: Shader Unsupported: 'Standard' - Pass 'SHADOWCASTER' has no vertex shader
WARNING: Shader Unsupported: 'Standard' - All passes removed

A: If your bundle was build with 5.2 you should rebuild it in 5.3 to use it in this version. It is not always true, and sometimes you can use bundle from previous version in new one. We had similar problems in our company, when some people have change their version of unity and others did not. Now one person dictates if we update or not, and we rebuild our bundles after updates.


text:
Q: Why is generalised complex structure defined to be a reduction of structure group to $O(n,n) \cap Gl(n,\mathbb{C})$? It is a basic and "intuition request" question. I have asked it on StackExchange yet it is probably to specialized for it since there were no answears.
Generalised complex structure is defined to be a field of endomorphisms $\mathcal{J}$ of the big tangent bundle $T^{big}M=TM \oplus T^*M$ such that $\mathcal{J}^2=-I$ and being orthogonal with respect to "natural paring" - neutral metric - $<X+ \xi, Y+\eta>=\xi(Y)+\eta(X)$. The first condition gives reduction of structure group of $T^{big}M$ to complex group, my question is why do we require the second condition?

A: This condition implies that $J $ preserves the natural pairing. This is quite typical; if one puts a metric on a complex manifold one usually requires the analogous condition to hold, making it a Kahler manifold.


text:
Q: Android Weather app crashing-network error I have been developing a weather app through Treehouse and unfortunately no one has been able to help me fix this perticular error.
For some reason no weather data is retrieved on the app. I signed up through forecast IO to get the weather data to the app but nothing appears and the app crashes.
I use my phone as an emulator but I receive no errors in the log. Only when I use the Android Studio emulator do I receive an error in the logcat. Any suggestions ?
Stormy app on gitHub
Github
MainActivity.java file
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import butterknife.ButterKnife;
import butterknife.InjectView;

public class MainActivity extends ActionBarActivity {
public static final String TAG = MainActivity.class.getSimpleName();
    private CurrentWeather mCurrentWeather;

    @InjectView(R.id.timeLabel) TextView mTimeLabel;
    @InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
    @InjectView(R.id.humidityValue) TextView mHumidityValue;
    @InjectView(R.id.precipValue) TextView mPrecipValue;
    @InjectView(R.id.summaryLabel) TextView mSummaryLabel;
    @InjectView(R.id.iconImageView) ImageView mIconImageView;
    @InjectView(R.id.refreshImageView) ImageView mRefreshImageView;
    @InjectView(R.id.progressBar)ProgressBar mProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);

        mProgressBar.setVisibility(View.INVISIBLE);

        final double latitude = 38.627;
        final double longitude = -90.199;

        mRefreshImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getForecast(latitude, longitude);
            }
        });

        getForecast(latitude, longitude);

        Log.d(TAG, "Main UI code is running!");

        }

    private void getForecast(double latitude, double longitude) {
        String apiKey = "8ec5f1674002ab5081cad28e9be10ced";
        String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
                "/" + latitude + "," + longitude;

        if(isNetworkAvailable()) {
            toggleRefresh();

            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().
                    url(forecastUrl)
                    .build();

            Call call = client.newCall(request);
            call.enqueue(new Callback() {

                @Override
                public void onFailure(Request request, IOException e) {
                    toggleRefresh();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            toggleRefresh();
                        }
                    });

                    alertUserAboutError();

                }

                @Override
                public void onResponse(Response response) throws IOException {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            toggleRefresh();
                        }
                    });
                    try {
                        String jsonData = response.body().string();
                        Log.v(TAG, response.body().string());
                        if (response.isSuccessful()) {
                            mCurrentWeather = getCurrentDetails(jsonData);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    updateDisplay();
                                }
                            });
                            updateDisplay();
                        } else {
                            alertUserAboutError();
                        }
                    } catch (IOException e) {
                        Log.e(TAG, "Exception caught: ", e);
                    }
                      catch (JSONException e) {
                        Log.e(TAG, "Exception caught:", e);
                    }

                }

            });
        }
        else {
            Toast.makeText(this, getString(R.string.network_unavailable_message),
                    Toast.LENGTH_LONG).show();
        }
    }

    private void toggleRefresh() {
        if (mProgressBar.getVisibility() == View.INVISIBLE) {
            mProgressBar.setVisibility(View.VISIBLE);
            mRefreshImageView.setVisibility(View.INVISIBLE);
        } else {
            mRefreshImageView.setVisibility(View.INVISIBLE);
            mRefreshImageView.setVisibility(View.VISIBLE);
        }
    }

    private void updateDisplay() {
        mTemperatureLabel.setText(mCurrentWeather.getTemperature() + "");
        mTimeLabel.setText("At" + mCurrentWeather.getFormattedTime() + " it will be");
        mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
        mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "%");
        mSummaryLabel.setText(mCurrentWeather.getSummary());

        Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
        mIconImageView.setImageDrawable(drawable);
    }

    private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
            JSONObject forecast = new JSONObject(jsonData);
            String timezone = forecast.getString("timezone");
            Log.i(TAG, "From JSON:" + timezone);

            JSONObject currently = forecast.getJSONObject("currently");

            CurrentWeather currentWeather = new CurrentWeather();
            currentWeather.setHumidity(currently.getLong("time"));
            currentWeather.setTime(currently.getLong("time"));
            currentWeather.setIcon(currently.getString("icon"));
            currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
            currentWeather.setTemperature(currently.getDouble("temperature"));
            currentWeather.setTimeZone(timezone);

            Log.d(TAG, currentWeather.getFormattedTime());

            return new CurrentWeather();
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager manager = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        boolean isAvailable = false;
        if(networkInfo != null && networkInfo.isConnected()) {
         isAvailable = true;

        }
        return isAvailable;
    }

    private void alertUserAboutError() {
        AlertDialogFragment dialog = new AlertDialogFragment();
        dialog.show(getFragmentManager(), "error_dialog");
    }
}

"PropertyFetcher: AdbCommandRejectedException getting properties for
  device 0043d8b5c84ed1f5: device unauthorized.

Please check the confirmation dialog on your device."
Error log
02-10 14:17:31.130 52-52/? I/qemu-props﹕ received: qemu.hw.mainkeys=0
02-10 14:17:33.180 56-56/? I/SurfaceFlinger﹕ SurfaceFlinger's main thread ready to run. Initializing graphics H/W...
02-10 14:18:51.060 624-624/? D/AndroidRuntime﹕ Calling main entry com.android.commands.pm.Pm
02-10 14:19:01.630 548-548/com.android.launcher I/Choreographer﹕ Skipped 346 frames! The application may be doing too much work on its main thread.
02-10 14:19:02.750 437-437/? I/Choreographer﹕ Skipped 1210 frames! The application may be doing too much work on its main thread.
02-10 14:19:04.920 386-386/system_process W/BroadcastQueue﹕ Failure sending broadcast Intent { act=android.intent.action.TIME_TICK flg=0x50000014
(has extras) } android.os.TransactionTooLargeException
at android.os.BinderProxy.transact(Native Method)
at android.app.ApplicationThreadProxy.scheduleRegisteredReceiver(ApplicationThreadNative.java:1059)
at com.android.server.am.BroadcastQueue.performReceiveLocked(BroadcastQueue.java:421)
at com.android.server.am.BroadcastQueue.deliverToRegisteredReceiverLocked(BroadcastQueue.java:507)
at com.android.server.am.BroadcastQueue.processNextBroadcast(BroadcastQueue.java:714)
at com.android.server.am.ActivityManagerService.finishReceiver(ActivityManagerService.java:13807)
at android.content.BroadcastReceiver$PendingResult.sendFinished(BroadcastReceiver.java:419)
at android.content.BroadcastReceiver$PendingResult.finish(BroadcastReceiver.java:395)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:785)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at com.android.server.ServerThread.initAndLoop(SystemServer.java:1093)
at com.android.server.SystemServer.main(SystemServer.java:1179)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
02-10 14:19:08.800 386-386/system_process I/Choreographer﹕ Skipped 34 frames! The application may be doing too much work on its main thread.
02-10 14:19:19.860 548-548/com.android.launcher I/Choreographer﹕ Skipped 1089 frames! The application may be doing too much work on its main thread.
02-10 14:19:23.320 718-718/com.android.systemui I/Choreographer﹕ Skipped 679 frames! The application may be doing too much work on its main thread.
02-10 14:19:25.100 718-718/com.android.systemui I/Choreographer﹕ Skipped 106 frames! The application may be doing too much work on its main thread.
02-10 14:19:27.700 718-718/com.android.systemui I/Choreographer﹕ Skipped 154 frames! The application may be doing too much work on its main thread.
02-10 14:19:30.720 548-548/com.android.launcher I/Choreographer﹕ Skipped 61 frames! The application may be doing too much work on its main thread.
02-10 14:19:57.300 893-893/? D/AndroidRuntime﹕ Calling main entry com.android.commands.am.Am
02-10 14:19:57.400 386-398/system_process I/ActivityManager﹕ START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=aurielvilaire.com.stormy/.MainActivity} from pid 893
02-10 14:19:57.890 386-714/system_process I/ActivityManager﹕ Start proc aurielvilaire.com.stormy for activity aurielvilaire.com.stormy/.MainActivity: pid=928 uid=10054 gids={50054, 3003}
02-10 14:20:00.640 928-928/aurielvilaire.com.stormy D/MainActivity﹕ Main UI code is running!
02-10 14:20:02.170 386-400/system_process I/ActivityManager﹕ Displayed aurielvilaire.com.stormy/.MainActivity: +4s339ms
02-10 14:20:05.540 928-943/aurielvilaire.com.stormy D/MainActivity﹕ 1:20 PM
02-10 14:20:05.600 928-943/aurielvilaire.com.stormy E/AndroidRuntime﹕ FATAL EXCEPTION: OkHttp Dispatcher Process: aurielvilaire.com.stormy, PID: 928 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6094)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:824)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:352)
at android.view.View.requestLayout(View.java:16431)
at android.widget.TextView.checkForRelayout(TextView.java:6600)
at android.widget.TextView.setText(TextView.java:3813)
at android.widget.TextView.setText(TextView.java:3671)
at android.widget.TextView.setText(TextView.java:3646)
at aurielvilaire.com.stormy.MainActivity.updateDisplay(MainActivity.java:154)
at aurielvilaire.com.stormy.MainActivity.access$500(MainActivity.java:31)
at aurielvilaire.com.stormy.MainActivity$2.onResponse(MainActivity.java:122)
at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:162)
at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
02-10 14:20:05.650 386-397/system_process W/ActivityManager﹕ Force finishing activity aurielvilaire.com.stormy/.MainActivity
02-10 14:20:05.710 386-414/system_process W/InputDispatcher﹕ channel 'b20c7078 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
02-10 14:20:05.710 386-414/system_process E/InputDispatcher﹕ channel 'b20c7078 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
02-10 14:20:05.720 386-606/system_process W/InputDispatcher﹕ Attempted to unregister already unregistered input channel 'b20c7078 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity (server)'
02-10 14:20:05.720 386-606/system_process I/WindowState﹕ WIN DEATH: Window{b20c7078 u0 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity}
02-10 14:20:05.960 386-397/system_process I/WindowManager﹕ Screenshot max retries 4 of Token{b2051338 ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity t2 f}} appWin=Window{b20c7078 u0 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity EXITING} drawState=4
02-10 14:20:07.260 548-548/com.android.launcher I/Choreographer﹕ Skipped 59 frames! The application may be doing too much work on its main thread.
02-10 14:20:08.550 386-400/system_process W/WindowManager﹕ This window was lost: Window{b20c7078 u0 aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity}
02-10 14:20:08.550 386-400/system_process W/WindowManager﹕ mDisplayId=0 mSession=Session{b210e748 928:u0a10054}
mClient=android.os.BinderProxy@b2116298 mOwnerUid=10054
mShowToOwnerOnly=true package=aurielvilaire.com.stormy appop=NONE
mAttrs=WM.LayoutParams{(0,0)(fillxfill) sim=#120 ty=1 fl=#1810100
pfl=0x8 wanim=0x10302a1} Requested w=1080 h=1776 mLayoutSeq=71
mBaseLayer=21000 mSubLayer=0 mAnimLayer=21000+0=21000 mLastLayer=0
mToken=AppWindowToken{b208c460 token=Token{b2051338
ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity
t2}}} mRootToken=AppWindowToken{b208c460 token=Token{b2051338
ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity
t2}}} mAppToken=AppWindowToken{b208c460 token=Token{b2051338
ActivityRecord{b207d380 u0 aurielvilaire.com.stormy/.MainActivity
t2}}} mViewVisibility=0x0 mHaveFrame=true mObscured=true mSeq=0
mSystemUiVisibility=0x0 mPolicyVisibility=false
mPolicyVisibilityAfterAnim=false mAppOpVisibility=true
mAttachedHidden=false mGivenContentInsets=[0,0][0,0]
mGivenVisibleInsets=[0,0][0,0] mConfiguration={1.0 310mcc260mnc en_US
ldltr sw360dp w360dp h567dp 480dpi nrml port finger qwerty/v/v -nav/h
s.5} mHasSurface=true mShownFrame=[0.0,0.0][1080.0,1776.0]
isReadyForDisplay()=false mFrame=[0,0][1080,1776]
last=[0,0][1080,1776] mSystemDecorRect=[0,0][1080,1776]
last=[0,0][1080,1776] Frames: containing=[0,0][1080,1776]
parent=[0,0][1080,1776] display=[0,0][1080,1776]
overscan=[0,0][1080,1920] content=[0,75][1080,1776]
visible=[0,75][1080,1776] decor=[0,0][1080,1920] Cur insets:
overscan=[0,0][0,0] content=[0,75][0,0] visible=[0,75][0,0] Lst
insets: overscan=[0,0][0,0] content=[0,75][0,0] visible=[0,75][0,0]
WindowStateAnimator{b20db3d0
aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity}:
mSurface=Surface(name=aurielvilaire.com.stormy/aurielvilaire.com.stormy.MainActivity)
mDrawState=HAS_DRAWN mLastHidden=true Surface: shown=false layer=21005
alpha=0.0 rect=(0.0,0.0) 1080.0 x 1776.0 mShownAlpha=1.0 mAlpha=1.0
mLastAlpha=-1.0 mGlobalScale=1.0 mDsDx=1.0 mDtDx=0.0 mDsDy=0.0
mDtDy=1.0 mExiting=false mRemoveOnExit=false mDestroying=true
mRemoved=false
02-10 14:20:52.610 386-606/system_process I/ActivityManager﹕ Start proc com.android.email for broadcast com.android.email/.service.EmailBroadcastReceiver: pid=1049 uid=10024 gids={50024, 3003, 1028, 1015}
02-10 14:20:53.400 1049-1063/com.android.email D/ActivityThread﹕ Loading provider com.android.email.provider;com.android.email.notifier: com.android.email.provider.EmailProvider
02-10 14:20:58.452 386-583/system_process W/ActivityManager﹕ Unable to start service Intent { cmp=com.android.email/.service.AttachmentDownloadService } U=0: not found
02-10 14:20:58.522 1049-1103/com.android.email I/Email﹕Observing account changes for notifications
02-10 14:20:58.622 386-432/system_process I/ActivityManager﹕ Start proc com.android.exchange for service com.android.exchange/.service.EmailSyncAdapterService: pid=1104 uid=10025 gids={50025, 3003, 1028, 1015}
02-10 14:20:58.622 386-607/system_process W/ActivityManager﹕ Unable to start service Intent { cmp=com.android.email/.service.AttachmentDownloadService } U=0: not found
02-10 14:20:58.882 1049-1065/com.android.email D/dalvikvm﹕ GC_FOR_ALLOC freed 313K, 16% free 3359K/3960K, paused 231ms, total 254ms
02-10 14:21:49.352 718-718/com.android.systemui I/Choreographer﹕ Skipped 32 frames! The application may be doing too much work on its main thread.

A: After reading through that and looking at your code, I believe the main culprit here is that you are doing to much on the main thread. You should use the android AsyncTask to run especially network connections on a separate thread. For example you might use:
private class DownloadForecast extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
      getForecast(); //run all your network intensive methods
      return response;
    }

@Override
protected void onPostExecute(String result) {
  //update all your UI stuff.
}

Can't seem to correctly intent the code. But thats what you should use. Good luck.


text:
Q: Multiple errors with Package Control in Sublime Text 3 I have installed Sublime Text 3 (unregistered, version: 3103 linux x64).
Now I want to install Package Control.
I tried to do this by paste the  code into the console.
But I had the follow error:
TypeError: unsupported operand type(s) for +=: 'NoneType' and 'str'

Next, I tried to manually install Package Control, but when I click the Preferences > Browse Packages… menu. But I saw the next:
image
What I should do to fix it?
p.s. there is no 'package_control' in the 'ignored_packages' setting


text:
Q: handlesubmit is undefined when i am writing the code in react functional component heres the code for the register component in which i have written using react functional components. what am i missing ,react states? the code is below.
import React, {useState} from 'react'
import './Register.css'
import axios from 'axios'

function Register() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');

     const handleSubmit = (e) => {
        e.preventDefault();
        const data = {name , email, password, confirmPassword};

        console.log('data');

     }

    return (

सवारी नविकरणको लागि

<form4 onSubmit={handleSubmit}>

 Name

<input type="text" placeholder="पुरा नाम लेख्नुहोस्"  value={name} onChange={e => setName(e.target.value)}/>

 Email-Address

<input type="Email" placeholder="ईमेल लेख्नुहोस्" value={email} onChange={e => setEmail(e.target.value)}/>

 Password

<input type="Password" placeholder="पासवर्ड लेख्नुहोस्s" value={password} onChange={e => setPassword(e.target.value)}/>

 Confirm Password

<input type="Password" placeholder="पुन: पासवर्ड लेख्नुहोस्" value={confirmPassword} onChange={e => setConfirmPassword(e.target.value)} />

<button type="submit" className="signup__registerButton" >Register Now</button>

</form4>

    )
    }

export default Register

I think all the code is good but only the handle submit says error. i am new to react pls help.

A: Line 7 should be
const handleSubmit = (e) => {


text:
Q: Do NSArrays stay sorted when saved then retrieved from a plist Simple question do NSArrays stay sorted when saved to a plist and then retrieved?
I am having a sorting issue when i retrieve my array from my plist so i was curious.
I think it may also be a problem with this line. Do these maintain the order from titles followed the order of titleArr?
NSMutableArray *allTitles = [[NSMutableArray alloc] init];
[allTitles addObjectsFromArray:titles];
[allTitles addObjectsFromArray:titleArr];

How I save to plist
imageInfo = [[NSMutableArray array] init];

    NSMutableArray *Listing = [NSMutableArray array];
    [imageInfo addObject:Listing];

    NSDictionary *Images = [NSDictionary dictionaryWithObjectsAndKeys:
                            allTitles, kKeyTitle,
                            allMediaUrls, kKeyThumbUrl,
                            allWidths, kKeyThumbWidth,
                            allHeights, kKeyThumbHeight,
                            nil];
    [Listing addObject:Images];

    NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,NSUserDomainMask, YES);

    NSString *documentsDirectory = [sysPaths objectAtIndex:0];

    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"image.plist"];

    NSLog(@"Plist File Path: %@", filePath);

    BOOL didWriteToFile = [imageInfo writeToFile:filePath atomically:YES];

    if (didWriteToFile) {
        NSLog(@"Write to .plist file is a SUCCESS!");
    } else {
        NSLog(@"Write to .plist file is a FAILURE!");
    }

A: Yes if titles and titleArr are sorted than allTitles  will also be sorted.
First all objects of titles will be added and than at all objects titleArr will be added as addObjectsFromArray method starts adding object array towards the end of receiving array.
Here is more info from Apple Docs

Adds the objects contained in another given array to the end of the
  receiving array's content.

So yes plist  will have sorted array.

A: Severe bug:
imageInfo = [[NSMutableArray array] init];

[NSMutableArray array] returns an initialised and autoreleased array.
Sending an init message to that array is not a good idea.


text:
Q: Short exact sequences of modules If we have the following  exact sequences of $R-$modules
$0 \rightarrow M_1 \stackrel{f} \rightarrow N \stackrel{g} \rightarrow L_1 \rightarrow 0$
$0 \rightarrow M_2 \stackrel{h} \rightarrow N \stackrel{k} \rightarrow L_2 \rightarrow 0$
and we know that $k \circ f$ is a R-isomorphism

How can we show that  $g \circ h$ is also a R-isomorphism?

A: Well, I just played with your sequences and here is my partial solution.
We need to show two things. First, that $\ker(g\circ h)=\{0\}$ and second, that $g\circ h$ is surjective.
To show that $\ker(g\circ h)=\{0\}$ we chose an element $x\in \ker(g\circ h)$, so $(g\circ h)(x)=g(h(x))=0$, this means that $h(x)\in \ker(g)=\text{Im}(f)$, so there is some $y\in M_1$ such that $h(x)=f(y)$. Applying $k$ to both sides we get $k(h(x))=k(f(y))$, but $h(x)\in \text{Im}(h)=\ker(k)$, thus $k(f(y))=k(h(x))=0$. By hypothesis $k\circ f$ is iso, hence $y=0$ and this gives us that $h(x)=f(y)=f(0)=0$. Since $h$ is injective, we conclude that $x=0$, as desired.
To show that $g\circ h$ is surjective, you have to use your hypothesis and "play" like I did to prove that $\ker(g\circ h)=\{0\}$.


text:
Q: Calculate change to be given to customer on POS javascript Can any one help me with this, I'm trying to use this code on a POS to calculate the change to give a customer and it works for the must part.
The problem I'm having is if I an order costs £9.99 and I enter £10, instead of it calculating the change as £0.01 it calculates it as £ 0.009999999999999787
Here is the code that I'm using.

function sum() {
    var og_total = document.getElementById('og_cart_total').value;
    var og_tendered = document.getElementById('og_cash_tendered').value;
    var og_change = (og_tendered - og_total).toFixed(2);
    var og_symbol = '£';
    if (!isNaN(og_change)) {
        document.getElementById('og_change_given').value = og_symbol + og_change;
    }
}
<input type="hidden" id="og_cart_total"  value="19.99" onkeyup="sum();" />

Tendered:

 <input class="cm-autocomplete-off" type="text" name="payment_info[og_cash_tendered]" value="" id="og_cash_tendered" onkeyup="sum();" />

Change:

 <input type="text" name="payment_info[og_change_given]" id="og_change_given" value="£-19.99" readonly="readonly" />

A: there is this way but it's not as promising as it should. the best way is to use a library for long numbers if it worth the trouble.

function sum() {
            var og_total = document.getElementById('txt1').value;
            var og_tendered = document.getElementById('txt2').value;
            var og_change = (og_tendered - og_total).toFixed(2);
            var og_symbol = "£";
            if (!isNaN(og_change)) {
                document.getElementById('og_change_text').value = og_symbol + og_change;
            }
        }
<input type="text" id="txt1"  value="9.99" readonly="readonly" onkeyup="sum();" />
<input type="text" id="txt2"  onkeyup="sum();" />
<input type="text" readonly="readonly" id="og_change_text" />


text:
Q: Inserting data in MySQL table only if it doesn't exist already: trouble with INSERT IGNORE so I've been looking around StackOverflow and the MySQL manual for a while, and I can't seem to solve my problem. What I'm trying to do is simply make my data INSERT function such that it doesn't add anything to my table if it already exists. I saw a few methods: the INSERT IGNORE function, together with a unique index, was the one that seemed the best for me, but I have no idea why it is not working... Here is a portion of my code (I have two columns: 'username' and 'email', and my table is called 'info4'):
$unique_index = mysqli_query ($con, "CREATE UNIQUE INDEX index ON info4 ( username, email);");

$insert = mysqli_query($con, "INSERT IGNORE INTO info4 (`username`, `email`) VALUES ('$array_values[0]', '$array_values[1]')");

Where am I going wrong? Am I missing anything?

A: You can't create an index named index.
Mysql is not case sensitive. Your INDEX wrongly named "index" won't work.
Example:
mysql> create index index on tbladresse (strasse_zusatz);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'index
 on tbladresse (strasse_zusatz)' at line 1
mysql> create index iindex on tbladresse (strasse_zusatz);
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0

A: Insert Ignore simply tells MySQL to not issue a duplicate key error when trying to insert duplicate data into fields with unique constraints.
The unique index should be all you need to stop duplicate entries from being inserted.
Generally you wouldn't want to do things like add indexes using PHP, you should do that via whatever tool you are using to access your database.
Are you seeing duplicate username/email combos being inserted into your table? What are the values of $array_values[0] and $array_values[1] ?
If you do SHOW INDEX FROM info4 do you see your unique index?


text:
Q: Is there any good articles about Python 3 changes? I'm returning Python developer. I was working with 2.7 last time. And i want to read full list of new things and changes in 3.3 since 2.7. Does anyone know something good?
PS: Yeah, i know that there it is for me in the documentation, but i want a single article with some author's thoughts about these changes.

A: http://docs.python.org/3/whatsnew/3.0.html
This article explains the new features in Python 3.0, compared to 2.6.

A: I found this pdf very informative. It is a free 4-page cheat sheet of differences provided by the publisher of "Programming in Python 3" book by Mark Summerfield.
In response to your PS, this is not an article, but a very easy to grasp categorized list of differences.


text:
Q: Is there any way to fill bubbles partially in highcharts bubble chart? Is there is any way to fill individual bubble's partially / fully (depending on % text in bubble) with different shade's of bubble color using highcharts.
I am trying to achieve this through renderer options, but not getting proper information.
Any reference link is also appreciated.
Regards,
Sopo

A: You can set for each bubble specific color, so also you can se gradients. For example 25% of bubble should be filled with red, the rest with light red: http://jsfiddle.net/TL3AV/
var chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container',
        type: 'bubble'
    },
    plotOptions: {
        bubble: {
            states: {
                hover: {
                    enabled: false
                }
            }
        }
    },
    series: [{
        data: [{
            x: 29.9,
            y: 71.5,
            z: 106.4
        }, {
            x: 129.2,
            y: 144.0,
            z: 176.0,
            color: {
                linearGradient: {
                    x1: 0,
                    x2: 0,
                    y1: 0,
                    y2: 1
                },
                stops: [
                    [0, 'rgb(255,100,100)'],
                    [0.25, 'rgb(255,100,100)'],
                    [0.26, 'rgb(255,200,200)'],
                    [1, 'rgb(255,200,200)']
                ]
            }
        }]
    }]
});

I advice to disable hover, to prevent changing color to default one.

A: Gradient done with svg element. I had to put it at the end of code othervise I got nothing:
<!DOCTYPE html>

<meta charset=utf-8 />
<title>SO Q#</title>

<svg>
    <linearGradient id="r" >
    <stop offset="0" stop-color="red"/>
    <stop offset="1" stop-color="green"/>
    </linearGradient>
</svg>


text:
Q: EXC_BAD_ACCESS when I work with arrays I always have error when working with arrays (non ARC code).
My code:
@implementation InfoController

NSMutableArray *lbCityArray;
NSMutableArray *lbTimeArray;
NSMutableArray *lbCameInArray;
NSMutableArray *lbCameOutArray;
NSMutableArray *lbInArray;
NSMutableArray *lbOutArray;

in ViewDidLoad I do something
- (void)viewDidLoad
{
    [super viewDidLoad];

    lbCityArray = [[NSMutableArray alloc] initWithCapacity:1];
    lbTimeArray = [[NSMutableArray alloc] initWithCapacity:1];
    lbCameInArray = [[NSMutableArray alloc] initWithCapacity:1];
    lbCameOutArray = [[NSMutableArray alloc] initWithCapacity:1];
    lbInArray = [[NSMutableArray alloc] initWithCapacity:1];
    lbOutArray = [[NSMutableArray alloc] initWithCapacity:1];

    //—add some values to arrays
    NSString *City = @"London";
    [lbCityArray addObject:City];
    //—————————————-----------------------//

}

and always when I click Back button app crash with EXC_BAD_ACCESS. If I comment adding values to array all work, Back button don't crash app. I read if you use non ARC code you must manually release in dealloc.
I add to dealloc
[_InfoTableView release];
[lbCityArray release];
[lbTimeArray release];
[lbCameInArray release];
[lbCameOutArray release];
[lbInArray release];
[lbOutArray release];
[super dealloc];

and nothing changes, app still crash.  Where can be problem ?
Solution - I move to ARC and all problems gone. Thanks.

A: It would help a lot if you made your variables into instance variables instead of global variables.
Change this:
@implementation InfoController

NSMutableArray *lbCityArray;
NSMutableArray *lbTimeArray;
NSMutableArray *lbCameInArray;
NSMutableArray *lbCameOutArray;
NSMutableArray *lbInArray;
NSMutableArray *lbOutArray;

into:
@implementation InfoController {
    NSMutableArray *lbCityArray;
    NSMutableArray *lbTimeArray;
    NSMutableArray *lbCameInArray;
    NSMutableArray *lbCameOutArray;
    NSMutableArray *lbInArray;
    NSMutableArray *lbOutArray;
}

Without the curly braces you are actually creating global variables, not instance variables.


text:
Q: Using a For Loop to work with many variables where the names differ only slightly (different numbers) I have a program where I am using several hundred JToggleButtons. Their names differ only slightly by numbers (e.g. jToggleButton1, jToggleButton2, jToggleButton3,...)
Is there a way that I can use a for loop when doing the same thing to multiple buttons?
For instance, if I want to programmatically change the states of several buttons, could I loop through them, changing the ending number of the name each time?

A: You could try to put them all in an array or ArrayList and use a foreach loop.
ArrayList<JToggleButton> toggleButtonArrayList = new ArrayList<JToggleButton>();
// ... insert your JToggleButtons to the ArrayList here...

for (JToggleButton myButton : toggleButtonArrayList) {
    myButton.changeSomething();
    // ...  do whatever you want here ...
}

A: The easiest way to achieve this by putting all the buttons into an array, or an ArrayList.


text:
Q: How do I deploy versioned releases using cmake and git? My project uses git for version control, and cmake for the build/install process.
When i want to release my project for other devs to use, i'll typically git tag x.y, followed by make install to a directory (set using CMAKE_INSTALL_PREFIX), let's call it /tmp/release.
I'd like to automate/combine this process, so that any time i attempt to install, cmake adds a git tag by incrementing the minor (minors at 99 rollover to 0, and the major is incremented), pushes the tag to remote, and then installs to /tmp/release/x.y
i.e, 5.67 - > 5.68 and 5.99 -> 6.00
This sounds like it should be possible, but i'm having trouble connecting the dots and making this cohesive.
Any suggestions on modules that already exist to do this, or writing this from scratch?


text:
Q: Charge determines masses? Why are the masses of the $\Sigma^-$ ($1197\ \mathrm{MeV}$) and $\Sigma^+$ ($1189\ \mathrm{MeV}$) particles are not exactly equal?
$\Sigma^-$ has quark context $\rm dds$ and $\Sigma^+$ has $\rm uus$...I have been thinking that this has to do with their charge, but I am not sure how that directly relates to mass?

A: The $\Sigma^\pm$ are not antiparticles of each other; both are baryons with a single strange quark and nonzero isospin. If isospin were an exact symmetry then they would have the same mass — but if isospin were an exact symmetry, the proton and neutron would have the same mass as well, and our universe would be very different.
The antiparticle of the $\Sigma^+$ is an antibaryon with quark content $\rm\bar u\bar u\bar s$, and similarly for the $\Sigma^-$.
I'm actually not 100% how to write that particle's name; in the first draft of that sentence I made a different choice than in this old answer.


text:
Q: Is there any way to save and read multi-dimension data with efficiency? Introduction

*

*I have a bunch of data series with 1000 stations and each station all have 4 features (e.g Temperature, Wind, CO2 concentration, solar radiation).

*All the features are in time-series with hourly resolution.
I read this data in .csv files with the support of Pandas.
Now I need to save and organize them together for better re-use.
My solution
I creat columns entitled by 'sample_x, feature_y'. And each column contain the time series data of feature_y for sample_x.
This method is doable but not show efficiency. Because I had to creat like 4000 columns  with long column name.
My question
Is there any better way to save multi-demensions data in Python. I want a simple solution that can help me assessing and handling with specific data directly.
Any advices or solution is appreciated!

A: I think you can use MultiIndex or Panel and then if necessary save data to hdf5.
Also function concat have parameter keys which create MultiIndex from list of DataFrames.
Sample:
df1 = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5]})

print (df1)
   A  B  C  D
0  1  4  7  1
1  2  5  8  3
2  3  6  9  5

df2 = df1 * 10

dfs = [df1, df2]

df3 = pd.concat(dfs, keys=['a','b'])
print (df3)
      A   B   C   D
a 0   1   4   7   1
  1   2   5   8   3
  2   3   6   9   5
b 0  10  40  70  10
  1  20  50  80  30
  2  30  60  90  50

print (df3.index)
MultiIndex(levels=[['a', 'b'], [0, 1, 2]],
           labels=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]])

wp = pd.Panel({'a' : df1, 'b' : df2})
print (wp)
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 3 (major_axis) x 4 (minor_axis)
Items axis: a to b
Major_axis axis: 0 to 2
Minor_axis axis: A to D

A: You may want to use HDF, which has been specifically designed to handle huge arrays of multidimensional data.

A: The simplest answer may be just to create a sqlite3 database.
It sounds like you have 6 pieces of data per hour (station, timestamp, feature1..feature4) times 1000 stations, times however-many hours.
So that's 6000 data items (at, say, 4 bytes each = 24k), times 24 hours/day times 365 days/year (* 8760), or about 200mb, per year. Depending on how far back you're going, that's not too bad for a db file. (If you're going to do more than 10 years, then yeah, go to something bigger, or maybe compress the data or break it up by year or something...)


text:
Q: dplyr create column that calculate percentage based on two columns I have a csv file that looks like this:
Year, Answer, Total
2017, Yes, 100
2017, No, 10
2017, Yes, 100
2018, No, 40
2018, Yes, 200

I'm trying to make a column that calculate the ratio between "No" to "Yes" in a given year. So it will look something like this:
Year, Answer, Total, Ratio
2017, Yes, 100, 1
2017, No, 10, 0.05
2017, Yes, 100, 1
2018, No, 40, 0.2
2018, Yes, 200, 1

I'm using R and dplyr. I think I have to create a column with the total for "Yes" in a given year(there will be duplicates). Then make another column with an ifelse statement, where "Yes" rows will be 1 and "No" rows will be the total NOs divide by the Yes total. Is there a more efficient way to doing this? Thanks

A:
How about this?
library(dplyr)

xdf <- data.frame(
  stringsAsFactors = FALSE,
  Year = c(2017, 2017, 2017, 2018, 2018),
  Answer = c("Yes", "No", "Yes", "No", "Yes"),
  Total = c(100, 10, 100, 40, 200)
)

xdf %>%
  group_by(Year, Answer) %>%
  summarise(Total = sum(Total)) %>%
  mutate(share = if_else(Answer == "No", Total/lead(Total), 1))
#> # A tibble: 4 x 4
#> # Groups:   Year [2]
#>    Year Answer Total share
#>   <dbl> <chr>  <dbl> <dbl>
#> 1  2017 No        10  0.05
#> 2  2017 Yes      200  1
#> 3  2018 No        40  0.2
#> 4  2018 Yes      200  1

A: Here is an approach using a custom function
# function calculating the ratios
f1 <- function(k){
   ind.yes <- intersect(which(df$year == df$year[k]),
                        which(df$answer == "yes")
               )
   ind.no <- intersect(which(df$year == df$year[k]),
                       which(df$answer == "no")
             )
   total.yes <- sum(df$total[ind.yes])
   total.no <- sum(df$total[ind.no])

   ratio.no.yes <- total.no/total.yes
   return(ratio.no.yes)
}

# vapplying function f1
ratios <- vapply(1:nrow(df), f1, numeric(1))

# binding the data
df$ratios <- ratios

And here is the result (using a dummy data frame)
df <- data.frame(
                 year = sample(2015:2018, 10, replace = T),
                 answer = sample(c("yes", "no"), 10, replace = T),
                 total = sample(10:200, 10, replace = T),
                 stringsAsFactors = F)
ratios <- vapply(1:nrow(df), f1, numeric(1))
df$ratios <- ratios

# printing
> df
  year answer total     ratios
1  2015    yes    76 0.08294931
2  2017    yes    43 2.55263158
3  2018    yes    63 0.00000000
4  2016    yes    61 0.83606557
5  2015     no    18 0.08294931
6  2017     no   142 2.55263158
7  2017    yes    33 2.55263158
8  2015    yes   141 0.08294931
9  2016     no    51 0.83606557
10 2017     no    52 2.55263158

A: I don't think efficiency will matter for this. You can make it a one-liner, though it's harder to read:
DF %>% group_by(Year) %>% mutate(v =
  (Total / sum(Total[Answer == "Yes"]))^(Answer == "No")
)

This x^cond uses x^FALSE = x^0 = 1 to assign the desired value of 1 when Answer != "No".


text:
Q: Group and map array to different format in JavaScript without using any plugin I have an array of objects like below,
cars = [
{id: 1, make: 'audi', year: '2010', someProperty: true},
{id: 2, make: 'bmw', year: '2011', someProperty: false},
{id: 3, make: 'bmw', year: '2011', someProperty: true},
{id: 4, make: 'vw', year: '2010', someProperty: true},
{id: 5, make: 'vw', year: '2011', someProperty: true},
{id: 6, make: 'audi', year: '2011', someProperty: true},
{id: 7, make: 'bmw', year: '2010', someProperty: false},
{id: 8, make: 'bmw', year: '2011', someProperty: false},
{id: 9, make: 'bmw', year: '2010', someProperty: true}
]

I want to format it as below,
requiredFormat = [{
somePropertyTrue: [
{id: 1, make: 'audi', year: '2010', someProperty: true},
{id: 4, make: 'vw', year: '2010', someProperty: true},
{id: 9, make: 'bmw', year: '2010', someProperty: true}
],
somePropertyFalse: [
{id: 7, make: 'bmw', year: '2010', someProperty: false}
],
year: '2010'
}, {
somePropertyTrue: [
{id: 3, make: 'bmw', year: '2011', someProperty: true},
{id: 5, make: 'vw', year: '2011', someProperty: true},
{id: 6, make: 'audi', year: '2011', someProperty: true}
],
somePropertyFalse: [
{id: 2, make: 'bmw', year: '2011', someProperty: false},
{id: 8, make: 'bmw', year: '2011', someProperty: false}
],
year: '2011'
}]

Basically it is to group by year and someProperty = true/false, but want it to be formatted this way. I cannot use any plugin to do this, can use ES6.
I tried using reduce by writing a function that groups by a single property, but I am not sure how do we do it for multiple properties and project it this way. Please find my code to group and what I was able to achieve below,
let groupBy = function(arr, key) {
return arr.reduce(function(r, x) {
  (r[x[key]] = r[x[key]] || []).push(x);
  return r;
 }, {});
};

I was able to achieve below,
ableToDo = [{
'2010' : [
{id: 1, make: 'audi', year: '2010', someProperty: true},
{id: 4, make: 'vw', year: '2010', someProperty: true},
{id: 7, make: 'bmw', year: '2010', someProperty: false},
{id: 9, make: 'bmw', year: '2010', someProperty: true}
],
'2011' : [
{id: 2, make: 'bmw', year: '2011', someProperty: false},
{id: 3, make: 'bmw', year: '2011', someProperty: true},
{id: 5, make: 'vw', year: '2011', someProperty: true},
{id: 6, make: 'audi', year: '2011', someProperty: true},
{id: 8, make: 'bmw', year: '2011', someProperty: false}
]}]

A: You could do this with an ES6 Map that you accumulate with reduce. Here is how that would look:

function transform(cars) {
    return [...cars.reduce ( (acc, car) => {
        const yearGrp = acc.get(car.year) || {
            somePropertyTrue: [],
            somePropertyFalse: [],
            year: car.year
        };
        yearGrp['someProperty' + (car.someProperty ? 'True' : 'False')].push(car);
        return acc.set(car.year, yearGrp);
    }, new Map).values()];
}

var cars = [
    {id: 1, make: 'audi', year: '2010', someProperty: true},
    {id: 2, make: 'bmw', year: '2011', someProperty: false},
    {id: 3, make: 'bmw', year: '2011', someProperty: true},
    {id: 4, make: 'vw', year: '2010', someProperty: true},
    {id: 5, make: 'vw', year: '2011', someProperty: true},
    {id: 6, make: 'audi', year: '2011', someProperty: true},
    {id: 7, make: 'bmw', year: '2010', someProperty: false},
    {id: 8, make: 'bmw', year: '2011', someProperty: false},
    {id: 9, make: 'bmw', year: '2010', someProperty: true}
];

console.log(transform(cars));
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: You could just simply loop again your result, then group the contents.
var groupBy = function(array, key)
{
  let result = {};

  for (let i = 0; i < array.length; i++)
  {
    if (array[i][key] in result) {
      result[array[i][key]].push(array[i]);
    }
    else
    {
      result[array[i][key]] = [array[i]];
    }
  }

  return result;
};
var byYear = groupBy(cars, "year");
var years  = Object.keys(byYear);

// loop those byYear Items
for (var i = 0; i < years.length; i++)
{
   var year = years[i];
   var yearData = byYear[year];
   // Then group those values in the inside
   byYear[year] = groupBy(yearData, "someProperty");
}

console.log(byYear);

// then byYear will be structured the way you wanted it to be.

hope that helps

A: Please use the following code:
var cars = [
{id: 1, make: 'audi', year: '2010', someProperty: true},
{id: 2, make: 'bmw', year: '2011', someProperty: false},
{id: 3, make: 'bmw', year: '2011', someProperty: true},
{id: 4, make: 'vw', year: '2010', someProperty: true},
{id: 5, make: 'vw', year: '2011', someProperty: true},
{id: 6, make: 'audi', year: '2011', someProperty: true},
{id: 7, make: 'bmw', year: '2010', someProperty: false},
{id: 8, make: 'bmw', year: '2011', someProperty: false},
{id: 9, make: 'bmw', year: '2010', someProperty: true}
];
var requiredFormat = [];

function group()
  {
  var spt = [], spf = [], y = "0", nexty;
  temp.sort
    (
    function(x, y)
      {
      return (x.year === y.year ? (x.someProperty > y.someProperty ? -1 : x.someProperty < y.someProperty ? 1 : 0) : x.year < y.year ? -1 : 1);
      }
    ).forEach
      (
      function(e, i, temp)
        {
        nexty = (i < temp.length - 1 ? temp[i+1].year : undefined);
        (e.someProperty === true ? spt : spf).push(e);
        if (e.year !== nexty)
          {
          y = e.year;
          requiredFormat.push({somePropertyTrue: spt, somePropertyFalse: spf, year: y});
          spt = [];
          spf = [];
          y = "0";
          }
        }
      );
  }

var temp = cars.slice(0);
group();
console.log("cars: ", cars);
console.log("temp: ", temp);
console.log("requiredFormat: ", requiredFormat);

You also have the fiddle here, to test it. What this code does is:

*

*firstly, create a temporary copy of cars array, with the help of
slice() method (maybe you still need the original array?)

*secondly, it sorts the temp array, first by year, and then by someProperty, giving you the exact order you'd want in the final result

*finally, it "breaks up" the sorted temp array into the format you require by using 3 variables (spt, spf and y) to store the somePropertyTrue and somePropertyFalse arrays, plus the year, all of which will get "commited" (aka applied to the final result) when the year changes (aka e.year !== nexty, where nexty is the year of the next array element, or undefined if it's the last array element).
You can check each step of the execution by using the console viewer in every browser (you can find it in Developer Tools menu in Chrome, for example). If you want to develop this further, maybe you can use reduce() to shorten the code - me, I didn't yet master the reduce() method enough to use it frequently, so I went for the classical method.
This code often uses the ternary operator to shorten the code (quick explanation here, if you're not familiar with it).

A: You can do a single pass by making your group criteria a function instead of a single field name. Code for that could be:
function groupBy(x, keyfunc) {
    let res = {};
    x.forEach(obj=>{
        let k = keyfunc(obj);
        (res[k]||(res[k]=[])).push(obj);
    });
    return res;
}

Called with let res = groupBy(input, obj=>obj.year+"/"+obj.sameProperty);.
This will however return a single list per group with keys like "2005/true".
To get the structured object you are listing instead you need to do the group operation multiple times and for that a possible solution is recursion:
function groupBy(x, ...keys) {
    if (keys.length === 0) {
        return x;
    } else {
        let res = Object.create(null), key = keys[0];
        x.forEach(obj=>{
            let k = obj[key];
            (res[k]||(res[k]=[])).push(obj);
        });
        let other_keys = keys.slice(1);
        Object.keys(res).forEach(k => {
            res[k] = groupBy(res[k], ...other_keys);
        });
        return res;
    }
}

calling with x.groupBy("year", "sameProperty").
Note also that using an object as a dictionary you're grouping by the conversion to a string of the attribute value; in other words keys values like 2010, "2010" and even [2010] will all end up in the same group.

A: You can achieve the desired format using reduce and a object literal to accumulate the groups:
const result = cars.reduce((state, car) => {
  const { year, someProperty } = car;
  const group = state[year] || { year, somePropertyTrue: [], somePropertyFalse: [] };
  const property = someProperty ? 'somePropertyTrue' : 'somePropertyFalse';
  group[property] = [...group[property], car];
  return { ...state, [year]: group };
}, {});

Because you are using an object to keep the groups, then the variable result would be an object. If you want an Array instead, you can use Object.values on result object.

A:

const cars = [
  { id: 1, make: 'audi', year: '2010', someProperty: true },
  { id: 2, make: 'bmw', year: '2011', someProperty: false },
  { id: 3, make: 'bmw', year: '2011', someProperty: true },
  { id: 4, make: 'vw', year: '2010', someProperty: true },
  { id: 5, make: 'vw', year: '2011', someProperty: true },
  { id: 6, make: 'audi', year: '2011', someProperty: true },
  { id: 7, make: 'bmw', year: '2010', someProperty: false },
  { id: 8, make: 'bmw', year: '2011', someProperty: false },
  { id: 9, make: 'bmw', year: '2010', someProperty: true }
]

const groupedCars =
  cars.reduce((memo, car) => {
    memo[car.year] = memo[car.year] || []
    memo[car.year].push(car)
    return memo
  }, [])

  .reduce((memo, cars, i) => {
    memo[i] = {
      somePropertyTrue: cars.filter(car => car.someProperty),
      somePropertyFalse: cars.filter(car => !car.someProperty),
      year: i
    }
    return memo
  }, [])

  .filter(v => v)

document.querySelector('#out').innerHTML = JSON.stringify(groupedCars, null, 4)
<pre id="out" style />


text:
Q: email encodeURIComponent no longer works after android update After the most recent update my web app no longer fills in the body of emails.
The email client comes up with the proper subject but the body is empty. This web app worked in prior to the most recent (awful) android update. I think its called lollipop.
The following is the jquery code.
$(document).on("click", "#sendEmail",function(){
    $(location).attr('href', 'mailto:?subject='
                         + encodeURIComponent(emailSubject)
                         + "&body="
                         + encodeURIComponent(emailBody)
    );
});

I suspect this has something to do with gmail update. Where do I start looking? Did anyone else experience these problems?

A: For the benefit of anyone else who may be looking for an answer. It seems that this is a gmail bug. I recommend switching to mailDroid or another email client.


text:
Q: Transfer the IMail object to another form There is a function that receives letters:
 private void button1_Click(object sender, EventArgs e)
        {
            ListViewItem list = new ListViewItem("Messages");
            using (imap = new Imap())
            {
                imap.ConnectSSL("imap.yandex.ru");
                imap.Login("----", "---");
                imap.SelectInbox();
                List<long> uids = imap.SearchFlag(Flag.All);
                IMail email;
                listView1.Items.Clear();
                foreach (long uid in uids)
                {
                    ListViewItem lvi = new ListViewItem();
                    email = new MailBuilder().CreateFromEml(imap.GetMessageByUID(uid));
                    lvi.SubItems.Add(email.Subject);
                     listView1.Items.Add(lvi);
                }
            }
        }

Another form that I try to pass to the IMAIL objecto oher form:
    private void button2_Click(object sender, System.EventArgs e)
    {//тут надо пулучать выбранный UID

        //получим выделенный элемент
        int SelectedMessageIndex = listView1.FocusedItem.Index;
       IMail email2 = new MailBuilder().CreateFromEml(imap.GetMessageByUID(SelectedMessageIndex));
        MessageForm messageForm = new MessageForm(SelectedMessageIndex,email2); //нужно передать нужный email
        messageForm.ShowDialog();

    }

But I get the error:

Access to the liquidated object is not possible.
  Object name: "ClientBase".

A: It looks like your imap variable is a class member. The problem lies with this:
using (imap = new Imap())

... in button1_Click(). When the using() code block ends, your imap object gets disposed. When you try using it again in button2_Click() it's already gone. You'll need to either not dispose the object or create a new imap object in button2_Click().


text:
Q: Add certain variables value in between characters in bash I am currently writing one script which creates an issue in jira based on //TODO comments in my java file. for that, i am using JIRA REST API.
here's my testing script which creates only one issue from a file,
#!/bin/bash
file=jira.txt

while IFS='' read -r line || [[ -n "$line" ]]; do
filename=$(tr -d '\n\r' <<< $(cut -d':' -f1 <<< $line))
summary=$(tr -d '\n\r' <<< $(cut -c4- <<< $(cut -d':' -f3 <<< $line)))

echo -e "\033[1mIssue Name\033[0m = $summary"
echo -e "\033[1mDescription\033[0m = $filename"
key="Project-181"
#key=$(curl -u username:password -X POST --data '{
#    "fields": {
#       "project":
#       {
#          "key": "project"
#       },
#       "summary": "'"$summary"'",
#       "description": "'"$filename"'",
#       "issuetype": {
#          "name": "Task"
#       }
#   }
#}' -H "Content-Type: application/json" http://JIRA-URL/rest/api/2/issue/ | jq '.key')
echo "key=$key"
sed  -i "/${summary}/s/$/ ${key}/" $filename
    done < "$file"

OUTPUT of script is,
Issue Name = TODO remove hack for my task
Description = /opt/test/testfile.java
key=project-181

I purposely commented JIRA REST API part as I don't want to generate new issue every time I ran test script
the output of commented JIRA REST API is as same as a variable declared above that
 "key="Project-181"
Content of jira.txt is as follows,
/opt/test/testfile.java:211:            // TODO remove hack for my task

Now if I ran this script it will run successfully but when I check into "testfile.java" I see this,
 // TODO remove hack for my task "Project-181"

I want something like that to happen,
// TODO project-181 Remove hack for my task

Any suggestion would be welcome
Thank You.

A: Given summary="TODO remove hack for my task",
if you want to insert $key after the "TODO",
change the sed line to this:
sed  -i "/${summary}/s/TODO \(.*\)/TODO ${key} \1/" $filename

Your original sed command "/${summary}/s/$/ ${key}/" replaced the end of the line $ with a space followed by $key, effectively appending $key to the end instead of inserting after "TODO".


text:
Q: RSA decrypt error I'm trying to encrypt and decrypt file with small string with RSA.
After encrypting string, program writes to a file private key and crypted text.
Code to encrypt:
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(4096);
string pub = rsa.ToXmlString(false);
string priv = rsa.ToXmlString(true);
string to_crypt = "Hello world, try to crypt me";

byte[] dataToEncrypt = Encoding.ASCII.GetBytes(to_crypt);
rsa.FromXmlString(pub);
dataToEncrypt = rsa.Encrypt(dataToEncrypt, false);

string s = System.Text.Encoding.UTF8.GetString(dataToEncrypt, 0, dataToEncrypt.Length);
WriteFile("crypt", priv+s);

Another program reads text in array and tries to decrypt:
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(4096))
{
byte[] to_decrypt = File.ReadAllBytes(args[0]);
byte[] key = new byte[3219];
byte[] text = new byte[to_decrypt.Length - key.Length];
Buffer.BlockCopy(to_decrypt, 0, key, 0, key.Length);
Buffer.BlockCopy(to_decrypt, key.Length, text, 0, text.Length);

string skey = System.Text.Encoding.UTF8.GetString(key, 0, key.Length);
rsa.FromXmlString(skey);
rsa.Decrypt(text, false);        <---- Error: Bad data
    ...

I've got error:

CryptographicException:Bad data

I made mistake in text array? Wrong size of array?

A: RSA encrypts to ciphertext, which is not UTF-8 but a byte array without any character encoding.
If you want to transport it over a text interface then you should base 64 encode after encryption and base64 decode before decryption.
You can of course also just create a binary file with the encrypted contents.

This during encrypt:
string s = System.Text.Encoding.UTF8.GetString(dataToEncrypt, 0, dataToEncrypt.Length);

and this during decrypt:
byte[] key = new byte[3219];
byte[] text = new byte[to_decrypt.Length - key.Length];
Buffer.BlockCopy(to_decrypt, 0, key, 0, key.Length);
Buffer.BlockCopy(to_decrypt, key.Length, text, 0, text.Length);
...
string skey = System.Text.Encoding.UTF8.GetString(key, 0, key.Length);

is all stuff you don't want nor need.

A: The easiest possible mistake: You're writing a newline at the end of your file, and that newline is being read into to_decrypt/text, making it two (on Windows) bytes bigger than the actual ciphertext.  Compare the length of dataToEncrypt (when it's already encrypted) and text.
As Maarten already said, and many of us have said innumerable times, there aren't strings in (real/modern) cryptography, just bytes.  Base64 is a stable way of sending bytes over a text stream, when that's a requirement.  Your other source of error could be that you're getting a \0 in your text interpretation of the "ciphertext" (which isn't text, but a legacy name from character-based encryption) and it's not round-tripping the way you hope or expect.  I don't think this is your current problem, though, since you're handing the data separation as bytes.
And, just as an FYI: The XML based key export/import don't work in .NET Core, you should use the RSAParameters-based ImportParameters/ExportParameters instead.


text:
Q: Is it possible to login in to another website with a php button? I am trying to make this function in laravel jetstream projecet that I need to login to another website (ex. Facebook, Twitter) using the credentials (ex. email, password) of my logged-in or authenticated user. I am thinking on specifying the url in the , but I am not sure on how to get the data from my database and populate the form of another website and automatically loggedin my user.
The problem that I have is that I have to connect two websites that we made using the credentials (email, password) of one website and used those credentials to open another website, so when the user logged-in to website 1, the dashboard will open and will have a link for website 2 and if the user visited website 2, the user will automatically be logged in to website 2 using the credentials of website 1.
Is this possible using php or I need to use a library for this one? I have no idea on how to do this, is this possible? Thank you.

A: No, you cannot control the user's browser through your own website and log them into another site. That would be a major security risk.

A: You can use firebase that is easy to set up and has all the login methods above you asked for.
https://console.firebase.google.com/project/


text:
Q: connection to NodeJs and Express.io get error i'm newbie in nodejs and express.io , in android application i'm wrote this simple code to connect from android or java but iget connection error
app = require('express.io')()
app.http().io()

// Broadcast the new visitor event on ready route.
app.io.route('ready', function(req) {
    req.io.broadcast('new visitor')
    console.log('ready');
})

// Send client html.
app.get('/', function(req, res) {
    //res.sendfile(__dirname + '/client.html')
  req.io.broadcast('new visitor')
  console.log('hello');
})

app.listen(7076)

this code maybe is correct, after opening http://192.168.1.5:7076 link in browser i get hello message, now with below code i'm try to connect but i get connection error:
private static final String SERVER_ADDRESS = "http://192.168.1.5:7076";
private Socket mSocket;
{
    try {
        mSocket = IO.socket(SERVER_ADDRESS);
    } catch (URISyntaxException e) {
        Log.e("Error URI", String.valueOf(e));
        throw new RuntimeException(e);
    }
}
public class ActivityHome extends FragmentActivity {
    ...
    mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
    mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
    mSocket.on("new message", onNewMessage);
    mSocket.on("user joined", onUserJoined);
    mSocket.on("user left", onUserLeft);
    mSocket.on("typing", onTyping);
    mSocket.on("stop typing", onStopTyping);
    mSocket.connect();
    ...
}

private Emitter.Listener onConnectError = new Emitter.Listener() {
    @Override
    public void call(Object... args) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(),
                        "CONNECT ERROR", Toast.LENGTH_LONG).show();
            }
        });
    }
};


text:
Q: Raw queries no output Hi can ask some help on this raw query it has no output,
   $userproj_id = UserProject::select('projid')->where('user_id', $id)->get()->toArray();
        $flattenid = array_flatten($userproj_id);
        foreach ($flattenid as $projid) {
            $projidarr [] = $projid;
        }

  $users = DB::select('select * from project where projid in  ( ? )  and user_id = 3 ', $projidarr );

but if I will manually do like this, it works fine..
$users = DB::select('select * from project where projid in  ( ? )  and user_id = 3 ', ['12345']);

but when I do this manually no output again.
 $users = DB::select('select * from project where projid in  ( ? )  and user_id = 3 ', ['12345','11111']);

Thank you in advance.

A: It's because in your bindings array, you have to many parameters - the SQL needs only one, and you are providing two.
A proper parameter list would be [implode(',', [12345, 1111])] but in this case it would be a string and the result wouldn't be correct as well
What about this?
DB::table('project')
->whereIn('projid', [12345, 1111])
->where('user_id', '=', 3);

A: Raw Query:
$users = DB::select('select * from project where projid in  ('. implode(',', $projidarr).')  and user_id = 3 ');

and Laravel query:
DB::table('project')
->whereIn('projid', $projidarr)
->where('user_id', '=', 3);


text:
Q: Broken Update Manager in Ubuntu 18.04.5 LTS My taskbar has this notification from Update Manager which says, "A problem occurred when checking for the updates".
I used sudo apt-get update but the output is this:
Hit:1 http://dl.winehq.org/wine-builds/ubuntu bionic InRelease
Hit:2 https://linux.teamviewer.com/deb stable InRelease
Hit:3 http://dl.google.com/linux/chrome/deb stable InRelease
Hit:4 https://updates.signal.org/desktop/apt xenial InRelease
Hit:5 http://in.archive.ubuntu.com/ubuntu bionic InRelease
Hit:6 http://in.archive.ubuntu.com/ubuntu bionic-updates InRelease
Hit:7 http://in.archive.ubuntu.com/ubuntu bionic-backports InRelease
Hit:8 http://ppa.launchpad.net/audio-recorder/ppa/ubuntu bionic InRelease
Hit:9 http://packages.microsoft.com/repos/code stable InRelease
Hit:10 https://packages.microsoft.com/repos/vscode stable InRelease
Hit:11 http://security.ubuntu.com/ubuntu bionic-security InRelease
Hit:12 https://packages.microsoft.com/repos/ms-teams stable InRelease
Get:13 https://packages.cloud.google.com/apt cloud-sdk InRelease [6,739 B]
Get:14 https://download.opensuse.org/repositories/Emulators:/Wine:/Debian/xUbuntu_18.04 ./ InRelease [1,559 B]
Hit:15 https://qgis.org/ubuntu-ltr bionic InRelease
Hit:16 https://download.sublimetext.com apt/stable/ InRelease
Hit:18 http://ppa.launchpad.net/deadsnakes/ppa/ubuntu bionic InRelease
Hit:17 https://packagecloud.io/slacktechnologies/slack/debian jessie InRelease
Hit:19 http://ppa.launchpad.net/libreoffice/ppa/ubuntu bionic InRelease
Err:13 https://packages.cloud.google.com/apt cloud-sdk InRelease
  The following signatures couldn't be verified because the public key is not available: NO_PUBKEY FEEA9169307EA071 NO_PUBKEY 8B57C5C2836F4BEB
Err:14 https://download.opensuse.org/repositories/Emulators:/Wine:/Debian/xUbuntu_18.04 ./ InRelease
  The following signatures were invalid: EXPKEYSIG DFA175A75104960E Emulators OBS Project <Emulators@build.opensuse.org>
Hit:20 http://ppa.launchpad.net/maarten-baert/simplescreenrecorder/ubuntu bionic InRelease
Hit:21 http://ppa.launchpad.net/nilarimogard/webupd8/ubuntu bionic InRelease
Hit:22 http://ppa.launchpad.net/sunderme/texstudio/ubuntu bionic InRelease
Hit:23 http://ppa.launchpad.net/ubuntuhandbook1/audacity/ubuntu bionic InRelease
Hit:24 http://ppa.launchpad.net/umang/indicator-stickynotes/ubuntu bionic InRelease
Hit:25 http://ppa.launchpad.net/webupd8team/java/ubuntu bionic InRelease
Hit:26 http://ppa.launchpad.net/yg-jensge/shotwell/ubuntu bionic InRelease
Reading package lists... Done
W: GPG error: https://packages.cloud.google.com/apt cloud-sdk InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY FEEA9169307EA071 NO_PUBKEY 8B57C5C2836F4BEB
E: The repository 'https://packages.cloud.google.com/apt cloud-sdk InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
W: GPG error: https://download.opensuse.org/repositories/Emulators:/Wine:/Debian/xUbuntu_18.04 ./ InRelease: The following signatures were invalid: EXPKEYSIG DFA175A75104960E Emulators OBS Project <Emulators@build.opensuse.org>
E: The repository 'https://download.opensuse.org/repositories/Emulators:/Wine:/Debian/xUbuntu_18.04 ./ InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

I tried  the following
sudo apt-get upgrade -f
sudo apt-get upgrade --fix-missing
sudo apt-get install -f
sudo apt-get clean
sudo apt autoremove && sudo apt autoclean -y

Nothing helped. I cannot open my "Update Manager" as well. It does not open. Here are some relevant outputs.
$ ls /etc/apt/sources.list.d
audio-recorder-ubuntu-ppa-bionic.list       libreoffice-ubuntu-ppa-bionic.list                          obs.list                                    teams.list                                           vlijm-ubuntu-takeabreak-bionic.list
audio-recorder-ubuntu-ppa-bionic.list.save  libreoffice-ubuntu-ppa-bionic.list.save                     obs.list.save                               teams.list.save                                      vlijm-ubuntu-takeabreak-bionic.list.save
deadsnakes-ubuntu-ppa-bionic.list           maarten-baert-ubuntu-simplescreenrecorder-bionic.list       signal-xenial.list                          teamviewer.list                                      vscode.list
deadsnakes-ubuntu-ppa-bionic.list.save      maarten-baert-ubuntu-simplescreenrecorder-bionic.list.save  signal-xenial.list.save                     teamviewer.list.save                                 vscode.list.save
google-chrome.list                          mc3man-ubuntu-trusty-media-bionic.list                      slack.list                                  ubuntuhandbook1-ubuntu-audacity-bionic.list          webupd8team-ubuntu-java-bionic.list
google-chrome.list.save                     mc3man-ubuntu-trusty-media-bionic.list.save                 slack.list.save                             ubuntuhandbook1-ubuntu-audacity-bionic.list.save     webupd8team-ubuntu-java-bionic.list.save
google-cloud-sdk.list                       nilarimogard-ubuntu-webupd8-bionic.list                     sunderme-ubuntu-texstudio-bionic.list       umang-ubuntu-indicator-stickynotes-bionic.list       yg-jensge-ubuntu-shotwell-bionic.list
google-cloud-sdk.list.save                  nilarimogard-ubuntu-webupd8-bionic.list.save                sunderme-ubuntu-texstudio-bionic.list.save  umang-ubuntu-indicator-stickynotes-bionic.list.save  yg-jensge-ubuntu-shotwell-bionic.list.save

and
$ cat /etc/apt/sources.list
deb https://qgis.org/ubuntu-ltr bionic main
# deb-src https://qgis.org/ubuntu-ltr bionic main

# deb cdrom:[Ubuntu 18.04.3 LTS _Bionic Beaver_ - Release amd64 (20190805)]/ bionic main restricted

# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://in.archive.ubuntu.com/ubuntu/ bionic main restricted
# deb-src http://in.archive.ubuntu.com/ubuntu/ bionic main restricted

## Major bug fix updates produced after the final release of the
## distribution.
deb http://in.archive.ubuntu.com/ubuntu/ bionic-updates main restricted
# deb-src http://in.archive.ubuntu.com/ubuntu/ bionic-updates main restricted

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://in.archive.ubuntu.com/ubuntu/ bionic universe
# deb-src http://in.archive.ubuntu.com/ubuntu/ bionic universe
deb http://in.archive.ubuntu.com/ubuntu/ bionic-updates universe
# deb-src http://in.archive.ubuntu.com/ubuntu/ bionic-updates universe

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://in.archive.ubuntu.com/ubuntu/ bionic multiverse
# deb-src http://in.archive.ubuntu.com/ubuntu/ bionic multiverse
deb http://in.archive.ubuntu.com/ubuntu/ bionic-updates multiverse
# deb-src http://in.archive.ubuntu.com/ubuntu/ bionic-updates multiverse

## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://in.archive.ubuntu.com/ubuntu/ bionic-backports main restricted universe multiverse
# deb-src http://in.archive.ubuntu.com/ubuntu/ bionic-backports main restricted universe multiverse

## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
# deb http://archive.canonical.com/ubuntu bionic partner
# deb-src http://archive.canonical.com/ubuntu bionic partner

deb http://security.ubuntu.com/ubuntu bionic-security main restricted
# deb-src http://security.ubuntu.com/ubuntu bionic-security main restricted
deb http://security.ubuntu.com/ubuntu bionic-security universe
# deb-src http://security.ubuntu.com/ubuntu bionic-security universe
deb http://security.ubuntu.com/ubuntu bionic-security multiverse
# deb-src http://security.ubuntu.com/ubuntu bionic-security multiverse
deb https://download.sublimetext.com/ apt/stable/
# deb-src https://download.sublimetext.com/ apt/stable/
deb http://dl.winehq.org/wine-builds/ubuntu/ bionic main
# deb-src http://dl.winehq.org/wine-builds/ubuntu/ bionic main
deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main
# deb-src [arch=amd64] https://packages.microsoft.com/repos/vscode stable main

Please help. How to update my system successfully?

A: You have to re-add GPG keys for problematic repositories by
cd /tmp
wget https://download.opensuse.org/repositories/Emulators:/Wine:/Debian/xUbuntu_18.04/Release.key
sudo apt-key add Release.key

wget https://packages.cloud.google.com/apt/doc/apt-key.gpg
sudo apt-key add apt-key.gpg

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys FEEA9169307EA071
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 8B57C5C2836F4BEB
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys DFA175A75104960E

and then run sudo apt-get update again.