text:
Q: Javascript how to format json values for pie chart DataTable I have an API that returns 100 rows of lots of different json data including HTTP Status:
{"data": [{"status": 409},{"status": 200},{"status": 404},{"status": 200},{"status": 200},{"status": 200}]}

And I want to make a pie chart which requires a DataTable like this:
['status', count],
['200', 4],
['404', 1],
['409', 1]

What is the most graceful way to accomplish this? I am somewhat familiar with vanilla Javascript but will accept Jquery or other solutions.
I would have thought there was a simple library (?) that would let me choose "status" from my json and it would automagically format it for a pie chart (any pie chart - although I'm trying Google Charts to begin) — but I have not found such a library.
What I have tried...
I made a list of things to learn how to accomplish ... assuming there is no "library" or simple way to select, count (and maybe also order from lowest to highest) the json data for the Google or other pie chatrt, Does this look like a decent plan, or is there a better way?

*

*create a new array with each "status" as an element

*from the new array, determine each unique status from the json (I Googled several ways to find unique values in an array, have not figured which one will work for me yet) as yet another new array

*using a combination of the first and second new arrays, count the number of times each status appears in the json (I think I can use each or foreach and count up +1 for each occurence of each unique status element)

*format each unique status with its count, adding brackets and commas (I think I can use join between name value pairs, so the last one does not have an extra comma, and + concatenate with commas and brackets using single quotes, maybe)

*sort the statuses low to high (this will be for color coding from green to red where 200's will be green and 500's will be red)

*add the title to each column

Thank you for any advice.

A: I believe an array.reduce loop will do the trick.

let data = {
  "data": [{
    "status": 409
  }, {
    "status": 200
  }, {
    "status": 404
  }, {
    "status": 200
  }, {
    "status": 200
  }, {
    "status": 200
  }]
}

let newdata = data.data.reduce((accum, a) => {
 // console.log(accum, a);
  let found = 0;
  accum.forEach((el, index) => {
    if (el[0] == a.status) {
      accum[index][1]++;
      found = 1
    }
  })
  if (!found) accum.push([a.status.toString(), 1])
  return accum
}, [
  ['status', 'count']
]);

console.log(newdata)


text:
Q: Sed inside an awk statement I'd like to perform a series of sed commands on lines of a file roster.txt only beginning with a keyword. For example:
Employee : Kiara 20 hours@8.25
Employee : Connor 25 hours@8.00
Employee : Dylan 30 hours@9.00

Becomes:
Employee : Kiara_20_hoursat8dot25
Employee : Connor_25_hoursat8dot00
Employee : Dylan_30_hoursat9dot00

I know the sed commands to make the changes I just wanted a way to peform them on lines starting with "employee". Maybe
awk '$1 == "Employee" {sed -i -e 's/\./dot/g' roster.txt}' roster.txt

A: $ cat roster.txt
foo : bar@baz.123
Employee : Kiara 20 hours@8.25
Employee : Connor 25 hours@8.00
Employee : Dylan 30 hours@9.00

$ awk 'BEGIN{FS=OFS=" : "} $1=="Employee"{gsub(/ /,"_",$2); gsub(/@/,"at",$2); gsub(/\./,"dot",$2)} 1' roster.txt
foo : bar@baz.123
Employee : Kiara_20_hoursat8dot25
Employee : Connor_25_hoursat8dot00
Employee : Dylan_30_hoursat9dot00

awk supports substitution commands as well - sub to replace first occurrence and gsub to replace all occurrences. Also allows to change only specific field

*

*BEGIN{FS=OFS=" : "} use  :  as input/output field separator

*gsub(/ /,"_",$2) replace all spaces with _ only for second field

*Similarly other substitutions as required

*1 at end of command is idiomatic way to print the line, includes any changes made

*See also awk save modifications in place

A: I'd write:
sed '/^Employee :/ {s/@/at/; s/\./dot/; s/ /_/3g}' <<END
Employee : Kiara 20 hours@8.25
Employee : Connor 25 hours@8.00
Employee : Dylan 30 hours@9.00
Foo : bar baz@qux.blah
END

Employee : Kiara_20_hoursat8dot25
Employee : Connor_25_hoursat8dot00
Employee : Dylan_30_hoursat9dot00
Foo : bar baz@qux.blah

Requires GNU sed for the 3g modifier of the s command

A: You really do not need to use both tools, either will do everything you need.
sed solution:
 sed -i -e 's/^Employee : \([^ ]*\) \([0-9]*\) hours@\([0-9]\)\.\([0-9]*\)/Employee : \1_\2_hoursat\3dot\4/' roster.txt

Edit after comment:
If you want a very generic replacement using only sed that works on your sample:
sed -i -e 's/\([^:]\) \([^:]\)/\1_\2/g' -e 's/@/at/g' -e 's/\./dot/g' roster.txt

redpajama_set_name: RedPajamaStackExchange


text:
Q: javascript WMI queries with firefox /chrome? goal : get the processor ID by WMI :
ive managed to make it work in IE : by
var strComputer = ".";
    var SWBemlocator = new ActiveXObject("WbemScripting.SWbemLocator");
    var objWMIService = SWBemlocator.ConnectServer(strComputer, "/root/CIMV2");
    var strProcess;
    var colItems = objWMIService.ExecQuery("select * from Win32_Processor");

    var e = new Enumerator(colItems);
    for(; ! e.atEnd(); e.moveNext())
    {
        strProcess =  e.item().ProcessorId;
    }

    alert( strProcess)

However- this wont work in FF/chrome since they not support ACTIVE X.
what is the alternative in FF / chrome ?

A: You could use NPAPI to write an extension for Google Chrome which allows you to execute native code on the client computer.
FireFox also allows for developers to write plugins and extensions.


text:
Q: Could you help me find a proper adjective?
The car park was deserted. It was empty/abandoned.

I think that both r acceptable but I have to decide one.I think abandoned is better, What about your opinions?

A: 'Empty' and 'Abandoned' have similar but not exactly the same meaning in your example sentence. An 'empty car park' is one with no or very few cars (or people) in it (at the current moment). An 'abandoned car park' implies that no or very few people use the car park, and haven't done so for a while. The abandoned car park might also be filled with broken, abandoned cars, litter, and garbage, rather than being 'empty'.


text:
Q: Pandas: Consecutive values of zero I have a data frame which looks like this
Timestamp                     Speed
2014-10-10 00:10:10            112
2014-10-10 00:10:13            34
2014-10-10 00:10:17            0
2014-10-10 00:10:20            0
2014-10-10 00:10:45            0
2014-10-10 00:10:56            3
2014-10-10 00:11:06            0
2014-10-10 00:11:09            0
2014-10-10 00:11:14            11

I want to group by consecutive values (0 in this case) and have output like
start_time              end_time               number
2014-10-10 00:10:17    2014-10-10 00:10:45     3
2014-10-10 00:11:06    2014-10-10 00:11:09     2

A: You can use a .groupby() to check whether adjacent values change (i.e., df["Speed"] != df["Speed"].shift()) and then check whether the speed in each of those blocks is 0 or not. There might be a better way to reassemble the final DataFrame, but I just threw the results into a list and reassembled it at the end.
Your table didn't read nicely with pd.read_clipboard() and so I've only got the times, but it should work the same with your real data.
In [113]: df
Out[113]:
           Speed
Timestamp
00:10:10     112
00:10:13      34
00:10:17       0
00:10:20       0
00:10:45       0
00:10:56       3
00:11:06       0
00:11:09       0
00:11:14      11

In [114]: l = []

In [115]: for k, v in df.groupby((df["Speed"] != df["Speed"].shift()).cumsum()):
     ...:     if v["Speed"].iloc[0] == 0:
     ...:         l.append({'start_time': v.index.min(), 'end_time': v.index.max(), 'number': len(v)})
     ...: pd.DataFrame(l, columns=['start_time', 'end_time', 'number'])
     ...:
Out[115]:
  start_time  end_time  number
0   00:10:17  00:10:45       3
1   00:11:06  00:11:09       2

A: Here's a non-loop implementation
s = (((df['speed'] == 0) & (df['speed'].shift(1) == 0)) | ((df['speed'] == 0) & (df['speed'].shift(-1) == 0)) ) * 1
s1 = s.diff()
group_labels = s1[s1 == 1].cumsum()
s_nan = s.replace(1, np.nan)
df_copy = df.copy()
df_copy['label'] = s_nan.combine_first(group_labels).fillna(method='ffill').replace(0, np.nan)
df_copy = df_copy.groupby('label')['timestamp'].agg({'start_time':'first', 'end_time':'last', 'number':'size'})
df_copy = df_copy[['start_time', 'end_time', 'number']].reset_index(drop=True)

df_copy

            start_time             end_time  number
0  2014-10-10 00:10:17  2014-10-10 00:10:45       3
1  2014-10-10 00:11:06  2014-10-10 00:11:09       2


text:
Q: Call class methods inline to create a new object Trying to figure out if I can pass arguments to a class without creating a new object. I tried as below
Filename: display.rb
class Print
  def initialize(name)
    @name = name
  end
  def disp
    p @name
  end
end

init = Print.new(ARGV[0])
init.disp

Terminal
> ruby display.rb "ross"
# => "ross"

[EDIT] I don't want to call init = Print.new(ARGV[0]) and init.disp in the file; instead, I want to pass it as command line argument ruby display.rb "ross", and it should display the name. How can I achieve this?

A: Add an option parser to your script and then properly instantiate the Print class from the option parser.  The option parser will handle the work of reading in the ARGV array and you can use the Print class in an OO manner as it is intended.

A: You can use the allocate method to create an object of a class.
But I think you are really asking if you can create and call a class method.
Print.disp(ARGV[0]) can definitely be done.
class Print
  def self.disp(something)
    puts something
  end
end

Print.disp(ARGV[0])

And you would call it like this:
$ ruby display.rb Ross
And it would output:
Ross

A: You could call ruby display.rb "ross" if you weren't using a class, and just running straight Ruby code. For example, let's say your file looks like this:
puts ARGV[0]

You could now run this as ruby display.rb "ross" and your argument will get printed.
Another options would be to setup your function like this:
class Print
  def self.disp(yourinput)
    puts yourinput
  end
end

Which in this case, you could then call you function directly from the class, without needing to instantiate the class. For what you are trying to achieve, this may be your best solution.
Print.disp(ARGV[0])

A: Here's an idea. Load the rb file and execute some inline ruby afterwards:
ruby -r"./display.rb" -e "Print.new('ross').disp"


text:
Q: Removing the end of line character from a read csv file I tried sever times to use strip() but I can't get it to work.
I removed that piece from this snip but every time I tried it I had
an error or it did nothing. The sort is fine I just want to strip the newline before writing to the new file?
import sys, csv, operator
data = csv.reader(open('tickets.csv'),delimiter=',')
sortedlist = sorted(data, key=operator.itemgetter(6))
# 0 specifies according to first column we want to sort

#now write the sort result into new CSV file

with open("newfiles.csv", "w") as f:
    #writablefile = csv.writer(f)
    fileWriter = csv.writer(f, delimiter=',')
    for row in sortedlist:
        #print(row)
        lst = (row)
        fileWriter.writerow(lst)

A: You need to add newline='' to your open() when writing a CSV file. This is explained in the documentation. Without it, your file can end up having a blank line per row.
import sys, csv, operator

data = csv.reader(open('tickets.csv'),delimiter=',')
header = next(data)

sortedlist = sorted(data, key=operator.itemgetter(6))
# 0 specifies according to first column we want to sort

#now write the sort result into a new CSV file
with open("newfiles.csv", "w", newline="") as f:
    fileWriter = csv.writer(f)

    fileWriter.writerow(header)     # keep the header at the top
    fileWriter.writerows(sortedlist)

Also you need to first read in the header row before loading everything for sorting. This avoids it being sorted. It can then be output separately when writing your sorted output CSV.
If your tickets.csv file contains blank lines, you would need to also remove these. For example:
    for row in sortedList:
        if row:
            fileWriter.writerow(row)


text:
Q: Faced error:Use of undefined constant TypeOfAccounting - assumed 'TypeOfAccounting Good day to all, I faced the error:Use of undefined constant TypeOfAccounting - assumed 'TypeOfAccounting in controller
Code in Controller:
 $personal= new PersonalAccounting();
        $personal->TypeOfAccounting=$request->input('TypeOfAccounting');
        $personal->Name=$request->input('Name');
        $personal->SumOfMoney=$request->input('SumOfMoney');
        $personal->user_id= auth()->user()->id;
        $user_id=auth()->user()->id;
        $user=User::find($user_id);
        if($request->input(TypeOfAccounting)=='Income'){
         $request->input('SumOfMoney')+ $user->balance;
        }
        if($request->input(TypeOfAccounting)=='Expense'){
            $request->input('SumOfMoney')-$user->balance;
        }
        $personal->save();

A: You are missing quotes for variable name so change this
You are doing mistake in 2 lines
1-if($request->input(TypeOfAccounting)=='Income')
2-if($request->input(TypeOfAccounting)=='Expense')

variables should be in quotation marks like shown below
1-if($request->input('TypeOfAccounting')=='Income')
2-if($request->input('TypeOfAccounting')=='Expense')

To sum and save in database do this:
    if($request->input(TypeOfAccounting)=='Income'){
     $user->balance = $request->input('SumOfMoney')+ $user->balance;
     //sum user input and old balance and save into balance
    }
    if($request->input(TypeOfAccounting)=='Expense'){
        $user->balance = $request->input('SumOfMoney')-$user->balance;
        //difference user input and old balance and save into balance
    }
    $user->save();
   //now save $user object to save changes in database.


text:
Q: Does symmetry of $AB$ implies symmetry of $A^\dagger B^T$ Let $A$ and $B$ not necessarily symmetric but $AB$ symmetric. Is $A^\dagger B^T$ also symmetric i.e.
\begin{equation}
A^\dagger B^T = B (A^\dagger)^T
\end{equation}
where $A^\dagger$ is the pseudo inverse of $A$?
I asked a particular case of this question when $A$ and $B$ are symmetric (Does symmetry of $AB$ implies symmetry of $A^\dagger B$?) and I am wondering if it still holds when $A$ and $B$ are non-symmetric.

A: I found a counter-example : let $A= \begin{pmatrix} 0 & 0 \\ 1 & 0 \end{pmatrix}$ and $B = \begin{pmatrix} 0 & 0 \\ 0 & 1 \end{pmatrix}$, then we have $AB = \begin{pmatrix} 0 & 0 \\ 0 & 0 \end{pmatrix}$, indeed symmetric, yet, $A^\dagger B^T = \begin{pmatrix} 0 & 1 \\ 0 & 0 \end{pmatrix}$ which is not symmetric.


text:
Q: Non-standard pub files error for loading into pdb2pqr and APBS programs I'm having some problems loading .pdb files into the APBS/Pdb2pqr programs. My pub files are generated using the FoldX suite, and apparently this is a non-standard .pdb file.
The error is mostly when translating using the pdb2pqr.
I would really appreciate any help or clues to my problem! Thank you
INFO:Checking and transforming input arguments.
INFO:Loading topology files.
INFO:Loading molecule: 001_pMHC_NLMEVMPNI.pdb
ERROR:Error parsing line: 'FoldX'
ERROR:<FoldX generated pdb file>
ERROR:Truncating remaining errors for record type:FoldX
WARNING:Warning: 001_pMHC_NLMEVMPNI.pdb is a non-standard PDB file.

ERROR:['FoldX']
INFO:Setting up molecule.
INFO:Created biomolecule object with 0 residues and 0 atoms.
INFO:Setting termini states for biomolecule chains.
INFO:Loading forcefield.
INFO:Loading hydrogen topology definitions.
CRITICAL:No biomolecule heavy atoms found and no ligand present. Unable to proceed.  You may also see this message if PDB2PQR does not have parameters for any residue in your biomolecule.
CRITICAL:Giving up.


text:
Q: Try to get a JSON from a URL I am new here and I have a problem with my code and I don't know what is wrong with it because four month ago when i created the code it worked perfectly but know I want to continue the program and my code doesn't work any more.
So the purpose of my code is to get all the information for comics book painting in Brussels which are in JSON form and are from an Api given from the open data Brussels.
My code is divided in two class one asynch task and a class that is input stream operation:
Here is the url of the api i use : https://opendata.bruxelles.be/api/v2/catalog/datasets/bruxelles_parcours_bd/records?start=0&stop=52
first here is the model class:
package com.formation.appli.brusselscomicbookpaintingtourapp.models;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * Created by Jeremyvdm on 27/10/2017.
 */

public class ComicBookPainting implements Parcelable{
    String comicsPaintingTitle = "";
    String comicsPaintingAuthor = "";
    int comicsPaintingYear = 0;
    double lat = 0.0;
    double lng = 0.0;
    String comicBookPaintingImageURL = "";

    public ComicBookPainting(){

    }

    public ComicBookPainting(String comicsPaintingTitle, String comicsPaintingAuthor, int comicsPaintingYear, double lat, double lng, String comicBookPaintingImageURL){
        this.comicsPaintingTitle = comicsPaintingTitle;
        this.comicsPaintingAuthor = comicsPaintingAuthor;
        this.comicsPaintingYear = comicsPaintingYear;
        this.lat = lat;
        this.lng = lng;
        this.comicBookPaintingImageURL = comicBookPaintingImageURL;
    }

    public String getComicsPaintingTitle() {
        return comicsPaintingTitle;
    }

    public void setComicsPaintingTitle(String comicsPaintingTitle) {
        this.comicsPaintingTitle = comicsPaintingTitle;
    }

    public String getComicsPaintingAuthor() {
        return comicsPaintingAuthor;
    }

    public void setComicsPaintingAuthor(String comicsPaintingAuthor) {
        this.comicsPaintingAuthor = comicsPaintingAuthor;
    }

    public int getComicsPaintingYear() {
        return comicsPaintingYear;
    }

    public void setComicsPaintingYear(int comicsPaintingYear) {
        this.comicsPaintingYear = comicsPaintingYear;
    }

    public double getLat() {
        return lat;
    }

    public void setLat(double lat) {
        this.lat = lat;
    }

    public double getLng() {
        return lng;
    }

    public void setLng(double lng) {
        this.lng = lng;
    }

    public String getComicBookPaintingImageURL() {
        return comicBookPaintingImageURL;
    }

    public void setComicBookPaintingImageURL(String comicBookPaintingImageURL) {
        this.comicBookPaintingImageURL = comicBookPaintingImageURL;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int i) {
        dest.writeString(comicsPaintingTitle);
        dest.writeString(comicsPaintingAuthor);
        dest.writeInt(comicsPaintingYear);
        dest.writeDouble(lat);
        dest.writeDouble(lng);
        dest.writeString(comicBookPaintingImageURL);
    }

    protected ComicBookPainting(Parcel in) {
        comicsPaintingTitle = in.readString();
        comicsPaintingAuthor = in.readString();
        comicsPaintingYear = in.readInt();
        lng = in.readDouble();
        lat = in.readDouble();
        comicBookPaintingImageURL = in.readString();
    }

    public static final Creator<ComicBookPainting> CREATOR = new Creator<ComicBookPainting>() {
        @Override
        public ComicBookPainting createFromParcel(Parcel in) {
            return new ComicBookPainting(in);
        }

        @Override
        public ComicBookPainting[] newArray(int size) {
            return new ComicBookPainting[size];
        }
    };
}

here is my Asynch task :
    package com.formation.appli.brusselscomicbookpaintingtourapp.asynch;

import android.os.AsyncTask;
import android.util.Log;

import com.formation.appli.brusselscomicbookpaintingtourapp.models.ComicBookPainting;
import com.formation.appli.brusselscomicbookpaintingtourapp.tools.InputStreamOperations;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

/**
 * Created by Jeremyvdm on 08/11/2017.
 */

public class GetTheComicBookPaintingFromJson extends AsyncTask<Integer, Void, ArrayList<ComicBookPainting>> {
    // déclaration des variables
    private ArrayList<ComicBookPainting> completeListOfComicBookPainting;
    private int debut = 0;
    private int fin = 52;

    //region Callback
    public interface GetTheComicBookPaintingFromJsonCallBack {
        void listOfComicBookPainting( ArrayList<ComicBookPainting> completeListOfComicBookPainting);
    }

    private GetTheComicBookPaintingFromJsonCallBack callback;
    public void setCallback(GetTheComicBookPaintingFromJsonCallBack callback) {
        this.callback = callback;
    }
    //endregion

    // déclaration de l'url en partie sous forme de constante
    private static final String URLBASE_PARCOURT_BD = "http://opendata.bruxelles.be/api/v2/catalog/datasets/bruxelles_parcours_bd/records?";
    private static final String URL_PARCOURT_START = "start=";
    private static final String URL_PARCOURT_STOP = "stop=";
    //initalisation du callback
    @Override
    protected void onPostExecute(ArrayList<ComicBookPainting> fresqueBDs) {
        if(callback!=null){
            callback.listOfComicBookPainting(completeListOfComicBookPainting);
        }
    }
    //récupération du parcourt sous forme de ArrayList<FresqueBD>
    @Override
    protected ArrayList<ComicBookPainting> doInBackground(Integer... integers) {
        completeListOfComicBookPainting = new ArrayList<>();
        String brusselsComicsPaintingURL = URLBASE_PARCOURT_BD + URL_PARCOURT_START + debut + "&" + URL_PARCOURT_STOP + fin;
        Log.v("TEST_URI_API",brusselsComicsPaintingURL);
        JSONObject brusselsComicsPaintingJSON = resuqestJson(brusselsComicsPaintingURL);
        JSONArray brusselsComicsPaintingJSONArray = listOfComicBookPaintingJsonArray(brusselsComicsPaintingJSON);
        completeListOfComicBookPainting = convertJsorrayTolistOfComicBookPainting(brusselsComicsPaintingJSONArray);

        return completeListOfComicBookPainting;
    }
    // Transformation du Json en fresque bd
    private ComicBookPainting convertJsonToComicBookPainting(JSONObject jsonFresqueBD) {
        String title = "";
        String author = "";
        int year = 0;
        double lon =0;
        double lat = 0;
        String imageURL = "";
        try {
            JSONObject jsonField = jsonFresqueBD.getJSONObject("record").optJSONObject("fields");
            title = jsonField.getString("personnage_s");
            author = jsonField.getString("auteur_s");
            year = Integer.parseInt(jsonField.getString("year"));
            JSONObject jsonCoordonees = jsonField.getJSONObject("coordonnees_geographiques");
            lon = jsonCoordonees.getDouble("lon");
            lat = jsonCoordonees.getDouble("lat");
            JSONObject JsonPhoto = jsonField.getJSONObject("photo");
            imageURL = JsonPhoto.getString("url");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return new ComicBookPainting(title,author,year,lat,lon,imageURL);
    }
    // transformation du json objet en json array
    public JSONArray listOfComicBookPaintingJsonArray(JSONObject jsonComicBookPaintingArray){
        JSONArray listOfComicBookPaintingJsonArray = new JSONArray();
        try {

            listOfComicBookPaintingJsonArray = jsonComicBookPaintingArray.getJSONArray("records");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return listOfComicBookPaintingJsonArray;
    }
    // Transformation du JsonArray en ArrayList<fresqueBD>
    public ArrayList<ComicBookPainting> convertJsorrayTolistOfComicBookPainting(JSONArray jsonArray){
        int lenghtParcourtJson = jsonArray.length();
        ArrayList<ComicBookPainting> completeListOfComicBookPaintings = new ArrayList<>();
        for(int i =0; i < lenghtParcourtJson;i++) {
            String comicBookPaintingUrl = null;
            try {
                comicBookPaintingUrl = jsonArray.getJSONObject(i).getJSONArray("links").getJSONObject(0).getString("href");
                URL comicBookPaintingURL = new URL(comicBookPaintingUrl);
                HttpURLConnection connection = (HttpURLConnection) comicBookPaintingURL.openConnection();
                connection.connect();
                InputStream inputStream = connection.getInputStream();
                JSONObject jsonFresqueBD = new JSONObject(InputStreamOperations.InputStreamToString(inputStream));
                ComicBookPainting comicBookPainting = convertJsonToComicBookPainting(jsonFresqueBD);
                completeListOfComicBookPaintings.add(comicBookPainting);
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return completeListOfComicBookPaintings;
    }

    public JSONObject resuqestJson(String urlString){
        JSONObject json=null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();

            InputStream inputStream = connection.getInputStream();
            String result = InputStreamOperations.InputStreamToString(inputStream);

            json = new JSONObject(result);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }finally {
            connection.disconnect();
        }

        return json;

    }
}

and here is my final class the input stream operation (I think that the problem is in this file because the buffer reader is always nul and I know that my JSON work because i use the api for my iPhone app and it work perfectly):
package com.formation.appli.bruxellesparcourbd.tools;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Jeremyvdm on 03/07/2017.
 */
//traite les String afin de les transformer en Json
public class InputStreamOperations {
    public static String InputStreamToString (InputStream in, int bufSize) {
        final StringBuilder out = new StringBuilder();
        final byte[] buffer = new byte[bufSize];
        try {
            for (int ctr; (ctr = in.read(buffer)) != -1;) {
                out.append(new String(buffer, 0, ctr));
            }
        } catch (IOException e) {
            throw new RuntimeException("Cannot convert stream to string", e);
        }
        // On retourne la chaine contenant les donnees de l'InputStream
        return out.toString();
    }

    /**
     * @param in : buffer with the php result
     * @return : the string corresponding to the buffer
     */
    public static String InputStreamToString (InputStream in) {
        // On appelle la methode precedente avec une taille de buffer par defaut
        return InputStreamToString(in, 1024);
    }

}

I don't know what is wrong with my code I have try several thing but I really need your help.
thanks in advance for your time.
Best regards
Jeremy


text:
Q: Cloning a Jquery draggable also drags its original I am creating an activity generator authoring tool. The user, using a right click menu can choose to add a number of elements to the page, and for some of them, fill them with text.
Using Jquery UI, All elements are draggable and some are resizeable. I want the user to be able to make an exact copy of an element but when I use the clone function i'm getting strange results. I can drag the original away from the clone but when I try to drag the clone, it just drags the original around and stays in its place.
Heres my code
    function addobject (element_type){
       $('#activitystage').append($("

"));
       $( "#" + counter ).multidraggable({ containment: "#activitystage",  grid: [10, 10],drag: function(event,ui){ showpositions(); }});
       $('#' + counter).contextMenu({menu: 'functionsMenu'  }, function(action, el, pos) {run(action, el);  });
       $('#' + counter).append("<textarea class=\"" + element_type + "\"></textarea>");
    }

    function run (action, el){
       switch (action){
            case "clone":
              $(el).clone(true).attr('id', 'some new id').appendTo('#activitystage');
              break;
}

A: The easiest fix for your problem i can think of is to simply use clone(false) and rebind the drag and drop event.
Try this code
var attr = { containment: "#activitystage",  grid: [10, 10],drag: function(event,ui){ showpositions(); }};

function addobject (element_type){
    $('#activitystage').append($("

"));
    $( "#" + counter ).multidraggable(attr);
    $('#' + counter).contextMenu({menu: 'functionsMenu'  }, function(action, el, pos) {run(action, el);  });
    $('#' + counter).append("<textarea class=\"" + element_type + "\"></textarea>");
}

    function run (action, el){
       switch (action){
            case "clone":
              $(el).clone(false).attr('id', 'some new id').appendTo('#activitystage').multidraggable(attr);
              break;
}


text:
Q: iOS: How do these two apps run in background? The following two apps perform tasks while put in background mode:

*

*System Status Pro

*Mobile Security Protection App
System Status Pro
The app monitors cpu usage while in background mode.
The app does not use CoreLocation or Notifications.

Mobile Security Protection App
The app send notifications when detects gyro changes i.e. you move the iPhone, also when USB cable is disconnected from the iPhone.
All of this when the app is in background.

To my knowledge, whether you have to use CoreLocation or send Push Notifications all the time in order to performs tasks from your app while in background mode.
However, these 2 options, if used out of scope, will lead to AppStore rejection.
How do they do that?
Any suggestions?

A: BGTaskScheduler is one way to perform periodic work in the background. There are definitely others; for example, audio apps can play music etc. in the background, apps can download data in the background, and so on. Read up on the BackgroundTasks framework.


text:
Q: How to implement undo/redo in Java for MVC model? I am having trouble understanding the undo/redo functions using UndoManager, and integrating it with the MVC model.
I am not sure where to put the various methods(in model, view or control)
and I am still not sure how to use the undo manager.
My control class implements UndoableEditListener
It creates:
private UndoManager manager = new UndoManager();

and in:
public void actionPerformed(ActionEvent e) {
   if (e.getActionCommand().equals("Undo")) {
      try {
          manager.undo();
      } catch (CannotUndoException ex) {
          ex.printStackTrace();
      }
   }
}

I understand up to here, but the rest I am not sure what to do. I know I will have to add more in the model and view class, but not sure where.
DO I have to have the following classes?
public class UndoAction extends AbstractAction {}

public void undoableEditHappened(UndoableEditEvent e) {

I am simply placing an integer number in a textfield, and then I want to be able to undo this.I set the number in the textfield in the view class.I want to acheive this the simplest way possible, no fancy coding! This is a minor part of my assg but I just cant get it working!!
==========================================================
Here is a more detailed description of my code, maybe it will help:
I have a model, view and control package.
Contol has:
ButtonGUIControl.java, which  implements both
    ActionListener and
    UndoableEditListener.

    final UndoManager manager = new UndoManager();

In the actionPerformed method, it calls
    if (e.getActionCommand().equals("Undo")){

             try {

                    manager.undo();
                }

and in:
    public void undoableEditHappened(UndoableEditEvent evt) {
          manager.addEdit(evt.getEdit());

}
In the View:
Grid.java , which extends JTextField will add the following, wherever it needs to display a number on the GUI:(model is simply an instance of my Model class)
    getDocument().addUndoableEditListener(new ButtonGUIControl(model));

Could it be because the UndoManager is being created in a different package? I really have no idea how to debug this anymore!!
I could post my entire code if that helps. I guess Im not sure how to integrate this with my mvc model structure.

A: Take a step back for a second.  The whole idea here is that a user will use your app and will make a series of changes to something.  A text editor is a good example.  You can insert characters and lines, delete them again, replace text with other text, scroll the text, etc.  In order to support this with MVC you have a model that holds state and a View that displays it.
Your first instinct might be to have the view directly access the model, and then refresh the view every time the user makes a change, but it's very hard to undo those changes with that implementation.  Instead, you encode every kind of change the user can make in classes that are able to perform that change and can later undo that change.
For example, an action that inserts text would be implemented by a class that knows the character offset of the insertion point and the string of characters that is to be inserted.  The perform action would insert the string at the offset and the undo action would remove the right number of characters after that insertion point.  You'd have a different class that would handle deletion, another to handle scrolling etc.
Every time the user takes some action, the view would construct one of these UndoableEdit classes and would tell the instance to run itself (redo()).  Once executed, you put that UndoableEdit at the end of a list of UndoableEdit instances that represent all of the actions the user has taken so far.  This list makes it very easy to support any sequence of undo requests, redo requests and actual edit actions (resulting in more UndoableEdit's being put on the list).
So back to your question.  If your app needs to support undo and redo, then you'll need to implement an UndoManager which simply manages the list of UndoableEdit's and performs undo and redo as necessary.  You also have to implement a whole bunch of UndoableEdits, one for each kind of thing your user will do against the UI.  As for a listener, I can't see that you really need to do that one.

A: *

*If you need only simple undo/redo, you can use UndoManager as it is, you don't need to subclass or customize it in any way.

*JTextField (more specifically its model, the Document) has some built-in support for undo, which means you don't need to write UndoableEdit implementations either, the UndoableEdit objects will be automagically created for you (actually AbstractDocument.DefaultDocumentEvent implements UndoableEdit).

*Full simple working example is here


text:
Q: Deactivate Chrome Pepper Flash (PPAPI) I am quite sure that it is not possible, but I ask anyway :
I have some issues with sounds in a flash AS2 content when the PPAPI is activated.
Turning PPAPI off solve the problem.
My question is, is there any miraculous way to desactivate PPAPI from the content with javascript ?
I can detect it (Detecting Pepper (PPAPI) Flash with Javascript) but users won't be able to follow the 3-steps desactivation procedure.
Thank for help.


text:
Q: Is the IIS LogParser still useful on 2008 R2? I have to look at the log files for IIS 7.5 on a Windows Server 2008 R2 server. I've been looking around for something that will help me with that. I've come across several websites that talk about IIS LogParser. e.g.:
http://www.iis.net/learn/troubleshoot/performance-issues/troubleshooting-iis-performance-issues-or-application-errors-using-logparser
However when I look at the system requires here http://www.microsoft.com/en-us/download/details.aspx?id=24659 it only looks Windows Server 2000, 2003 and Windows XP. Can I still use LogParser for Windows Server 2008 R2?

A: LogParser is working fine on my Windows 2008R2, just as well as it did on my Windows 2003R2.
In the end it is just an executable that reads textfiles (your logfiles), there is not much to be incompatible.
The only reason that the system requirements do not mention Windows 2008 or newer is probably because it is a very old tool. It has not been updated since April 2005.

A: Yes, still very useful in 2015.
It installs and works fine on 2008, 2008R2, 2012, 2012R2 and 2016.
The only thing to keep in mind is that it is 32bit, which means it wont run if you disable the 32bit subsystem.
You can even xcopy deploy it without running the installer.


text:
Q: WCF Timeout exception on service call I have a WCF service that is giving the following error on live
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 19/06/2012 10:39:09
Event time (UTC): 19/06/2012 09:39:09
Event ID: 501c1b630958413db7c7f746b0a467f7
Event sequence: 74336
Event occurrence: 742
Event detail code: 0

Application information:
    Application domain: /LM/W3SVC/5/ROOT-1-129844753959691296
    Trust level: Full
    Application Virtual Path: /
    Application Path: <private>
    Machine name: <private>

Process information:
    Process ID: 6112
    Process name: w3wp.exe
    Account name: IIS APPPOOL\<private>

Exception information:
    Exception type: TimeoutException
    Exception message: The HTTP request to '<private>/EndPoint.svc' has exceeded the allotted timeout of 00:01:00. The time allotted to this operation may have been a portion of a longer timeout.
   at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)

The operation has timed out
   at System.Net.HttpWebRequest.GetResponse()
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

Request information:
    Request URL: http://<private>/
    Request path: /
    User host address: <private>
    User:
    Is authenticated: False
    Authentication Type:
    Thread account name: IIS APPPOOL\<private>

Thread information:
    Thread ID: 110
    Thread account name: IIS APPPOOL\<private>
    Is impersonating: False
    Stack trace:    at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)

Custom event details:

Our site is down and I don't know what to do here.  Any ideas are most welcome.

A: Try increasing the SendTimeout and ReceiveTimeout properties in service/client configurations.
WCF Service , how to increase the timeout?


text:
Q: How to determine neighboring elements from a 1D array? I am working on a Finite element analysis code and I currently have 1D array listing the element density values like so:
x = np.ones(12) where the index is the element number 0, 1, 2, ..., 10, 11
The elements when plotted are like so:
0 - 3 - 6 - 9
1 - 4 - 7 - 10
2 - 5 - 8 - 11

I set the number of elements in the x and y direction (for this case 4 in the x and 3 in the y) however am having difficulty determining the surround elements. I need to find a way to determine the 3, 5 or 8 elements which surround a given elements. For example, if I select element 0 the surrounding elements are 1, 3, 4 or if I select element 6 the surrounding elements are 3, 4, 7, 9, 10 or if if I select element 7 the surround elements are 3, 4, 5, 6, 8, 9, 10, 11...
The end goal here would be to put in a radius and based on it determine the element numbers surrounding a selected element. Any advice or help with this would be greatly appreciated. For some reason I am unable to determine the logic to do this in python.

A:
determine the logic to do this

*

*A 1-d array with 6 items has the indices - [0,1,2,3,4,5]

*A proposed shape is 2 rows and 3 columns - M,N = 2,3.

*for any item's index (i) its row and column are c,r = divmod(i,M)

*The neighbor column,row indices will be

*

*
cplus,cminus = c + 1, c - 1
rplus, rminus = r + 1, r - 1
cplus,r
cminus,r
c,rplus
c,rminus
cplus,rplus
cplus,rminus
cminus,rplus
cminus,rminus

*those 2d indices need to be converted to 1d indices with (col * M) + row
For example
[0,1,2,3,4,5]
M,N = 2,3
'''
0  2  4
1  3  5
'''

*

*item 4's 2d index is c,r = divmod(4,M) --> (2,0) (col,row)

*one of its neighbor's 2d index is c,rplus --> (2,1)

*that neighbor's 1d index is (2 * M) + 1 --> 5

*after converting the neighbors' 2d indices to 1d you will need to check for and discard some that don't make sense.

*

*item 4 is in the top-right a corner and doesn't have some neighbors like c,rminus which would be (2,-1) which does not make sense. Or cplus,r ... (3,0) which also does not make sense.

Caveat - I did NOT try to thoroughly test this.

Here is a function that returns a callable.
import operator
def get_neighbors(index, shape=(M,N)):
    '''Returns a callable.

    (M,N) --> (number_of_rows, number_of_columns)
    '''
    M, N = shape
    # 2d index
    c, r = divmod(index, M)
    print(f'2d index: {(c,r)}')
    # neighbors
    cplus, cminus = c + 1, c - 1
    rplus, rminus = r + 1, r - 1
    # dot product of (c,cplus,cminus) and (r,rplus,rminus)?
    neighbors = [
        (cminus, rminus),
        (cminus, r),
        (cminus, rplus),
        (c, rplus),
        (cplus, rplus),
        (cplus, r),
        (cplus, rminus),
        (c, rminus),
    ]
    # print(neighbors)

    # validate/filter
    neighbors = [
        (col, row) for col, row in neighbors if (0 <= col < N) and (0 <= row < M)
    ]
    # print(neighbors)

    # 1d indices
    one_d = [(col * M) + row for col,row in neighbors]
    # print(one_d)
    return operator.itemgetter(*one_d)

Try it out.
>>> a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't']

>>> M,N = 4,5    # nrows, ncols

'''
[['a' 'e' 'i' 'm' 'q']
 ['b' 'f' 'j' 'n' 'r']
 ['c' 'g' 'k' 'o' 's']
 ['d' 'h' 'l' 'p' 't']]
'''

>>> # i's neighbors
>>> q = get_neighbors(a.index('i'),(M,N))
2d index: (2, 0)
>>> q(a)
('e', 'f', 'j', 'n', 'm')
>>>
>>> # k's neighbors
>>> q = get_neighbors(a.index('k'),(M,N))
2d index: (2, 2)
>>> q(a)
('f', 'g', 'h', 'l', 'p', 'o', 'n', 'j')
>>>
>>> # q's neighbors
>>> q = get_neighbors(a.index('q'),(M,N))
2d index: (4, 0)
>>> q(a)
('m', 'n', 'r')
>>>

i's neighbors for different shapes
>>> M,N = 5,4
>>> q = get_neighbors(a.index('i'),(M,N))
2d index: (1, 3)
>>> q(a)
('c', 'd', 'e', 'j', 'o', 'n', 'm', 'h')
>>> M,N = 10,2
>>> q = get_neighbors(a.index('i'),(M,N))
2d index: (0, 8)
>>> q(a)
('j', 't', 's', 'r', 'h')
>>> M,N = 2,10
>>> q = get_neighbors(a.index('i'),(M,N))
2d index: (4, 0)
>>> q(a)
('g', 'h', 'j', 'l', 'k')
>>>

There is a nice discussion in the Numpy docs about making/treating a 1d thing as a Nd thing - Internal memory layout of an ndarray
The way you depicted your 1d --> 2d transformation used a column major scheme. I'm used to thinking row-major - I wrote the function to accept/expect a (nrows,ncols) shape argument but inside the function I kinda switched to column major processing. I was having to be careful so maybe that was a bad design.


text:
Q: Detecting is a user is an administrator (or any type) per page, asp.net mvc default membership provider I'm building a web application, and I would like to make certain functions on the front end visible when a user is logged in as an administrator.
I am using the default membership provider, but I have an extension table called userFields which i use for storing user settings.
I have just added a UserType field to this table, and am now considering how will be best to pick this up on the pages.
I don't really want to have to add extra code to each controller method to get this information out of the db, and pass it through.
Is there a better way to do this, either using the built in roles settings in asp.net membership, OR is there a cool way I can expose this information from my db, in the same way user.identity.name works or (User.Identity.Name).ProviderUserKey;

A: Use the asp.net roles - then you can use authorization attributes on your controllers to ensure that the user has the relevant roles set.
See this question.
This solves the problem of only allowing certain actions/controllers to be accessible to certain users.
It doesn't solve the problem of only making certain features 'visible'.  To do that you will need to either create different views (or partial views) and your controller(s) chooses which view to render based on roles - or you write role specific logic directly into your view.
Of course if you store flags for users in a separate table you can do all this based on your own data.  Write your own authorization attribute (i.e. an authorization filter),  and use your own data to drive views - just pass it to the view as part of the view data - just like any other part of the model.
You say you don't want to write code to pass the data through your controller to the view - but this is kind of what controllers are for - it's the reason they exist.  You could write a static method - or a service of some type that access the DB directly from the view, bypassing the controller, but then you might as well just go back to webforms.

A: As long as you are using the standard authentication method that places the user object in the context it shouldn't be too hard.  In your view, use Html.RenderPartial and the appropriate controller to accomplish what you want like this...
/Home/Index View:

Page 1

Page 2

<% Html.RenderPartial("/Home/AdminView"); %>

/Home/Admin View:

Admin 1

Admin 2

/Shared/Empty View:

/Home Controller:
public ActionResult AdminView()
{
  //Check if user is admin
  //This should be your own logic... I usually have a few static methods that the
  //Users or User object has to assist with checking
  if (Models.User.IsAdmin(HttpContext.User.Identity.Name))
  {
    return View();
  }
  else
  {
    return View("Empty");
  }
}

That should work...  It's how I do it.  If it's wrong, hopefully someone smarter posts a better answer so we can both learn
EDIT:
Just thought of something else...  If your user object implements IPrincipal, you could extract it from the context, cast it to your user type and have the information right in the user class...
Kind of like this
class User : IPrincipal
{
  //Implement IPrincipal stuff
  public string Role { get; set; }
}

Then the admin view logic could look like this:
public ActionResult AdminView()
{
  //Check if user is admin
  //This should be your own logic... I usually have a few static methods that the
  //Users or User object has to assist with checking
  if ( ((Model.User)HttpContext.User).Role =="Admin" )
  {
    return View();
  }
  else
  {
    return View("Empty");
  }
}


text:
Q: Does matrix multiplication of a random vector preserve independence? Let $\boldsymbol{X},\boldsymbol{Y} \in \mathbb{R}^n$ be random vectors and let $\boldsymbol{A} \in \mathbb{R}^{m \times n}$ be a non-square matrix of constants i.e. m < n. Suppose that each element of $\boldsymbol{X}$ is known to be independent of each element of the vector $\boldsymbol{Y}$. Are the elements of the vector $\boldsymbol{X}^* = \boldsymbol{A}\boldsymbol{X}$ also independent of the elements of $\boldsymbol{Y}$?

A: Since $\mathbf{A}$ is constant, then $\mathbf{X}^*=\mathbf{A X}$ is a function of $\mathbf{X}$. So this follows from the general result that functions of independent random variables are independent. So, the answer is yes, without further conditions on the matrix $\mathbf{A}$ (such as rank restrictions).
As to your further information in comment: The only important fact about the matrix $\mathbf{A}$ is that it is non-random. Square or rectangular plays no role at all.


text:
Q: Loss of numerical keypad to enter alarm times For a while within the past year, I was delighted to find that my iPhone allowed me to enter an alarm time using a numerical keypad instead of the simulated dials.  Now, it has reverted to the dials.  I wonder whether it is because I recently upgraded from iOS 14.4 to 15.2.1.
Was this in fact determined by the iOS version?
I'm a fan of installing as few apps as possible, and relying on native functionality.  Is there any way to get the numerical keypad back without installing an app?

A: No - the interface has changed, though.
Thanks to AVelj's comment, I found that if I tap directly on the number that is selected by the dial picker, I get a number pad.  I can then enter (say) 900 and get a 9am alarm.


text:
Q: grid lines on bar chart V3 chart js Need gridlines on the bar chart , chart js  V3.
I tried many grid options nothing seems to be working , by default the grid lines seems to be going next to the bar chart and not on it.

A: I finally figured it out , I'm gonna leave .

 let options = {
            plugins: {
                  scales: {
                          x: {
                              offset: true,
                              grid: {
                                   offset: false
                                     }
                             }
                         }
                     }
                 }


text:
Q: Wix Check if Application Initialization is installed on 2008R2 I need to check if Application Initialization is installed on a 2008R2 Server.
The app is not installed as a feature, it is an IIS Module that I downloaded from the following link.
The problem I'm having is where does the folders actually get placed to be able to perform a search in my WiX project to see if they exist or not.

A: TLDR:
Look for the Version value in HKLM\SOFTWARE\Microsoft\IIS Extensions\Application Initilaization. Current version is 7.1.1636.0.
Full answer:
Since this is a MSI installation package, you can open it using Orca and search for any registry key being created.
Then in Orca, you open the Registry table and find the
row with Registry=reg8BD5741527F144C70BDB7B0134BC7B84. In it, you will find the Key where the value will be created, the Name of it and the Value.
This way, you  can easily perform a registry search and evaluate if the module is installed.
EDIT
To perform a search during launch and verify if the module is installed, add the following code:
<Property Id="MODULEINSTALLED">
    <RegistrySearch Id="IsModuleInstalled"
                    Root="HKLM"
                    Key="SOFTWARE\Microsoft\IIS Extensions\Application Initilaization"
             Name="Version"
                    Type="raw" />
</Property>

Then use the property in a condition:
<Condition Message="This application requires Application Initialization module. Please install the Application Initialization module then run this installer again.">
    <![CDATA[Installed OR MODULEINSTALLED]]>
</Condition>


text:
Q: Practical High Current Transistor Connections I'm designing a power supply with n+1 redundancy implemented with MOSFETs and an OR-ing FET controller.  The power supplies are each rated for 35.7A output at 28V (TDK-Lambda CPFE1000FI28) and parallel operation behind diodes for redundancy is explicitly supported - so far so good.  Does anyone have any practical tips for making the high current connection to the MOSFET?  I'll add that the MOSFET hasn't been chosen yet.  A monster like an IXFN360N10T in a SOT-227 package is obviously the easiest but the gate capacitance is about an order of magnitude more than the FET controller recommends.  Right now, I'm looking at something like a SUM50020EL on a 3 oz board with ~550 mil traces but was wondering if there's another solution I'm overlooking.

A: Current sharing on redundant DCDC converters requires accurate voltage matching and accurate current detection with share splitting communication between the supplies.  Diode Or SHARING often requires a preload of 5% to 10% to achieve stability with no loads from my experience as resonance can occur from each driver sharing the same current sense see each other's current pump as a disturbance.
Another way to achieve redundancy is by multi-phase drivers that operate in parallel , not by splitting the load but by enabling parallel drivers on load demand.
Such an example is https://www.powersystemsdesign.com/articles/multiphase-dcdc-converters/39/4250


text:
Q: Disk full on Synology NAS, can't connect I accidentally filled the entire disk on my Synology DS218 NAS. Normally I would try to delete files, and I can reach it via AFP but I have the recycling bin turned on, so any file I can delete just gets moved there, it does not actually get deleted from the machine.
I cannot connect to it on ports 22 or 5000, the normal ways I would connect to it.
Do you have suggestions for how I can get into the device to clear some disk space and restore normal operation?

A: *

*Restart you NAS

*Before Synology "Turn On beep" ssh to device

*df -h to get drives

*Found out drive with use > 99% (probably it is /dev/md0 if deletion of files from volume1 does not help)

*navigate to / (root dir)

*sudo du -hs * list biggest directories/files

*Delete file that is causing the problem(in my case this was a video file that I tried to copy to USB drive before)

A: You should be able to get into the machine even if the disk is full. In my case the default settings were trying to bind to an unexpected IP address. The Synology Assistant app helped me reset the device's settings to an IP address in the DHCP range, which allowed me to connect to it again.


text:
Q: Java HTTP post using HTTPS Confusion - javax.net.ssl.SSLException: hostname in certificate didn't match I'm sending an https POST on some url using Apache HttpClient.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost);

And I get:
javax.net.ssl.SSLException: hostname in certificate didn't match: <*.*.*.*> != <*.url

Now after searching, I found the solution on stackoverflow:
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
HttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

And the POST is succesfully done.
But I don't understand what's happening here! Is my connection still secure?
Is this the right solution? If not, what's the best solution?

A: If you're not verifying the host name, you're simply not checking that you're talking to the entity you intended to talk to: it could be a MITM instead. It's the same issue as disabling VERIFYHOST with Curl, for example. You may also be interested in this question on Security.SE.
Regarding your initial problem, the host name (or IP address) in the certificate needs to match the host name you intended to contact, that is, the one in the URL.
If you're using an IP address, that IP address needs to be in the Subject Alternative Name of the certificate. (See this question.)
In general, it's easier to use names rather than IP addresses, even on a LAN.
EDIT: Considering you're using Apache Http Client 4.0.2, the release notes for 4.0.3 say:

This is an emergency release fixing a critical regression in the SSL
  connection management code. HttpClient 4.0.2 release included an
  improved  support for multihome hosts, which unfortunately had a bug
  causing the default  SSL hostname verification logic to fail. An
  attempt to establish an SSL  connection with HttpClient 4.0.2 can
  result in javax.net.ssl.SSLException:  "hostname in certificate didn't
  match ..." error.

A: Important - if you are allowing all hosts (that is, disabling host name verification), then it is certainly NOT safe. You shouldn't be doing this in production.
I think you are probably using self-signed certificates which may be the root cause of this exception. If yes, create a certificate with host as localhost (or your IP) and then try. On production, just enable host name verification and your code would run fine.


text:
Q: WCF DataContract DataMember as simpleType in XSD? Using WCF and DataContract serializer, how can I represent a data member to reflect as a simpleType when viewing the XSD. For example:
[DataContract(Namespace="http://mydomain.xyz/example")]
public class MyType
{
 [DataMember(IsRequired=true)]
 public SomeBasicDataType basicAttribute { get; set; }

 [DataMember(IsRequired=true)]
 public SomeComplexType complexElement { get; set; }
}

Basically, I want someBasicDataType to be <xs:simpleType name="SomeBasicDataType "> in the the accompanying XSD instead of <xs:complexType name="SomeBasicDataType">

A: XSD does not allow simple types to contain either elements or attributes defined elsewhere in the schema.
Simple types are created by deriving them from existing simple types (built-in data types and other derived simple types)
Simple types are usually derived by restriction, but can also be derived by list or union.


text:
Q: How can I call an api endpoint using a public certificate using lambda function java I Have a aws lambda function built in java.
When i try to call one api endpoint i get this error:
"PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target".
I tried to import the public certificate CRT but not worked:
 - echo "Install My certificates"
      - aws s3 cp s3://myrepositoria/mycacert.crt
      - cp mycacert.crt  /usr/local/share/ca-certificates/mycacert.crt
      - ls /usr/local/share/ca-certificates/
      - keytool -import -noprompt -trustcacerts -keystore $JAVA_HOME/jre/lib/security/cacerts -alias mycacert -file /usr/local/share/ca-certificates/mycacert.crt -storepass changeit
      - update-ca-certificates
      - apt-get install jq

But I get error when I call an api endpoint.

A: There are multiple errors in your command.  First is that you can only write to /tmp in an AWS Lambda by default.  So start with:
- echo "Install My certificates"
  - aws s3 cp s3://myrepositoria/mycacert.crt /tmp/mycacert.crt

Then, following this answer, you'll need to change your code to use the certificate store in /tmp instead of the default.  Note that a quick check to see if your custom store is there could be an optimization in case of a warm Lambda start.
Lastly, you're not on Ubuntu/Debian.  apt-get will not work.  To install jq, instead run yum install jq


text:
Q: Silverlight Localhost on Xampp I am trying to retrive data to my SL application from PHP, MySQL service which is hosted locally on Xampp.
I can see my php file running OK and deliver results via JSON  (http://localhost/silverlight/data.php) but SL cannot receive it. I belive it has something to do with correct URl path but I cant figure it out. Also I've putted clientaccesspolicy.xml file to allow cross-domain access but with no avail:(
 public partial class MainPage : UserControl
{
    WebClient wc = new WebClient();
    ObservableCollection<ToDoItem> myToDoList = new ObservableCollection<ToDoItem>();
    string baseURI = "http://localhost/silverlight/";

    public MainPage()
    {
        InitializeComponent();
        wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
        wc.DownloadStringAsync(new Uri(baseURI + "data.php",UriKind.Absolute));
    }

    void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {

        if (e.Error == null && e.Result!= "")
        { JsonValue completeResult = JsonPrimitive.Parse(e.Result);
            string resultType = completeResult["returnType"].ToString().Replace("'", "").Trim();}

A: The clientaccesspolicy.xml file you use only allows cross-domain access for web service requests (as specified by http-request-headers="SOAPAction")
For WebClient to work the way you use it, you need to enable content requests as well.
Try specifying http-request-headers="*" or http-request-headers="SOAPAction,Content-Type".
Also, do check that the clientaccesspolicy.xml file is located at the root of the host, i.e. http://localhost/clientaccesspolicy.xml. Eventually when you decide to deploy your application, you'll have to make sure the file is placed in the root of the deployment host as well, e.g. http://example.org/clientaccesspolicy.xml


text:
Q: Using *ngFor to display string values from array I have an array which is created from splitting a string using str.split() and this creates an array and it looks like this:
var array = [
  "TEXT1,1234,4321,9876",
  "TEXT2,2345,5432",
  "TEXT3,6543,3456"
]

I want to be able to display this information in a table using *ngFor.
I have tried this (from this question):

    {{info.join(",")}}

But I get this error:
ERROR TypeError: _v.context.$implicit.join is not a function
    at Object.eval [as updateRenderer]

The table should look like this:
TITLE | VALUE1 | VALUE2 | VALUE3
--------------------------------
TEXT1 | 1234   | 4321   | 9876
--------------------------------
TEXT2 | 2345   | 5432   |
--------------------------------
TEXT3 | 6543   | 3456   |

How do I achieve this table?

A: To make array from string with , delimiters use String.prototype.split method

  {{info}}

Ng-run Example

A: You will need two *ngFors. One to loop through each item in the array and one to iterate through each item in the array that you'll create by splitting the string with ,
Give this a try:

      TITLE
      VALUE 1
      VALUE 2
      VALUE 3

        {{ column }}

Here's a Working Sample StackBlitz for your ref.


text:
Q: Calculate calendar days Rails where start time is 09:00 AM I appreciate your help with the following:
I am active in the rental industries. The idea is that a customer pays for the amount of calendar days, whereby the calendar day should be from 09:01 AM to 09:00 AM the next day.
Note that a customer can select a pickup date and pickup time from the datetimepicker.
To calculate the number of calendar days, i use the following variable.
"num_of_calendar_days = ((return_date.end_of_day - pickup_date.beginning_of_day)/ 86400).to_i + 1"

Obviously, this is not a great solution as the day is now starting at 00:00 until 23:59.
Can you help me out with the code to fix this? Some way to add 9 hours to the beginning and the end of the day helper?
Thanks in advance.

A: A possible solution will be to set the time of the pickup date to 09:01 AM and then set the return date's time to the actual return time. We can then simply subtract the datetimes to get the actual days and add one extra day to accommodate for the pickup day.
    pickup_time = "09:01" # should be set to start of business day + 1 minute
    return_time = "10:00"

    pickup_time_parts = pickup_time.split(":")
    return_time_parts = return_time.split(":")

    pickup_date = "07-11-2020".to_datetime.change(hour: pickup_time_parts[0].to_i, min: pickup_time_parts[1].to_i)
    return_date = "08-11-2020".to_datetime.change(hour: return_time_parts[0].to_i, min: return_time_parts[1].to_i)

    num_of_calendar_days = (return_date - pickup_date).to_i + 1

    # print out the result here
    puts "Number of Calendar Days: " + num_of_calendar_days.to_s


text:
Q: How to trigger click event when I apply checked to a radio button? I have an uninitialized property in app.component.ts:
color!:string;

I want color to be automatically initialized when I set checked to a radio button:
<div>
  <input type="radio" name="colors" (click)="color='red'" checked>Red
  <input type="radio" name="colors" (click)="color='blue'">Blue
  <input type="radio" name="colors" (click)="color='green'">Green
</div>

Unfortunately, checked does not trigger the click event so color is still uninitialized.  Any idea to solve it?

A: Use input():
<input type="radio" name="colors" value="red" (input)="onInput($event)">Red
<input type="radio" name="colors" value="blue" (input)="onInput($event)">Blue
<input type="radio" name="colors" value="green" (input)="onInput($event)">Green

onInput(event: Event) {
  this.color = event.target.value;
}

Or you can use ngModel:
<input type="radio" name="colors" value="red" [(ngModel)]="color">


text:
Q: Django: Bootstrap input group not rendering desired HTML/CSS with form I'm relatively new to Django and having an issue with rendering a form as an input group in Bootstrap. The form is to add a message to a model for a chat.
Here is what I am aiming for as an input group: Expected input group
This can be achieved with the below HTML:

    <textarea name="" class="form-control type_msg" placeholder="Type your message..."></textarea>

Now using Django to include the form within the input group I am using the below:

    <form method="post" action=".">
        {% csrf_token %}
        {{ form.content }}

            <button class="send_btn" type="submit"></button>

    </form>

This is using the below forms.py:
class JobMessageForm(ModelForm):
content = forms.CharField(required=True, widget=forms.Textarea(attrs={
    'class': 'form-control type_msg',
    'placeholder': 'Type your message...'}), label=False)

class Meta:
    model = JobMessage
    fields = ('content',)

This is giving me the below: Current input group
Any help in achieving the expected output would be greatly appreciated! Let me know if any further info would help.

A: Turns out the answer was to simply make the form itself an input group:
<form class="input-group" method="post" action=".">

    {% csrf_token %}
    {{ form.content }}

        <button class="send_btn" type="submit"></button>

</form>


text:
Q: invalid hook call with nextjs inside custom hook I'm getting a invalid hook call error when using state inside my custom hook. Here's my code
import { useState } from 'react';

export default function useFetch() {
  const [randomValue, setRandomValue] = useState<number>();
  setRandomValue(3);

  return randomValue;
}

the hook is inside my hooks folder on the path: ./src/hooks
any reason for that?

A: Your comment mentions you call useFetch() from inside useEffect(). That's where your problem is.
Hooks are only valid when called during render of a component. useEffect() is triggered after a render. So you cannot call any hook from inside useEffect.
It's hard to advise how to fix that since you haven't posted that code.

Also, and this is equally important, never call a state setter function during render. And remember that hook functions run when the component renders. Setting state triggers a render, so this typically results in an infinite loop.
Most of time when fetching a value and setting it in state, you should have a valid initial value for its type (like null), and a useEffect() to set something you want.
Remember that useEffect means "use side effect" where a side effect is something that a render may trigger, but is not executed synchronously every single render.
export default function useFetch() {
  const [randomValue, setRandomValue] = useState<number | null>(null);

  useEffect(() => {
    setRandomValue(Math.floor(Math.random() * 10));
  }, [setRandomValue]}

  return randomValue;
}


text:
Q: Add-Content for each line in a CSV using PowerShell I'm creating a simple script to pull a chrome extension from a user's file path, search the chrome app store for the name of the extension, and enter it into the csv:
# Open file
$file = Import-Csv 'filepath'

# Loop through each line of CSV
foreach ($line in $file)
{
    # Assign file path, and regex just the extension
    $path = $line.path
    $extension = $path -replace '.*\\Extensions\\'

    # Open chrome webstore for specific extension
    $result = Invoke-webrequest -Uri "https://chrome.google.com/webstore/detail/$extension" -Method Get
    $resultTable = @{}

    # Grab title of extension and place in CSV
    $title = $result.ParsedHtml.title
    Add-Content -Path 'filepath' -Value "$path,$extension,$title"

    # Create table and return as an object
    $resultTable.$extension = $title
    Write-Output $resultTable
}

Doing this works fine, but appends the results to the bottom of the table instead of in it's neighbouring column, as shown:

How would I go about simply placing the output into the fields beside, instead of adding to the bottom?
Any help would be much appreciated, and thank you in advance.
EDIT: To make things a little clearer.
The file originally looks like this:

My desired output would be to have the extension, and title in the same row, but neighbouring columns, as such:

A: Since you are using Import-Csv to read your file, which I assume is a proper CSV, you can use Export-Csv to output custom objects.
# Open file
$file = Import-Csv 'filepath'

# Loop through each line of CSV
# store results in $resultTable
$resultTable = foreach ($line in $file)
{
    # Assign file path, and regex just the extension
    $path = $line.path
    $extension = $path -replace '.*\\Extensions\\'

    # Open chrome webstore for specific extension
    $result = Invoke-WebRequest -Uri "https://chrome.google.com/webstore/detail/$extension" -Method Get

    # Grab title of extension and place in CSV
    $title = $result.ParsedHtml.title

    # Create and output custom object with path,extension,title properties
    [pscustomobject]@{
        Path = $path
        Extension = $extension
        Title = $title
    }
}
# Export to CSV overwriting 'filepath'
$resultTable | Export-Csv 'filepath' -NoType

Export-Csv converts an input object into a CSV. Each property of the object becomes a column and each property value is output under those respective columns. Each object becomes its own row in the case of an array of objects.

A: Instead of writing the file directly, you can construct each row with [PSCustomObject]'s and then export with Export-Csv
Import-Csv 'filepath' | ForEach-Object {
    $extension = $_.path -replace '.*\\Extensions\\'
    $result = Invoke-webrequest -Uri "https://chrome.google.com/webstore/detail/$extension" -Method Get
    $title = $result.ParsedHtml.title
    [PSCustomObject]@{
        Path      = $_.path
        Extension = $extension
        Title     = $title
    }
} | Export-Csv 'filepath' -NoTypeInformation

You could also do it all with calculated properties.
$SelectProps = @(
    "Path",
    @{n="Extension";e={$_.path -replace '.*\\Extensions\\'}},
    @{n="Title";e={(Invoke-webrequest -Uri "https://chrome.google.com/webstore/detail/$($_.path -replace '.*\\Extensions\\')" -Method Get).ParsedHtml.title}}
)

Import-Csv 'filepath' |
    Select-Object $SelectProps |
        Export-Csv 'filepath' -NoTypeInformation


text:
Q: How to execute command for go group character in codemirror? I am trying to execute the command goGroupLeftCtrl in codemirror and it is not working,
Other commands like goLineUp is working.
editor.execCommand('goGroupLeftCtrl');

The cursor should move to left of the word. Do I need any special addons?
Thank you

A: I finally managed to solve the problem by using a different technique. Instead of using execCommand, I used keydown functionality with ctrlKey


text:
Q: Please explain, simply, dir /b > dirlist.txt with powershell Actually learned how to obtain a directory list by looking here. Now that I've updated Windows 10 on my PC laptop, all I find is something called Powershell. There is no command prompt anymore and I have tried to click the "turn off" button for replacing cmd with powershell, but no luck. Well, there is in the Windows-start-right-click, but it opens the command prompt for the computer and I don't know how to get it to identify the folder I need contents to. I am NOT a computer geek. I do NOT understand computer language. I know just enough to get myself in trouble.
Could someone PLEASE tell me how to get a directory list, with or without subdirectories) of any given file folder?
I used to highlight the folder, shift+rightclick, open command prompt and simply "dir /b > dirlist.txt" and the txt file would pop into the folder. I would open it and copy/paste into whatever format I needed. (usually excel or Google sheet) I cannot figure out what to do now.
Again, if you can tell me how to get from users\owner> to, say my "music" folder or any other folder, in this case "01 waw ct" or whatever and then the directory, I'd be good to go. What I really need to someone to please walk me through this. Hold my hand.

A: The direct equivalent of that command in PowerShell would be dir -n > dirlist.txt.
The long (canonical) form of the command is Get-ChildItem -Name > dirlist.txt.
If you want to include subdirectories, that's dir -n -r > dirlist.txt and Get-ChildItem -Name -Recurse > dirlist.txt respectively.

dir in PowerShell is simply another name for Get-ChildItem, but unfortunately has different option names (-n vs /b) compared to cmd's dir command of the same name.

A: Do you see that menu option, "Open Power_S_hell window here"?  Well, you can select that, and get one of those blue-windowed PowerShell windows.
Then, instead of running:

dir /b optional-target > output.txt

You can run this:

cmd
dir /b optional-target > output.txt
exit

Yes, the process is longer.  That's the downside.  The upsides are that it's an easy workaround, and this process lets you do the same things, in the same way, that you did with the traditional DOS-like command prompt.  (Also, having PowreShell run CMD is a technique that ought to work on basically any Windows 10 computer, not just the ones where you've taken the time to re-add a desirable menu option to a context menu.)
When you run "cmd", you'll notice the command prompt will stop saying "PS " at the start of your prompt.  That is how you can tell that the computer is ready to accept the traditional-style syntax.  Since your command prompt will technically be using CMD, you won't have Powershell trying to insist on you using new parameters/options, and you won't need to worry about PowerShell doing screwy stuff with unescaped commas and quotation marks (until you run the first exit command, which leaves CMD and goes back to PowerShell).


text:
Q: Yahoo Fantasy Sports example using OAuth2 I'd like to build an application to query the data in my Yahoo! Fantasy league but can't make it past the 3-legged OAuth authentication and was hoping someone could give me a quick demo, or point me to a relevant tutorial.
I'm willing to use NodeJS, Python or PHP.
I've registered an API and gotten a Consumer Key and Consumer Secret.
Their documentation contains two PHP examples (that I couldn't get to work) and references OAuth.net's list of libaries.
But let's take Python. The rauth documentation only lists
the first leg, how am I supposed to complete the other 2 legs?
from rauth import OAuth2Service

yahoo = OAuth2Service(
client_id='mykey',
client_secret='mysecret',
name='yahoo',
authorize_url='https://api.login.yahoo.com/oauth/v2/request_auth',
access_token_url='https://api.login.yahoo.com/oauth/v2/get_token',
base_url='https://api.login.yahoo.com/oauth/v2/')

url = yahoo.get_authorize_url()

Almost all of the examples I found on GitHub.com are years old and have compatibility problems, although yahoofantasysandbox seemed almost there.
This tutorial recommens using fantasy-sports but I didn't see a lot of details on implementation or examples.
Can someone either point me in the right direction on this or give me a demo of working code?

A: One year later I've managed to do this myself.
TL;DR: If you want to access the Yahoo Fantasy API just use this NodeJS tool I've created: https://github.com/edwarddistel/yahoo-fantasy-baseball-reader
If you want to create your own app in NodeJS or PHP however, here's how:

*

*Go to https://developer.yahoo.com/apps/create/, get a Consumer Key and Consumer Secret

*Put the Consumer Key into https://api.login.yahoo.com/oauth2/request_auth?client_id=YOUR-CONSUMER-KEY-GOES-HERE&redirect_uri=oob&response_type=code&language=en-us and Agree to allow access, then grab the authorization code

*Construct the Auth header, a Base64 encoding of CONSUMER_KEY:CONSUMER_SECRET:
const AUTH_HEADER = Buffer.from(`${CONSUMER_KEY}:${CONSUMER_SECRET}`, `binary`).toString(`base64`);

*Yahoo requires x-www-form-urlencoded, so if using an HTTP request library like Axios you'll need to stringify the data as per the docs

*Make a request to Yahoo. Here's an example:
function getInitialAuthorization () {
    return axios({
        url: `https://api.login.yahoo.com/oauth2/get_token`,
        method: 'post',
        headers: {
            'Authorization': `Basic ${AUTH_HEADER}`,
            'Content-Type': 'application/x-www-form-urlencoded',
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
        },
        data: qs.stringify({
            client_id: CONSUMER_KEY,
            client_secret: CONSUMER_SECRET,
            redirect_uri: 'oob',
            code: YAHOO_AUTH_CODE,
            grant_type: 'authorization_code'
        }),
        timeout: 1000,
        }).catch((err) => {
            console.error(`Error in getInitialAuthorization(): ${err}`);
        });
}

*Take that response and write it to a file. You'll need those credentials to re-authorize the app every 60 minutes of usage.

*Make normal HTTP requests to the Yahoo API. Check the response, if the authorization token has expired, re-authorize using a slightly different set of parameters:
function refreshAuthorizationToken (token) {
    return axios({
        url: `https://api.login.yahoo.com/oauth2/get_token`,
        method: 'post',
        headers: {
            'Authorization': `Basic ${AUTH_HEADER}`,
            'Content-Type': 'application/x-www-form-urlencoded',
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
        },
        data: qs.stringify({
            redirect_uri: 'oob',
            grant_type: 'refresh_token',
            refresh_token: token
        }),
        timeout: 10000,
    }).catch((err) => {
        console.error(`Error in refreshAuthorizationToken(): ${err}`);
    });
}

*An example of making an API request and checking authorization:

// Hit the Yahoo Fantasy API
async function makeAPIrequest (url) {
    let response;
    try {
        response = await axios({
        url: url,
            method: 'get',
            headers: {
                'Authorization': `Bearer ${CREDENTIALS.access_token}`,
                'Content-Type': 'application/x-www-form-urlencoded',
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
            },
            timeout: 10000,
        });
        const jsonData = JSON.parse(parser.toJson(response.data));
        return jsonData;
    } catch (err) {
        if (err.response.data && err.response.data.error && err.response.data.error.description && err.response.data.error.description.includes("token_expired")) {
            const newToken = await refreshAuthorizationToken(CREDENTIALS.refresh_token);
            if (newToken && newToken.data && newToken.data.access_token) {
                CREDENTIALS = newToken.data;
                // Just a wrapper for fs.writeFile
                writeToFile(JSON.stringify(newToken.data), AUTH_FILE, 'w');
                return makeAPIrequest(url, newToken.data.access_token, newToken.data.refresh_token);

             }
        } else {
            console.error(`Error with credentials in makeAPIrequest()/refreshAuthorizationToken(): ${err}`);
            process.exit();
        }
    }
}

Here is an example in PHP:
function getInitialAuthorizationToken() {

    $ch = curl_init();

    $post_values = [
        "client_id" => $GLOBALS['consumer_key'],
        "client_secret" => $GLOBALS['consumer_secret'],
        "redirect_uri" => "oob",
        "code" => $GLOBALS['initial_auth_code'],
        "grant_type" => "authorization_code"
    ];

    curl_setopt_array($ch, array(
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => $GLOBALS['auth_endpoint'],
        CURLOPT_POST => 1,
        CURLOPT_HTTPHEADER => array(
        'Authorization: Basic ' . $GLOBALS['auth_header'],
        'Content-Type: application/x-www-form-urlencoded',
        'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'),
        CURLOPT_POSTFIELDS => http_build_query($post_values)
    ));

    $answer = curl_exec($ch);
    if (isset($answer)) writeToFile($answer);

    if (!isset($access_token)) {
        echo "Error!";
        die;

    }
    else {
        return $token;
    }

}

Hope this helps others.


text:
Q: asp net c# code behind bind textbox to textbox Hello i have a calculations page and has many textboxes created dynamically. What i want to do is when the first textbox value changed, change the others code behind without using javascript or events. Is there any way to bind textBoxes like this.
Thnx
Ex.Code that i use
tb = new TextBox()
{
    ID = String.Format("tb_{0}_{1}_{2}_{3}", x, y, z, i),
    Width = 130,
    TextMode = TextBoxMode.Number,
    Text = ((TextBox)(Master.FindControl("ContentPlaceHolder1").FindControl(String.Format("tb_{0}_{1}_{2}", x, y, z)))).Text.ToString()
};

There is link for sample view for textboxes
http://oi61.tinypic.com/2hd8f8p.jpg

A: I suppose you would have to set AutoPostBack to true on the textbox, and handle the OnTextChanged event.  When the user changes the text of the textbox and leaves the textbox, the page should perform a postback, allowing you to handle this event.  To my knowledge, this is the closest you can get without JavaScript.
If you don't want events either.. then... this is impossible..


text:
Q: Input not cleared As the question says, for some reason my program is not flushing the input or using my variables in ways that I cannot identify at the moment. This is for a homework project that I've gone beyond what I had to do for it, now I just want the program to actually work :P
Details to make the finding easier:
The program executes flawlessly on the first run through. All throws work, only the proper values( n > 0 ) are accepted and turned into binary.
As soon as I enter my terminate input, the program goes into a loop and only asks for the terminate again like so:

When I run this program on Netbeans on my Linux Laptop, the program crashes after I input the terminate value. On Visual C++ on Windows it goes into the loop like just described.
In the code I have tried to clear every stream and initialze every variable new as the program restarts, but to no avail. I just can't see my mistake.
I believe the error to lie in either the main function:
int main( void )
{
vector<int> store;
int terminate = 1;

do
{
    int    num   =  0;
    string input = "";

    if( cin.fail() )
    {
        cin.clear();
        cin.ignore( numeric_limits<streamsize>::max(), '\n' );
    }

    cout << "Please enter a natural number." << endl;
    readLine( input, num );

    cout << "\nThank you. Number is being processed..." << endl;
    workNum( num, store );

    line;
    cout << "Go again? 0 to terminate." << endl;
    cin >> terminate // No checking yet, just want it to work!

    cin.clear();
}while( terminate );

cin.get();
return 0;
}

or in the function that reads the number:
void readLine( string &input, int &num )
{
    int buf = 1;
    stringstream ss;
    vec_sz size;

    if( ss.fail() )
 {
        ss.clear();
     ss.ignore( numeric_limits<streamsize>::max(), '\n' );
 }

    if( getline( cin, input ) )
    {
       size = input.size();
       for( int loop = 0; loop < size; ++loop )
           if( isalpha( input[loop] ) )
               throw domain_error( "Invalid Input." );

    ss << input;
    ss >> buf;

    if( buf <= 0 )
        throw domain_error( "Invalid Input." );

    num = buf;

    ss.clear();
    }
}

A: When you call cin >> terminate, it will read the value of terminate, but leave the newline following it in the input stream. Late when you call getline(cin, input), it will read up to the newline, which means it will get an empty string.
You can discard all characters up to the newline by adding this after cin >> terminate:
cin.ignore(99, '\n');

Or avoid mixing operator >> and getline.

A: Don't mix those >> and getline operators as interjay mentioned.
Also, if you want to clear your code, I assume it can be rewritten the folllowing way:
int main() {
   while (true) {
      std::cout << "Please enter a natural number" << std::endl;
      int num;
      std::cin >> num;

      // Exception handling here can be done easily
      // like this
      // if (!(std::cin >> num) || num < 0)
      //    throw std::domain_error("TROLOLOLO");

      std::cout << "Thank you. Number is being processed..." << std::endl;
      //workNum(num, store) here

      std::cout << "Go again? 0 to terminate." << std::endl;

      int terminate;
      std::cin >> terminate;
      if (terminate == 0) break;
   }
}


text:
Q: Extract lined table from scanned document opencv python I want to extract the information from a scanned table and store it a csv. Right now my table extraction algorithm does the following steps.

*

*Apply skew correction

*Apply a gaussian filter for denoising.

*Do a binarization using Otsu thresholding

*Do a morphological opening.

*Canny egde detection

*Do a hough transform to obtain lines of table.

*Remove duplicate lines( same lines in the range of 10 pixels)

*filter the horizontal and vertical lines using slope of line(slope should be less than +/-5 degree for horizontal and normal of verticals).

This algorithm is working fine for digital born pdfs and most of the scanned documents. But, Some of the documents have a noisy table and thus its not identifying the lines correctly.
Here is a sample image in which my algorithm fails.

These are the operations I am doing on this table.
1.Gaussian blur

2.Otsu thresholding

3.Morphological opening

4.Canny edge detection

5.filtered lines,as you can see the lines are clearly not identified
correctly.

Can anyone please suggest better method for extracting horizontal and vertical lines from this kind of less quality scans.
Thanks in advance!!

A: I found a perfect solution in this blog. https://medium.com/coinmonks/a-box-detection-algorithm-for-any-image-containing-boxes-756c15d7ed26
Here,We are doing morphological transformations using a vertical kernel to detect vetical lines and horizontal kernel to detect horizontal lines and then combining them to get all the required lines.
Vertical lines

Horizontal lines

required output

A: The problem is and always will be is that you don't have perfect lines.
One solution for this approach can be:

*

*Threshold image to grayscale as you have done.

*Now find the largest contour in the image, which will be your table.

*Now use Floodfill to separate table from the image, by choosing any point on contour to create a flooded mask,

A: The problem might be in HoughLinesTransform()
You can try using: HoughLinesTransformP()
For HoughLinesTranform() to work perfectly, the lines need to be perfect. From the image you have provided, you can see the distortion clearly which is clearly causing the method to fail.
Try dilating your image first. Image Dilation in Python.


text:
Q: "Unable to load class 'com.google.common.base.Optional'". Problems with the installation of Andorid Studio I'm new to the forum, so I hope I don't violate any rules I'm not aware of. I recently tried reinstalling Android Studio and it seemed like there was no problem. Instead every time I start a new project I get this error:
Unable to load class 'com.google.common.base.Optional'.
This is an unexpected error. Please file a bug containing the idea.log file.

that I don't know how to solve. I have tried uninstalling and reinstalling the software but the problem persists. Anyone know how to help me?

A: Hi I had the same problem as you, and I solved it by redoing the project from the beginning and connecting the graphic elements to the phone screen in the activity.xml file, or by clicking on the circles inherent to the element taken into consideration and bringing the arrows towards the screen (connecting them)


text:
Q: Interesting determinant problem how to go about computing following determinant? I tried using Gaussian elimination on some special cases and figured there might be some pattern, maybe a recurrence relation involved, but I just can't see it.
$\begin{vmatrix}
  1 & 2 & 3 & \cdots & n-1 & n \\
  2 & 3 & 4 & \cdots & n & 1 \\
  3 & 4 & 5 & \cdots & 1 & 2 \\
  \vdots  & \vdots  & \ddots & \vdots  \\
  n & 1 & 2 & \cdots & n-2 & n-1
 \end{vmatrix}$


text:
Q: Implications of Conditional Expectation Let $X,\ Y,\ Z >0\ $ random variables such that $X=YZ$ where $Y$ and $Z$ are not independent. If I have the following two relationships:
$$\mathbb{E}[X|Y=c]=\mathbb{E}[Y|Y=c]\ \mathbb{E}[Z|Y=c],\ \forall c\ge0 $$
and $$\mathbb{E}[X|Y\ge c]=\mathbb{E}[Y|Y\ge c]\ \mathbb{E}[Z|Y\ge c],\ \forall c\ge0 \label{1}$$
Does the first imply the second or vice versa or no implication is present?
For the first,
$$\begin{align}
\mathbb{E}[X|Y\ge c]&={1 \over \mathbb{P}(Y\ge c)}\int_0^{\infty}\int_c^{\infty}xf_{X|Y}f_Y\ dy\ dx\\
&={1 \over \mathbb{P}(Y\ge c)}\int_c^{\infty}\mathbb{E}[X|Y=y]f_Y\ dy\\
&={1 \over \mathbb{P}(Y\ge c)}\int_c^{\infty}\mathbb{E}[Y|Y=y]\ \mathbb{E}[Z|Y=y]f_Y\ dy\\
&\not={1 \over \mathbb{P}(Y\ge c)^2}\int_c^{\infty}\mathbb{E}[Y|Y=y]\ f_Y\ dy\ \int_c^{\infty}\mathbb{E}[Z|Y=y]f_Y\ dy\\
\end{align}$$
For the second implication I get:
$${\mathbb{P}(Y\ge c)}\int_c^{\infty}\mathbb{E}[X|Y=y]f_Y\ dy\\=\int_c^{\infty}\mathbb{E}[Y|Y=y]\ f_Y\ dy\ \int_c^{\infty}\mathbb{E}[Z|Y=y]f_Y\ dy\\$$
Which gives:
$$\int_c^{\infty}\int_c^{\infty}\mathbb{E}[X|Y=y]f_Y\ f_Y\ dy\ dl\\=\int_c^{\infty}\int_c^{\infty}\mathbb{E}[Y|Y=y]\ \mathbb{E}[Z|Y=l]f_Y\ f_Y\ dy\ dl\\$$
Which implies $\mathbb{E}[X|Y=c]=\mathbb{E}[Y|Y=c]\ \mathbb{E}[Z|Y=c],\ \forall c\ge0 $.
Is my reasoning correct?


text:
Q: Notifications inbox was pinged a second time when a comment on a followed post was edited A screenshot from my global inbox:

A post I follow had a comment added onto it which rightly pinged my notifications inbox. I then clicked through to the notification, bringing me to the comment. Within the 5-minute window, the comment was edited by its poster and I received another notification in my inbox (shown above). The comment was not changed in any way that should have affected me (no pings were edited into the comment of any sort).

I thought this was reproduced in the comments under this same post, but that seems to have been deleted or something. Regardless, attempts at reproducing it under the current answer to this question did not work so the current answer would seem to be correct; that there was only a double ping because there were actually two comments (one deleted). So this can be marked status-by-design

A: (I'm a diamond moderator on the site where that happened which how I can see these what happened)
There's actually two different comments. The comment was posted, edited, and then deleted, and reposted with additions and then edited (thus it looks like one comment that was edited).
I assume you clicked through on the first notification, thus it persists despite the comment being deleted (which IIRC is intended behaviour).
If you hover over the timestamps you should be able to see that the first notification is slightly more than 5 minutes older than the extant comment and that the second notification has the same timestamp.


text:
Q: Error Duplicate class androidx.databinding.xxxx Android Studio - Volley Cuando ejecuto Build APK, para generar mi aplicativo, estaba funcionando bien, sin ningun problema, en mi MainActivity estaba editando una funcion y cuando lo finalice, se generó ese error.

Eso fue, entonces vi en internet sobre esto y me dicen que revise mi build.gradle y el gradle-wrapper.properties pero tampoco veo algun error.
Adjunto mi build.gradle

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.prd.cocaapp"
        minSdk 21
        targetSdk 31
        versionCode 3
        versionName "1.2"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildFeatures {
        viewBinding true
    }
}

dependencies {

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
    implementation 'androidx.navigation:navigation-fragment:2.3.5'
    implementation 'androidx.navigation:navigation-ui:2.3.5'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.databinding:compilerCommon:3.2.0-alpha11'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation 'com.android.volley:volley:1.2.1'
    implementation 'com.github.bumptech.glide:glide:4.12.0'
    testImplementation 'junit:junit:4.12'
    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'me.biubiubiu.justifytext:library:1.1'
}

Adjunto mi gradle-wrapper.properties

Espero me puedan ayudar, ya recién estoy empezando en android studio

A: Tenía el mismo error, simplemente he comentado la línea de:
implementation 'androidx.databinding:compilerCommon:3.2.0-alpha11'