text:
Q: How do I insert data from my JS function into table after clicking submit? I'm trying to create a table showing results of different variables in my javascript function. I'd like the table to appear after clicking the submit button (which I've managed to do with the onclick function). However my problem is actually getting the data into the table. I am unsure how to reference the variables to specific cells in the table. I realise that this explanation might be a bit difficult to understand so I've got an example below:
I want to reference and do calculations with this information:
function myFunction() {

  var age = document.getElementById("age").value;
  var favoritenumber = document.getElementById("favoritenumber").value;
  var birthdayyear = document.getElementById("birthdayyear").checked;

  var a1 = +(age - 10);
  var fn = +(favoritenumber * 2);
  var by;
        if (document.getElementById("birthdayyear").checked) {
            by = +14;
            } else {
            by = 0;
            }

  var total = +(a1 + fn + by);

  document.getElementById("submit").innerhtml = total;
  }

And show the 'total' in a separate paragraph (say, a h1 tag) onclick of the submit button:
                                     This is the TOTAL

And the rest of the information to be inserted below into a bordered table with the following headings:
A1           FN            BY

But for example, if 'birthdayyear' is not checked, this column does not show.
How do I reference the data in myFunction to insert it into the table?
My calculations are more complicated than this but they work, it's just the referencing I need help with!
Thanks in advance for your help!

A: Check out the suite of functions associated with insertRow() here at w3schools. I think I understood your question correctly, but let me know if I didn't. Try something like this:
function myFunction() {

var age = document.getElementById("age").value;
  var favoritenumber = document.getElementById("favoritenumber").value;
  var birthdayyear = document.getElementById("birthdayyear").checked;

  var a1 = +(age - 10);
  var fn = +(favoritenumber * 2);
  var by;
  if (document.getElementById("birthdayyear").checked) {
      by = +14;
  } else {
      by = 0;
  }

  var total = +(a1 + fn + by);

  var table = document.getElementById("tableid");
  var row = table.insertRow(0);

  var cella1 = row.insertCell(0);
  var cellfn = row.insertCell(1);
  var cellby = row.insertCell(2);

  cella1.innerHTML = a1;
  cellfn.innerHTML = fn;
  cellby.innerHTML = by;

  document.getElementById("submit").innerhtml = total;
  }


text:
Q: How to fetch with axios after a post request in another view with react native? How is it possible to fetch again the posts after I submit a form in another view?
This is the button I use for submitting:
<Button icon="plus" mode="contained" text="#1ebc61" color="white" onPress={() => {
   this.addHomework()
   this.props.navigation.navigate("ViewSubject")
}}>

How is it possible to fetch again in (ViewSubject) after submitting the form?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ordering foreign keys without removing the duplicates keys I have a table called courses and courses has relation to country table
The table courses have name,country_id(FK)
A result like this

id
course_name
country_id

1
course1
1

2
course2
1

3
course3
1

4
course4
2

5
course5
2

6
course6
2

7
course7
3

8
course8
3

What I want to achieve is to order the courses based on country_id without duplicates in the same order
like this

id
course_name
country_id

1
course1
1

2
course2
2

3
course3
3

4
course4
1

5
course5
2

6
course6
3

7
course7
1

8
course8
2

How can I achieve this in eloquent?
Update2: I'm getting the courses in pagination way, so I want to get courses without duplicate the country per page

A: WITH
cte1 AS ( SELECT course_name,
                 country_id,
                 ROW_NUMBER() OVER (PARTITION BY country_id ORDER BY course_name) rn1,
                 ROW_NUMBER() OVER (ORDER BY course_name) rn2
          FROM cources ),
cte2 AS ( SELECT course_name,
                 country_id,
                 rn2,
                 ROW_NUMBER() OVER (ORDER BY rn1, course_name) rn3
          FROM cte1 )
SELECT cte1.course_name, cte2.country_id
FROM cte1
JOIN cte2 ON cte1.rn2 = cte2.rn3
ORDER BY cte1.course_name

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=8eb0d00560eebc7f4fad2cb669a79e0b

your assumes that the country_ids are sorted numbers but if they aren't dbfiddle.uk/… – nbk

This can be easily fixed by according ORDER BY adjusting in cte2:
WITH
cte1 AS ( SELECT course_name,
                 country_id,
                 ROW_NUMBER() OVER (PARTITION BY country_id ORDER BY course_name) rn1,
                 ROW_NUMBER() OVER (ORDER BY course_name) rn2
          FROM cources ),
cte2 AS ( SELECT course_name,
                 country_id,
                 rn2,
                 ROW_NUMBER() OVER (ORDER BY rn1, country_id) rn3
          FROM cte1 )
SELECT cte1.course_name, cte2.country_id
FROM cte1
JOIN cte2 ON cte1.rn2 = cte2.rn3
ORDER BY cte1.course_name

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=1ae20ca7eb414d7c049d2643a092254f


text:
Q: Ancestor query - missing events Is there any reason, why activities queried by ancestorId does not return all activities for particular file? When I use fileId to query activities, I can see all singleEvents for given file. However, when I use ancestorId to query activities, I can not find some of them.
If I change groupingStrategy from driveUi to none I can see the missing events in combinedEvents (each event has own combinedEvent), but why some of them are not included in singleEvents when using ancestor query along with driveUi, when the are present in file query with driveUi?
EDIT
Maybe these details will help to figure out where is the problem:
service user: personC, file owner: personA
activity2
2016-01-04 23:17:16, edit, personA
2016-01-04 23:14:16, edit, personA
2016-01-04 23:11:03, edit, personA
2016-01-04 23:08:03, edit, personB
2016-01-04 23:05:02, edit, personA
2016-01-04 23:02:02, edit, personB
2016-01-04 22:59:02, edit, personB
2016-01-04 22:56:02, edit, personB
2016-01-04 22:53:01, edit, personB
2016-01-04 22:47:46, edit, personA •
2016-01-04-22:44:46, edit, personA •
2016-01-04 22:41:46, edit, personA •
2016-01-04 22:38:46, edit, PersonA •
2016-01-04 22:35:47, edit, personA •
2016-01-04 22:30:32, edit, personA •
2016-01-04 22:27:32, edit, personA •
2016-01-04 22:24:32, edit, personA •

activity1
2016-01-04 22:18:29, create, personA

• missing event in ancestor query
Changing service user to personA or personB has no impact on result.

A: First of all, it's probably not the Google Drive API you are working with, but the activities API.
Activities API: https://developers.google.com/google-apps/activity/
Drive API: https://developers.google.com/drive/v3/web/about-sdk
If you take a close look at the activity parameters (https://developers.google.com/google-apps/activity/v1/reference/activities/list#parameters) you can see this:

*

*drive.ancestorId: Identifies the Drive folder containing the items for which to return activities.

*drive.fileId: Identifies the Drive item to return activities for.

Your problem seems to be that you are looking at activities on the folder vs activities on the individual file
How to solve this
If you query the folder for all files and loop through them, if you combine all the fileId's activities you will have all activities on files in a folder.


text:
Q: postgresql list all the tables that are granted select to public I was wondering in postgres how can i find tables that are granted select(read) to public?
I know in \dp is showing priviliges of specific table but is there any function that can do \dp just public?


text:
Q: Version control using timestamp I have a database DB with table T (id int, version timestamp) and  application APP that works with this database and table. What I need to do:

*

*Lock table T.

*Select some rows from table T.

*Get current time curTimeStamp.

*Unlock table T.

*All rows thar are updated after unlocking tables (#4) must have version > curTimeStamp. Their version is set in UPDATE statement using SQL functions, for example, now(), current_timestamp() etc. I mean UPDATE T SET version=now();

After reading a lot of information I think about such solution:

*

*Start SQL transaction with read committed isolation level.

*Execute SELECT statement to get rows of table T

*Execute SELECT to get curTimeStamp.

*Commit SQL transcation.

However, some RDMS, for example H2 and Posgtresql return same value of now() functions inside one transaction. And as I understand then if some update transaction started before my select transaction AND update transaction finished after select transaction then row.version will be < curTimeStamp.
I am not very good in SQL transactions and I have doubts about my solution. Is this solution correct? If not, please, show my mistakes and right direction.


text:
Q: Reseting PSN Password to access old account on PS4? I created an account, on my PS3, but then I created another account and forgot my old account's password. Now, I am trying to transfer my old account to my PS4.
I know my Online ID, and I know my Sign-In ID, but I still don't remember the password.
What else can I do to access my account  on  my PS4?

A: Try following the instructions on this page.
If I remember correctly you may need your birth date and if for some reason you didn't use your real one you can also have their support team walk you through a password reset (they won't/can't(?) tell you what your old password was, for obvious reasons).


text:
Q: How to build jar with only one Java class from large NetBeans project I am using NetBeans and have a Java project with many packages each containing many class files. None of these classes contain a main method as they are called from a larger program.
How can I build a jar file from this project with only one of those classes and include all libraries required for that class? I am currently right-clicking on the project in the "Projects" pane of NetBeans and selecting "Clean and build", which builds the entire project.
Example: build a Jar file containing only the com.andrew.overflow.questions.foo class from the following project:
> AndrewOverflow (Project)
> > com.andrew.overflow.questions (Package)
> > > Foo (Class)
> > > Bar (Class)
> > com.andrew.overflow.answers (Package)
> > > Some (Class)
> > > None (Class)

When I search for this question, I only find how to import single classes when I'm looking for how to export (or "build") single classes.

A: In Netbeans 8.1, right-click your project and go to Properties. In the Sources menu, click the Includes/Excludes button.
To include only the Foo class, you would enter **/Foo.java into the Includes field. To add the entire .questions package, you would enter **/questions/**. Multiple includes are separated by a comma.


text:
Q: bat command - eliminate the strings from right to left im trying to split the strings. please find the details below,
Scenario:
set test1="C:A\B\C\D\X\Y\Z"
set test2="D:A\B\X\Y\Z"

echo %test1%
echo %test2%

i have to eliminate "\X\Y\Z" and i need the remaining string.
expectation is it should print like below output
echo C:A\B\C\D
echo D:A\B

Thanks for reading this

A: In case you don't want to remove a known string, but want the folder name "three up":
set "test1=C:\A\B\C\D\X\Y\Z"
for %%a in ("%test1%\..\..\..") do echo %%~fa


text:
Q: Timer as a background job I want to implement a timer so as to keep track of a test program.
The timer will be in a different file and linked with my test.cc (test program).
I wantto keep track of execution, so as which statement takes how much time, and when the timer reaches certain interval may br 10 secs, i wish to do something, like may be aborting the test program.
I am using C++ in Linux environment.
Can someone tell me how to achieve it?

A: There are several solutions possible.
If you can use POSIX threads and if the timer is only needed to end your application, then the "timer" can wait in a separate thread by using the nanosleep call.  On wakeup, a signal can be sent (or a signal to a thread).


text:
Q: Coprimes - assumption and required proof We have three numbers $a$, $b$ and $c$.
There them $gcd(a, b) = 1$ and $gcd(a, c) = 1$ and $gcd(b, c) = 1$ (coprimes).
It must be shown that there are an infinitely many $k$ such that $gcd(a, k) = 1$ and $gcd(b, k) = 1$, and $gcd(c, k) = 1$ (a, b, c, k are coprime) and $k$ is not a prime.
The assumption seems obvious to me but someone might try to prove it?

A: Let $e=abc$. Since there are infinitely many primes $\{p_i\}_{\infty}$ such that $m>n \implies p_m>p_n$, let $j$ be such that $p_j>e$. Then for any $k,l>j$ you get $\gcd(a,p_kp_l)=1$, $\gcd(b,p_kp_l)=1$ and $\gcd(c,p_kp_l)=1$.
Note that you don't need any assumptions about $a$, $b$, $c$.
Also the $\{p_i\}_\infty$ should just be thought of as the enumeration of all primes in ascending order.


text:
Q: Issue while returning the errors list Below is code in views.py file.
class login(View):
    def get(self, request):
        return render(request, 'login.html')
    def post(self, request):
        form = LoginForm(request.POST)
        if form.is_valid():
            username = request.POST.get('username')
            password = request.POST.get('password')
            return HttpResponse("ok")
        else:
            form = LoginForm()
            return HttpResponse(form)

Below code is in template file.
<form method="post" action="{% url 'authapp:login' %}">
    {% csrf_token %}
    <input type="text" name="username" class="form-control">
    <input type="password" name="password" class="form-control">
    <button type="submit" class="btn btn-primary">
        Login
    </button>
</form>

below code is in forms.py file
from django import forms

class LoginForm(forms.Form):
    username = forms.CharField(max_length = 50, required = True),
    password = forms.CharField(max_length = 50, required = True)

Issue Details
When i submit the form with both username and password empty, it returns just a textfield of password.
I was expecting a list of errors for required username and password. As both are required in forms file.
Can you please suggest something?

A: change your views.py so it actually return the forms to the template:
class login(View):
    if request.method == 'GET':
        form = LoginForm()
        return render(request, 'login.html', {'form': form})
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            # some validation stuffs
            return HttpResponse("ok")
        else:
            return render(request, 'login.html', {'form': form})

Your forms.py so it actually use to render:
from django import forms

class LoginForm(forms.Form):
    username = forms.CharField(label="username", max_length=50, required=True, widget=forms.TextInput(attrs={'class' : 'form-control'}))
    password = forms.CharField(label="password", max_length=50, required=True, widget=forms.PasswordInput(attrs={'class': 'form-control'}))

And your template:
<form method="post" action="{% url 'authapp:login' %}">
    {% csrf_token %}
    {{ form.username }}
    {% if form.username.errors %}
       {% for error in form.username.errors %}
          {{ error }}
       {% endfor %}
    {% endif %}
    {{ form.password }}
    {% if form.password.errors %}
       {% for error in form.password.errors %}
           {{ error }}
        {% endfor %}
    {% endif %}
    <button type="submit" class="btn btn-primary">
        Login
    </button>
</form>

I think you should finish reading the form docs before you doing this since last question you didn't know that you have to add forms.py in your project

A: You need to enable the debug true in settings.py file
DEBUG = True


text:
Q: E: Malformed entry 4 in list file /etc/apt/sources.list.d/additional-repositories.list (Component) E: The list of sources could not be read i'm trying to install putty and i got the following error
E: Malformed entry 4 in list file /etc/apt/sources.list.d/additional-repositories.list (Component)
E: The list of sources could not be read.
E: Malformed entry 4 in list file /etc/apt/sources.list.d/additional-repositories.list (Component)
E: The list of sources could not be read.

after going through some posts on this forum . i opened the file using sudo nano /etc/apt/sources.list.d/additional-repositories.list i have the following content
deb [arch=amd64] https://download.docker.com/linux/debian    sylvia    stable
deb [arch=amd64] https://download.docker.com/linux/debian    sylvia    stable
deb [arch=amd64] https://download.docker.com/linux/ubuntu    sylvia sudo add-ap$
deb [arch=amd64] https://download.docker.com/linux/ubuntustable
deb [arch=amd64] https://download.docker.com/linux/ubuntu xenial stable

i created a space between ubuntu and stable in line 4 . but still got the sane error?
what is wrong with it ?
P.S:- While getting my hands on first time on docker, i uninstalled some packages which i don't need . so, i would like to remove all docker files and install freshly for linux mint.

A: You need a distribution keyword between ubuntu and stable, e.g.
deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable
if you're on 20.04.


text:
Q: Threading params in f# I have the following issue - a handful of functions and 2 types where each of the functions takes at least 2 params (one of each defined type).
Now those types are parametrized and can only be used with those functions if their generic type params fit.
type Record<'a, 'b> = { first: 'a; second: 'b }
type Lens<'a, 'b> = Lens of 'a * 'b

let someFn lens rec : Record<'a, 'b> = ....
let anotherFn lens rec : Record<'a, 'b> = ...
let aThirdFn lens rec : Record<'a, 'b> = ...
//and potentially a dozen functions more that might or might not return a record

The usage scenario is something like this
let workflow1 () =
    let intIntLens = Lens (1, 1)
    let intIntRec = { first = 10; second = 100}

    intIntRec
    |> someFn intIntLens
    |> anotherFn intIntLens
    |> aThirdFn intIntLens

let workflow2 () =
    let strIntLens = Lens ("foo", 1)
    let strIntRec = { first = "bar"; second = 100}

    strIntRec
    |> someFn strIntLens
    |> someFn strIntLens
    |> aThirdFn strIntLens
    |> anotherFn strIntLens
    |> someFn strIntLens

Now for any given workflow the lens type stays the same but record is being somehow processed.
However I have to thread the lens into each of those functions which is somehow boring.
One obvious option would be to have a mutable module level variable. Which I assume wouldnt work for much long in the face of concurrent code.
So what is the best approach to get rid of the lens param here?

A: If your functions always take and return the same type (meaning they themselves are all of the same type), you could just make a list of them and apply in order:
let ap lens fns rec = Seq.fold (fun r f -> f lens r) rec fns

let workflow2 () =
    let strIntLens = Lens ("foo", 1)
    let strIntRec = { first = "bar"; second = 100}

    ap strIntLens [someFn; someFn; aThirdFn; anotherFn; someFn] strIntRec

I can't see how the functions could be of different types, but perhaps this is just a toy example, and your real problem actually does deal with functions of different types.
If that is the case, here's a slightly less elegant solution: define a pipe locally to close the lens within it.
let workflow2 () =
    let strIntLens = Lens ("foo", 1)
    let strIntRec = { first = "bar"; second = 100}
    let (|*>) r f = f strIntLens r

    strIntLens
    |*> someFn
    |*> someFn
    |*> aThirdFn
    |*> anotherFn
    |*> someFn

(Note that I did not reuse the standard pipe name |>. Though technically possible, that would make the code less readable)
Finally, you could go all-out on the problem, and combine input with lens in a single data structure, then create a custom pipe to work with such structure, which will apply the function, but tunnel the lens:
type RecAndLens<'a, 'b> = { rec: Record<'a, 'b>; lens: Lens<'a, 'b> }
let (|*>) rl f = { rec = f rl.lens rl.rec; lens = rl.lens }

let workflow2 () =
    ...
    { rec = strIntRec; lens = strIntLens }
    |*> someFn
    |*> someFn
    |*> aThirdFn
    |*> anotherFn
    |*> someFn

This final approach would be a "long-term" kind of foundation, in case you're building a highly reusable library or something.
Technically, for a quick-and-dirty proof of concept, you could just use a tuple instead of the RecAndLens record:
let (|*>) (rec,lens) f = f lens rec, lens

let workflow2 () =
    ...
    (strIntRec, strIntLens)
    |*> someFn
    |*> someFn
    |*> aThirdFn
    |*> anotherFn
    |*> someFn

But this would be less sound, more error-prone (smells a bit of primitive obsession).


text:
Q: How to check in an activity if a file was not downloaded completely redownload it My question is: when download getting started the file "music.mp3" will make in directory but it is not complete I want to check if the file is not complete redownload it
here is my code:
String root = android.os.Environment.getExternalStorageDirectory() + "/folderName/music.mp3";
            File wav = new File(root);
            long length = wav.length();
        if (!wav.isFile()) {

            // instantiate it within the onCreate method
            mProgressDialog = new ProgressDialog(TV_LG.this); // Downloading = activity name
            mProgressDialog.setMessage("downloading... . .");
            mProgressDialog.setIndeterminate(true);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(true);

            // execute this when the downloader must be fired
            final DownloadTask downloadTask = new DownloadTask(TV_LG.this); // Downloading = activity name

downloadTask.execute("http://dl.music.ml/1398/03/16/music.mp3"); // the url to the file you want to download
            mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    downloadTask.cancel(true);
                }
            });
            return;

        }
    }

private class DownloadTask extends AsyncTask {
    private Context context;

    public DownloadTask(Context context) {
        this.context = context;
    }

    @Override
    protected String doInBackground(String... sUrl) {
        // take CPU lock to prevent CPU from going off if the user
        // presses the power button during download
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                getClass().getName());
        wl.acquire();

        try {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                // expect HTTP 200 OK, so we don't mistakenly save error report
                // instead of the file
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
                    return "Server returned HTTP " + connection.getResponseCode()
                            + " " + connection.getResponseMessage();

                // this will be useful to display download percentage
                // might be -1: server did not report the length
                int fileLength = connection.getContentLength();

                // download the file
                input = connection.getInputStream();

                File root = android.os.Environment.getExternalStorageDirectory();
                File dir = new File(root.getAbsolutePath() + "/folderName");
                if (!dir.exists()) {
                    dir.mkdirs(); // build directory
                }
                output = new FileOutputStream(root.getAbsolutePath() + "/folderName/music.mp3");

                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    // allow canceling with back button
                    if (isCancelled())
                        return null;
                    total += count;
                    // publishing the progress....
                    if (fileLength > 0) // only if total length is known
                        publishProgress((int) (total * 100 / fileLength));

                    output.write(data, 0, count);
                }
            } catch (Exception e) {
                return e.toString();
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }

                if (connection != null)
                    connection.disconnect();
            }
        } finally {
            wl.release();
        }
        return null;
    }


text:
Q: Update user data in PHP without refreshing page (Ajax?) I made some update user information code in PHP, but that form I inserted into one of tabs on my site:
When I fill form and submit it, my page refresh and  brought me to first tabe again.
How can I prevent it?
I tryed with ajax but don't now how exactly.
[EDIT] I added ajax
my code:
<form action="" method="post">

Adresa:
 <input type="text" name="address" id="address"/>

Grad:
<input type="text" name="city" id="city"/>

Poštanski broj:
 <input type="number" name="zip" id="zip"/>

Mobitel/Telefon:
 <input type="tel" name="phone_number" id="phone_number"/>

Lozinka:
 <input type="password" name="password" id="password"/>

Ponoviti lozinku:
<input type="password" name="repassword" id="repassword" onkeyup="checkPass(); return false;"/>

<input type="submit" value="izmijeni"/>

                </form>


text:
Q: Display SVG stored as data URI using background-image: Why is property value invalid? I store SVG files as data URIs in MySQL. Later I want to display the SVGs as images again using the CSS background-image property.
This is how I produce the data URI (following this answer).
// SVG element
let svg = document.getElementById('tree-svg');

// SVG as string
let serializer = new XMLSerializer();
let svgSource = serializer.serializeToString(svg);

// Add name spaces
if (! svgSource.match(/^<svg[^>]+xmlns = "http\:\/\/www\.w3\.org\/2000\/svg"/)) {
    svgSource = svgSource.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"');
}
if (! svgSource.match(/^<svg[^>] + "http\:\/\/www\.w3\.org\/1999\/xlink"/)) {
    svgSource = svgSource.replace(/^<svg/, '<svg xmlns:xlink="http://www.w3.org/1999/xlink"');
}

// XML declaration
svgSource = '<?xml version="1.0" standalone="no"?>\r\n' + svgSource;

// data URI
let svgUri = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svgSource);

I store svgUri as a blob in MySQL. This is a sample string representing a simple SVG:
data:image/svg+xml;charset=utf-8,%3C%3Fxml%20version%3D%221.0%22%20standalone%3D%22no%22%3F%3E%0D%0A%3Csvg%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20id%3D%22tree-svg%22%20viewBox%3D%220%200%20700%20500%22%3E%3Cg%20transform%3D%22translate(40%2C%2040)%22%3E%3Ctext%20class%3D%22node-text%22%20y%3D%2220%22%20x%3D%2223.192203521728516%22%20id%3D%22n0%22%3Eone%3Ctspan%20class%3D%22node-subscript%22%3E1%3C%2Ftspan%3E%3C%2Ftext%3E%3Cline%20x1%3D%2223.192203521728516%22%20y1%3D%2240%22%20stroke-width%3D%222%22%20id%3D%22n0%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E

This is the CSS to display the SVG as an image (this is Blade template syntax, but as I can see in dev tools, the string from my database is rendered correctly between the parentheses):
edit: I added the quotes in the below code sample after reading a comment. It's working now.
background-image: url("{!! $sentence['svg'] !!}")

This doesn't work yet, nothing is rendered. The div I attach the background image to is empty. If I paste the string from MySQL to a URL bar, the SVG is displayed correctly.
What do I need to change in my JS code and or in CSS to display the SVG as background-image?


text:
Q: python tempfile read and write I am having issues reading and writing to a tempfile:
import tempfile

def edit(base):
    tmp = tempfile.NamedTemporaryFile(mode='w+')
    #fname = tmp.name
    tmp.write(base)
    #system('nano %s' % fname)
    content = tmp.readlines()
    tmp.close()
    return content

answer = "hi"
print(edit(answer))

Output is [] instead of ["hi"]
I don't get the reason behind it,
Help is appreciated

A: Temporary files are still files; they have a "pointer" to the current position in the file. For a freshly written file, the pointer is at the end of the last write, so if you write without seeking, you read from the end of the file, and get nothing. Just add:
tmp.seek(0)

after the write and you'll pick up what you wrote in the next read/readlines.
If the goal is solely to make the data visible to something else opening the file by name, e.g. an outside program like nano in your commented out code, you can skip the seek, but you do need to make sure the data is flushed from buffer to disk, so at the same point after the write, you'd add:
tmp.flush()

A: You're wrong because of the cursor's position.
When you write to a file, cursor will stop at the very end of your text. Then you're reading which means nothing. Because cursor reads the data comes after its position. For quickfix, the code must be like this:
import tempfile

def edit(base):
    tmp = tempfile.NamedTemporaryFile(mode='w+')
    #fname = tmp.name
    tmp.write(base)
    tmp.seek(0, 0)  # This will rewind the cursor
    #system('nano %s' % fname)
    content = tmp.readlines()
    tmp.close()
    return content

answer = "hi"
print(edit(answer))

You may want to read the documentation about that.
https://docs.python.org/3/tutorial/inputoutput.html?highlight=seek#methods-of-file-objects


text:
Q: Javascript - multidimensional associative array I would like to know (if it's possible) how I can push data into a multidimensional associative array with JavaScript like this:
myarray['type1']['label1'].push('Data to insert');
myarray['type1']['label1'].push('Data2 to insert');
myarray['type1']['label1'].push('Data3 to insert');

myarray['type2']['label1'].push('Data to insert');
myarray['type2']['label2'].push('Data1 to insert');
myarray['type2']['label2'].push('Data2 to insert');

Here is the answer thanks to Brennan:
myarray = {};
myarray['type1'] = {};
myarray['type1']['label1'] = [];
myarray['type1']['label1'].push('Data to insert');
myarray['type1']['label1'].push('Data2 to insert');
myarray['type1']['label1'].push('Data3 to insert');

console.log(myarray);

http://jsfiddle.net/177zu9n4/
Thanks a lot.

A: First, there needs to be an array there to push the data into:
myarray = {};
myarray['type1'] = {};
myarray['type1']['label1'] = [];
myarray['type1']['label1'].push('Data to insert');
myarray['type1']['label1'].push('Data2 to insert');
myarray['type1']['label1'].push('Data3 to insert');

A: myarray= {};
myarray.type1= {};
myarray.type1.label1= "Data to insert";

console.log(myarray.type1.label1);

Is this what you need?
If label1 is somehow meant to hold stuff too, as an array:
myarray= {};
myarray.type1= {};
myarray.type1.label1= [];

myarray.type1.label1.push("data");

console.log(myarray.type1.label1);

Note that I used both object and arrays in the last example, and only objects in the first. Each have case-specific uses they are better at.


text:
Q: Add up 2 datagridview cell values I have 3 Datagridview controls in vb.net form. DGV1 with price column, DGV2 with quantity column and the 3rd one is the total column DGV3. deos anyone tell me please on how to do this, DGV1*DGV2 show the total on DGV3 and update DGV3 everytime DVG1 cellvalue get changed. my code below doesn't update DGV3. also, one of the problems is that DGV3 get calculated before DGV2 bind the DATA and if DGV2 cell value=0 it gives me a wrong total. any idea ? appreciated,
 Private Sub DGV1_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV1.CellValueChanged
    Dim Tot As Int32 = 0
   DGV3.Enabled = False
    DGV3.DataSource = Nothing
    DGV3.Enabled = True

    Dim OBJ As Double
    Dim SALES As Integer
    Dim dtt As DataTable
    For Each R As DataGridViewRow In Me.DGV1.Rows
        For Each N As DataGridViewRow In Me.DGV2.Rows

            OBJ = CDbl(R.Cells(4).Value)
            SALES = CInt(CDbl(N.Cells(0).Value))
            Tot = CInt(OBJ * SALES)
            DGV3.Rows.Add(Tot.ToString)

        Next
    Next
End Sub

A: If you were able to use the one datagridview, I would go about it like this:
    Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ''// Set the number of columns.
        DataGridView1.ColumnCount = 3
        DataGridView1.ColumnHeadersVisible = True

        ''// Set the column header style.
        Dim columnHeaderStyle As New DataGridViewCellStyle()

        columnHeaderStyle.BackColor = Color.Beige
        columnHeaderStyle.Font = New Font("Verdana", 10, FontStyle.Bold)
        DataGridView1.ColumnHeadersDefaultCellStyle = columnHeaderStyle

        ''// Set column names.
        DataGridView1.Columns(0).Name = "Price"
        DataGridView1.Columns(1).Name = "Quantity"
        DataGridView1.Columns(2).Name = "Total"

        DataGridView1.Enabled = False
        DataGridView1.DataSource = Nothing
        DataGridView1.Enabled = True

    End Sub

    Private Sub DataGridView1_CurrentCellChanged(sender As Object, e As EventArgs) Handles DataGridView1.CurrentCellChanged

        ''// show the total in column 3 and update column 3 everytime column `price's` cellvalue gets changed.
        If (DataGridView1.CurrentCell.ColumnIndex = 0) Then
            ''// MsgBox("Updating column three `Total`")

            For Each R As DataGridViewRow In DataGridView1.Rows
                On Error Resume Next ''// iKNOW <-.->

                Dim price As Double = R.Cells(0).Value.ToString
                Dim quantity As Integer = R.Cells(1).Value.ToString

                ''// not the auto new new at the bottom. <`.'>
                If Not (R.IsNewRow) Then
                    Dim Tot As Double = CInt(price * quantity)
                    R.Cells(2).Value = Tot
                End If

            Next

        End If

     End Sub
 End Class

A: Create an Empty DGV and Add the desired columns in it using Add Columns. Then use Edit Columns to select the values to be displayed under each specific column which you have created now. You could see DataBindingsource option in every newly created column. so choose your needed Datasource to be binded and the DisplayMember (the column name that contains values that you like to display)


text:
Q: I am having trouble using jquery to submit a form. It was working before;/ When a user clicks a link it uses jquery ajax to submit a form to go to paypal. It is not working for some reason. I appreciate any help.
The HTML link:
Paypal

The JS function:
function go_paypal() {

data = 'req_paypal=1';

$.blockUI({ message: '
 Going to Paypal...
',css:{background:'#000'} });
    $.ajax({
      type: "POST",
      url: "index.php",
      data: data,
      success: function(data) { $("#paypal_form").html(data); $("#payPalForm").submit(); } ,
      error: function() {$.unblockUI(); alert('Unable to communicate to server.'); }
    });
    return false;
}

The PHP code:
if(isset($_POST['req_paypal']) && $_POST['req_paypal'] == 1 ) {

    $sql = 'INSERT INTO `transactions` (id,type,ip,time,ammount,status) VALUES (NULL,1,\''.$_SERVER['REMOTE_ADDR'].'\',\''.time().'\',\''.$global['paypal_prod_amount'].'\',0) ';
    echo $sql;
//      $sql2 = 'INSERT INTO `users` (id,email,password,referred_by,referrals) VALUES ('',)';

    mysql_query($sql);

    $id = mysql_insert_id();

    $html = '
    <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" id="payPalForm">
<input type="hidden" name="item_number" value="One Year of Imgur Pro">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="business" value="'.$global['paypal_email'].'">
<input type="hidden" name="custom" value="'.base64_encode($id).'">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="return" value="'.$global['paypal_return'].'">
<input name="item_name" type="hidden" id="item_name" value="One Year of Imgur Pro" >
<input name="amount" type="hidden" id="amount" value="'.$global['paypal_prod_amount'].'" >
</form>
    ';

    echo $html;exit;
}

A: Looks like inside your success function, you are passing the global variable data to html(). Try naming your vars a bit more carefully.
Try this:
function go_paypal() {

var postData = 'req_paypal=1';

$.blockUI({ message: '
 Going to Paypal...
',css:{background:'#000'} });
    $.ajax({
      type: "POST",
      url: "index.php",
      data: postData,
      success: function(data) { $("#paypal_form").html(data); $("#payPalForm").submit(); },
      error: function(e) {$.unblockUI(); alert('Unable to communicate to server.'); }
    });
    return false;
}

A: Unfortunately the problem here seems very vague since we don't know what really isn't working. My basic recommendation to find out what is not working is to turn on error reporting in PHP and then print copious amounts of output at each step of the process. Print variable values at each step to see if they are what you think they should be. Print messages to let you know when you enter a subroutine, etc. This will help narrow down where something goes wrong. Often, you will find that you just mistyped something.
I see the array $global, but it doesn't seem to be defined. Did you mean $GLOBALS? I would suspect that is the problem. If you turn your error reporting on in PHP while testing, you should see some complaints about an undefined variable. Also, while testing, double check all of your values and be sure to fuzz test. Some problems might not be apparent until too late to fix once it goes live.

A: First I would try to add a input submit to the form in PHP and also try that form in the code without fetching via ajax and in Firebug execute the submit code $("#payPalForm").submit(); to see if it works.

A: Um... did you try: Paypal I had the same problem and it was the a's onclick handler... So if this doesnt work dont give me -1 i was just trying to help based on my previous experience. =)

A: your data object must be a json object, not a string.
try this:
function go_paypal() {
    data = { req_paypal: 1 };

    $.blockUI({ message: '
 Going to Paypal...
', css:{background:'#000'} });
        $.ajax({
          type: "POST",
          url: "index.php",
          data: data,
          success: function(data) { $("#paypal_form").html(data).submit(); } ,
          error: function() { $.unblockUI(); alert('Unable to communicate to server.'); }
        });
}

i would also suggest to change the a tag to
$("#go_paypal").click(function() { go_paypal(); }

or
Paypal

that way the page wont be scrolled to the top when the link is clicked


text:
Q: php function argument default value - how to know that def. value was applied? I have a function
function my_func($id,$arg1='aaa',$arg2='bbb'){
 if($arg1=='aaa'){
     //means that def. value applied, real argument has not been provided
 }
 if($arg1=='bbb'){
     //means that def. value applied, real argument has not been provided
 }
}

I check if my values are default I will do one thing, if not - another thing.
But my user may call my function like
 my_func($id,'aaa','bbb')

So he provided real values. How I know that these values are real in my code, not default?

A: In PHP, when a user supplies the default value for an optional argument the result is exactly the same as when the argument is absent. There is no way to tell the difference.
What you can do is design your function so that the default values cannot be confused with actual, useful arguments. You can then detect this case and supply the values you really want used in this case. For example:
function my_func($id,$arg1=null,$arg2=null){
 if($arg1===null){
     $arg1 = "aaa";
     // do other default things
 }
 if($arg2===null){
     $arg2 = "bbb";
     // do other default things
 }
}

If the caller calls the function with "aaa", it will not be mistaken for a default argument. Of course the caller can always call the function with null as the value, which will be indistinguishable from absent arguments; but that's not really such a bad thing, the special values just mean "do the default thing".


text:
Q: Have buttons move div different amounts So I have three buttons, each triggers an event. At the same time as triggering an event, i want it to move a div next to the button that was clicked. Problem is I want it not to teleport next to the button but move there in an animation. I have my code organised as shown below but it only occurs once and then when i try and click on a different button the div stays there.

function func1() {
  var elem = document.getElementById("thebarofpower");
    var pos = elem.style.top;
  var doneTheStuff;
    var id = setInterval(frame, 10);
    function frame() {
  if (!doneTheStuff) {
    doneTheStuff = true;
  } else if (pos == 6) {
            clearInterval(id);
        } else if (pos > 6) {
            pos++;
            elem.style.top = pos - 'px';
        } else {
          pos++;
          elem.style.top = pos + 'px';
        }
    }
    }

    function func2() {
  var elem = document.getElementById("thebarofpower");
    var pos = elem.style.top;
    var doneTheStuff;
    var id2 = setInterval(frame2, 10);
    function frame2() {
       if (!doneTheStuff) {
    doneTheStuff = true;
  } else if (pos == 60) {
            clearInterval(id2);
        } else if (pos > 60) {
            pos++;
            elem.style.top = pos - 'px';
        } else {
          pos++;
          elem.style.top = pos + 'px';
        }
    }
    }
        function func3() {
  var elem = document.getElementById("thebarofpower");
    var pos = elem.style.top;
    var doneTheStuff;
    var id3 = setInterval(frame3, 10);
    function frame3() {
          if (!doneTheStuff) {
    doneTheStuff = true;
  } else if (pos == 120) {
            clearInterval(id3);
        } else {
            pos++;
            elem.style.top = pos + 'px';
        }
    }
    }
#button-1 {
  position: absolute;
  background: transparent;
  left: 0px;
  top: 0px;
  width: 50px;
  height: 50px;
  border: ;
  box-shadow: 6px 6px 6px #888888;
}
#button-2 {
  position: absolute;
  background: transparent;
  left: 0px;
  top: 60px;
  width: 50px;
  height: 50px;
  border: ;
  box-shadow: 6px 6px 6px #888888;
}
#button-3 {
  position: absolute;
  background: transparent;
  left: 0px;
  top: 120px;
  width: 50px;
  height: 50px;
  border: ;
  box-shadow: 6px 6px 6px #888888;
}

#thebarofpower{
  position: absolute;
  background-color: #42bff4;
  width: 2px;
  height: 50px;
  left: 70px;
  top: 0px;
  border-radius: 30px;
  box-shadow: 0px 0px 10px 1px #41d0f4;
}
<button id="button-1" onclick="func1()"></button>
<button id="button-2" onclick="func2()"></button>
<button id="button-3" onclick="func3()"></button>

A: The main issue is that after you change the style.top to a number plus px, you have to account for that when you check it the next time.  There were also a few situations where you were moving in the wrong direction.

function func1() {
  var elem = document.getElementById("thebarofpower");
  var pos = elem.style.top;
  if (pos[pos.length-2] == "p") pos = pos.slice(0, pos.length -2)
  var doneTheStuff;
  var id = setInterval(frame, 10);

  function frame() {
    if (!doneTheStuff) {
      doneTheStuff = true;
    } else if (pos == 6) {
      clearInterval(id);
    } else if (pos > 6) {
      pos--;
      elem.style.top = pos + 'px';
    } else {
      pos++;
      elem.style.top = pos + 'px';
    }
  }
}

function func2() {
  var elem = document.getElementById("thebarofpower");
  var pos = elem.style.top;
  if (pos[pos.length-2] == "p") pos = pos.slice(0, pos.length -2)
  var doneTheStuff;
  var id2 = setInterval(frame2, 10);

  function frame2() {
    if (!doneTheStuff) {
      doneTheStuff = true;
    } else if (pos == 60) {
      clearInterval(id2);
    } else if (pos > 60) {
      pos--;
      elem.style.top = pos + 'px';
    } else {
      pos++;
      elem.style.top = pos + 'px';
    }
  }
}

function func3() {
  var elem = document.getElementById("thebarofpower");
  var pos = elem.style.top;
  if (pos[pos.length-2] == "p") pos = pos.slice(0, pos.length -2)
  var doneTheStuff;
  var id3 = setInterval(frame3, 10);

  function frame3() {
    if (!doneTheStuff) {
      doneTheStuff = true;
    } else if (pos == 120) {
      clearInterval(id3);
    } else {
      pos++;
      elem.style.top = pos + 'px';
    }
  }
}
#button-1 {
  position: absolute;
  background: transparent;
  left: 0px;
  top: 0px;
  width: 50px;
  height: 50px;
  border: ;
  box-shadow: 6px 6px 6px #888888;
}

#button-2 {
  position: absolute;
  background: transparent;
  left: 0px;
  top: 60px;
  width: 50px;
  height: 50px;
  border: ;
  box-shadow: 6px 6px 6px #888888;
}

#button-3 {
  position: absolute;
  background: transparent;
  left: 0px;
  top: 120px;
  width: 50px;
  height: 50px;
  border: ;
  box-shadow: 6px 6px 6px #888888;
}

#thebarofpower {
  position: absolute;
  background-color: #42bff4;
  width: 2px;
  height: 50px;
  left: 70px;
  top: 0px;
  border-radius: 30px;
  box-shadow: 0px 0px 10px 1px #41d0f4;
}
<button id="button-1" onclick="func1()"></button>
<button id="button-2" onclick="func2()"></button>
<button id="button-3" onclick="func3()"></button>

A: https://jsfiddle.net/t8jztc7x/1/

$('.btn').each(function(){
var btnOffset = $(this).offset().top;
$(this).click(function(){
$('#thebarofpower').css('top',btnOffset)
});
});
#button-1 {
  position: absolute;
  background: transparent;
  left: 0px;
  top: 0px;
  width: 50px;
  height: 50px;
  border: ;
  box-shadow: 6px 6px 6px #888888;
}
#button-2 {
  position: absolute;
  background: transparent;
  left: 0px;
  top: 60px;
  width: 50px;
  height: 50px;
  border: ;
  box-shadow: 6px 6px 6px #888888;
}
#button-3 {
  position: absolute;
  background: transparent;
  left: 0px;
  top: 120px;
  width: 50px;
  height: 50px;
  border: ;
  box-shadow: 6px 6px 6px #888888;
}

#thebarofpower{
  position: absolute;
  background-color: #42bff4;
  width: 2px;
  height: 50px;
  left: 70px;
  top: 0px;
  border-radius: 30px;
  box-shadow: 0px 0px 10px 1px #41d0f4;
 transition:top 0.4s
}

<button id="button-1" class="btn"></button>
<button id="button-2" class="btn"></button>
<button id="button-3"  class="btn"></button>

A: Your functions just weren't processing the pixel change exactly right.  I made a couple of small changes (summarized below) and here is a solution that works as intended:

var elem = document.getElementById("thebarofpower");

function func1() {
    var pos = elem.style.top.slice(0,-2);
    var doneTheStuff;
    var id = setInterval(frame, 10);
    function frame() {
        if (!doneTheStuff) {
            doneTheStuff = true;
        }
        else if (pos == 6) {
            clearInterval(id);
        }
        else if (pos > 6) {
            pos--;
            elem.style.top = pos + 'px';
        }
        else {
            pos++;
            elem.style.top = pos + 'px';
        }
    }
}

function func2() {
    var pos = elem.style.top.slice(0,-2);
    var doneTheStuff;
    var id2 = setInterval(frame2, 10);
    function frame2() {
        if (!doneTheStuff) {
            doneTheStuff = true;
        }
        else if (pos == 60) {
            clearInterval(id2);
        }
        else if (pos > 60) {
            pos--;
            elem.style.top = pos + 'px';
        }
        else {
            pos++;
            elem.style.top = pos + 'px';
        }
    }
}

function func3() {
    var pos = elem.style.top.slice(0,-2);
    var doneTheStuff;
    var id3 = setInterval(frame3, 10);
    function frame3() {
        if (!doneTheStuff) {
            doneTheStuff = true;
        }
        else if (pos == 120) {
            clearInterval(id3);
        }
        else {
            pos++;
            elem.style.top = pos + 'px';
        }
    }
}
#button-1 {
  position: absolute;
  background: transparent;
  left: 0px;
  top: 0px;
  width: 50px;
  height: 50px;
  border: ;
  box-shadow: 6px 6px 6px #888888;
}
#button-2 {
  position: absolute;
  background: transparent;
  left: 0px;
  top: 60px;
  width: 50px;
  height: 50px;
  border: ;
  box-shadow: 6px 6px 6px #888888;
}
#button-3 {
  position: absolute;
  background: transparent;
  left: 0px;
  top: 120px;
  width: 50px;
  height: 50px;
  border: ;
  box-shadow: 6px 6px 6px #888888;
}

#thebarofpower{
  position: absolute;
  background-color: #42bff4;
  width: 2px;
  height: 50px;
  left: 70px;
  top: 0px;
  border-radius: 30px;
  box-shadow: 0px 0px 10px 1px #41d0f4;
}
<button id="button-1" onclick="func1()"></button>
<button id="button-2" onclick="func2()"></button>
<button id="button-3" onclick="func3()"></button>

Changes:

*

*Removed "px" from the position before processing it

*Moved the element variable declaration outside the functions so you only have to declare it once, rather than 3 times

*Some of the pos++ commands were moving the bar in the wrong direction; changed them to pos--


text:
Q: How to calculate overdue fee's every month I am having a problem with overdue calculation because I don't know how to get the month interval of the date I set.
I want to add 3% to the remaining balance when the date today reaches the overdue date.
Here is my code:

<?php
 $balance = $fetch['total'] - $total;
 $loan_date = strtotime($fetch['loan_end']);
 $TodayDate = strtotime('today');

  <!--plus 3% to the remaining for every month exceeds to loan_date then print the balance below-->

 print number_format($balance);

?>

Here is my example interval for every 30 days exceed to loan_end

       $invoicedate = strtotime("2013/07/01");
       $TodayDate = strtotime('today');

       $timeDiff = abs($TodayDate - $invoicedate);

       $numberDays = $timeDiff/86400;  // 86400 seconds in one day

       $numberDays = intval($numberDays);

       $noOfdaysToCheck ="30";

       $Fees ="600";

       if ($numberDays >= $noOfdaysToCheck){

              $Interval = $numberDays%$noOfdaysToCheck;

              for($i=1;$i<=$Interval;$i++){
                     $late = (1.5 / 100) * $Fees;
                     $Fees =  FeesCalc($Fees);

               }
        }

       $Fees = number_format($Fees, 2, '.', '');
       echo $Fees;

       function FeesCalc($Fees){
            $late = (1.5 / 100) * $Fees;
            return $TotalFees = $late+$Fees;

       }

It calculates the fee for every 30 days exceeding. now in my code I want to calculate (add 3+ to the balance) every month exceeding to loan end.

A: Instead of using strtotime(), use PHP's DateTime objects instead. They have a built in method to calculate the number of months between two objects:
<?php

$balance = $fetch['total'] - $total;
$endDate = new DateTime( $fetch['loan_end'] );
$diff    =  $endDate->diff( new DateTime() );
$months  = round( abs($diff->y * 12 + $diff->m + $diff->d / 30) );

$base    = $balance * 0.03;

$interest = $base * $months;

echo number_format( $interest + $balance );

Please note that this function assumes $fetch['loan_end'] is a MySQL DATE field (i.e. 2014-07-01, for example).

A: Please try this code:

<?php
 $balance = $fetch['total'] - $total;
 $endDate = new DateTime($fetch['loan_end']);
 $today = new DateTime();

 if($today >=$endDate)
  {
   $interval = $endDate->diff(new DateTime());
                        $months = round(abs($interval->y * 12 + $interval->m + $interval->d / 30));
   for($i=1;$i<=$months;$i++){
   $late = (3 / 100) * $balance;
   $balance = FeesCalc($balance);
   }
  }

 print number_format($balance);

  function FeesCalc($balance){
     $late = (3 / 100) * $balance;
     return $TotalFees = $late+$balance;
   }

?>


text:
Q: NewFromFD failed in nativeDecodeFileDescriptor - Android 4.4 I have used Android sample project ContactsList (http://developer.android.com/shareables/training/ContactsList.zip) as an example to develop contacts Activity in my app.
It is working perfectly on all Android versions, but in Android 4.4 the contact images are not being loaded and I get the following error:
 NewFromFD failed in nativeDecodeFileDescriptor

This happens while this method is being executed:
BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);

and it always returns null.
To get the fileDescriptor itself I use this method:
private Bitmap loadContactPhotoThumbnail(String photoData, int imageSize) {
    if (!isAdded() || getActivity() == null) {
        return null;
    }

    AssetFileDescriptor afd = null;
    try {
        Uri thumbUri;

        if (Utils.hasHoneycomb()) {
            thumbUri = Uri.parse(photoData);
            Log.d("imageloader", photoData);
        } else {
            final Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI,photoData);

            thumbUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);
        }

        afd = getActivity().getContentResolver().openAssetFileDescriptor(thumbUri, "r");
        Log.d("imageloader", afd.toString());

        FileDescriptor fileDescriptor = null;

        try{
            fileDescriptor = afd.getFileDescriptor();
            Log.d("imageloader", fileDescriptor.toString());
        } catch (NullPointerException e){
            e.printStackTrace();
        }

        if (fileDescriptor != null) {
            return ImageLoader.decodeSampledBitmapFromDescriptor(
                    fileDescriptor, imageSize, imageSize);
        }
    } catch (FileNotFoundException e) {

        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Contact photo thumbnail not found for contact " + photoData
                    + ": " + e.toString());
        }
    } finally {
        if (afd != null) {
            try {
                afd.close();
            } catch (IOException e) {

            }
        }
    }

    return null;
}

and the photoData is the Contacts.PHOTO_THUMBNAIL_URI taken from ContactsContract.Contacts.CONTENT_URI.
And here is some part of log output of the mentioned code:
12-09 21:15:04.683: D/ImageCache(12531): Memory cache created (size = 6554)
12-09 21:15:05.024: D/ImageLoader(12531): doInBackground - starting work
12-09 21:15:05.024: D/imageloader(12531): content://com.android.contacts/contacts/296/photo
12-09 21:15:05.034: D/imageloader(12531): {AssetFileDescriptor: {ParcelFileDescriptor: FileDescriptor[54]} start=0 len=-1}
12-09 21:15:05.034: D/imageloader(12531): FileDescriptor[54]
12-09 21:15:05.044: D/ImageLoader(12531): doInBackground - finished work
12-09 21:15:05.044: D/ImageLoader(12531): doInBackground - starting work
12-09 21:15:05.054: D/imageloader(12531): content://com.android.contacts/contacts/300/photo
12-09 21:15:05.064: D/imageloader(12531): {AssetFileDescriptor: {ParcelFileDescriptor: FileDescriptor[54]} start=0 len=-1}
12-09 21:15:05.064: D/imageloader(12531): FileDescriptor[54]
12-09 21:15:05.074: D/ImageLoader(12531): doInBackground - finished work
12-09 21:15:05.084: D/ImageLoader(12531): doInBackground - starting work
12-09 21:15:05.084: D/imageloader(12531): content://com.android.contacts/contacts/318/photo
12-09 21:15:05.114: D/imageloader(12531): {AssetFileDescriptor: {ParcelFileDescriptor: FileDescriptor[54]} start=0 len=-1}
12-09 21:15:05.114: D/imageloader(12531): FileDescriptor[54]
12-09 21:15:05.114: D/ImageLoader(12531): doInBackground - finished work
12-09 21:15:05.114: D/ImageLoader(12531): doInBackground - starting work
12-09 21:15:05.114: D/imageloader(12531): content://com.android.contacts/contacts/319/photo
12-09 21:15:05.124: D/imageloader(12531): {AssetFileDescriptor: {ParcelFileDescriptor: FileDescriptor[54]} start=0 len=-1}
12-09 21:15:05.124: D/imageloader(12531): FileDescriptor[54]
12-09 21:15:05.124: D/ImageLoader(12531): doInBackground - finished work
12-09 21:15:05.124: D/ImageLoader(12531): doInBackground - starting work
12-09 21:15:05.124: D/imageloader(12531): content://com.android.contacts/contacts/320/photo
12-09 21:15:05.144: D/imageloader(12531): {AssetFileDescriptor: {ParcelFileDescriptor: FileDescriptor[54]} start=0 len=-1}
12-09 21:15:05.144: D/imageloader(12531): FileDescriptor[54]
12-09 21:15:05.144: D/ImageLoader(12531): doInBackground - finished work
12-09 21:15:05.144: D/ImageLoader(12531): doInBackground - starting work
12-09 21:15:05.144: D/imageloader(12531): content://com.android.contacts/contacts/302/photo
12-09 21:15:05.154: D/imageloader(12531): {AssetFileDescriptor: {ParcelFileDescriptor: FileDescriptor[55]} start=0 len=-1}
12-09 21:15:05.154: D/imageloader(12531): FileDescriptor[55]
12-09 21:15:05.154: D/ImageLoader(12531): doInBackground - finished work
12-09 21:15:05.164: D/ImageLoader(12531): doInBackground - starting work
12-09 21:15:05.164: D/imageloader(12531): content://com.android.contacts/contacts/301/photo
12-09 21:15:05.164: D/imageloader(12531): {AssetFileDescriptor: {ParcelFileDescriptor: FileDescriptor[55]} start=0 len=-1}
12-09 21:15:05.164: D/imageloader(12531): FileDescriptor[55]
12-09 21:15:05.174: D/ImageLoader(12531): doInBackground - finished work
12-09 21:15:05.174: D/ImageLoader(12531): doInBackground - starting work
12-09 21:15:05.174: D/imageloader(12531): content://com.android.contacts/contacts/304/photo
12-09 21:15:05.184: D/imageloader(12531): {AssetFileDescriptor: {ParcelFileDescriptor: FileDescriptor[55]} start=0 len=-1}
12-09 21:15:05.184: D/imageloader(12531): FileDescriptor[55]
12-09 21:15:05.184: D/ImageLoader(12531): doInBackground - finished work

Can anybody help me with this problem, please?

A: I had the same problem, and although I do not know what is the problem I found a solution, which works on KitKat & JellyBean (4.2.2). All you have to do is opening the file as an InputStream instead of a AssetFileDescriptor. I used this code:
private Bitmap loadContactPhotoThumbnail(String photoData) {
    InputStream is = null;
    try {
        Uri thumbUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            thumbUri = Uri.parse(photoData);
        } else {
            final Uri contactUri = Uri.withAppendedPath(
                    Contacts.CONTENT_URI, photoData);
            thumbUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY);
        }

        is = getContentResolver().openInputStream(thumbUri);

        if (is != null) {
            return BitmapFactory.decodeStream(is);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

It's the same code that you can find at Display contact badge, the only modification is that it uses InputStream.


text:
Q: p-retry making my test unlaunchable wonder why and how to fix that So my problem is that since I implemented the p-retry lib (retry call api X times you want). On the localhost:3000 work fine but when I launch the tests I got the following return:
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /project/node_modules/p-retry/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import retry from 'retry';
                                                                                ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | import fetch from 'node-fetch';
    > 2 | import pRetry, { AbortError } from 'p-retry';
        | ^
      3 |
      4 | import HttpsProxyAgent from 'https-proxy-agent';
      5 | const proxyAgent = process.env.HTTPS_PROXY

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (services/medVir/http.ts:2:1)

So I guess it's probably an error of config so this is my jest.config.js :
const nextJest = require('next/jest');

const createJestConfig = nextJest({
    // Provide the path to your Next.js app to load next.config.js and .env.local files in your test environment
    dir: './',
});

// Add any custom config to be passed to Jest
const customJestConfig = {
    clearMocks: true,
    collectCoverage: true,
    coverageDirectory: 'coverage',
    coveragePathIgnorePatterns: [
        '/node_modules/',
        '__tests__/utils/',
        '/public/',
    ],
    moduleNameMapper: {
        '\\.(css|less)$': 'identity-obj-proxy',
        '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
            'identity-obj-proxy',
        '^-!svg-react-loader.*$': '<rootDir>/config/jest/svgImportMock.js',
    },
    testEnvironment: 'jsdom',
    testMatch: [
        // "**/__tests__/**/*.[jt]s?(x)",
        '**/?(*.)+(spec|test).[tj]s?(x)',
    ],
    testPathIgnorePatterns: ['/node_modules/', '__tests__/utils/'],
    // transformIgnorePatterns: ['node_modules/(?!(p-retry)/)'],
    verbose: true,
    transform: {
        // Use babel-jest to transpile tests with the next/babel preset
        // https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object
        '^.+\\.(js|jsx|ts|tsx)$': [
            'babel-jest',
            {
                presets: [
                    [
                        '@babel/preset-env',
                        {
                            targets: {
                                node: 'current',
                            },
                        },
                    ],
                    '@babel/preset-typescript',
                    '@babel/preset-react',
                ],
            },
        ],
    },
    setupFiles: ['<rootDir>/.jest/setEnvVars.js'],
    setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
};

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
// module.exports = customJestConfig;
module.exports = createJestConfig(customJestConfig);

I tried a lot of different config and implementation but nothing to do... still the same error so I`m wondering if the problem could be something else.
Something sure since I change axios to node-fetch with p-retry (to handle request and retry then) my tests just stoped to work

A: I come to give you a solution for people which crossing the same problem as me. So I didn't fix the lib or found jest config to handle the weird behavior so I made my own function to do kind of the same thing :

*

*Which is recalling X times the same call api if the timeout is reach

code :
const makeAPICall = async ({
    url,
    body = '',
    method = 'GET',
    type = 'TEXT',
}: IApi) => {
    // init path
    const path = new URL(url);
    const timeout = 28_000;
    let myInit = {
        method,
        timeout,
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        },
    };
    if (method !== 'GET') myInit = { ...myInit, ...{ body: body } };
    const res = await fetch(path.href, myInit);
    switch (type) {
        case 'TEXT':
            return res.text();
        default:
            return res.json();
    }
};

const sleep = (ms: number) =>
    new Promise((resolve) => setTimeout(() => resolve(), ms));

const makeApiRetry: any = async (args: IArgs, retries = 3, old_n = 0) => {
    let n = old_n;

    return makeAPICall(args).catch(async () => {
        if (n < retries) {
            n++;
            // console.log('Retrying request', n, `waiting ${1000 * n} `, args.url);
            await sleep(1000 * (n + 1));
            return makeApiRetry(args, retries, n);
        } else {
            return Promise.reject('Too many retries : error timeout');
        }
    });
};

// Get node-fectch
export const getApiRoute = async (body: string) =>
    await makeApiRetry({
        url: `/apiRoute`,
        body,
        method: 'GET',
        type: 'JSON',
    });


text:
Q: Numpy - Reading a csv file with string header and row names I'm starting to learn using Numpy and I have this CSV table:
,August,September,October,November,December,January
Johny,84,81.3,82.8,80.1,77.4,75.2
Dave,79.6,75.2,75,74.3,72.8,71.4
Ali,67.5,66.5,65.3,65.9,65.6,64
Bob,110.7,108.2,104.1,101,98.3,95.5

I have to get the raw numbers in an array and also the months and names as array of strings in a list.
I managed the first one but struggle finding the right way for the other two.
My code:
def load_training_data(filename):
    data = np.genfromtxt(filename, delimiter=',',skip_header=1)
    data = data[:, 1:]
    column_names = np.asarray(np.genfromtxt(open(filename),delimiter=",",dtype=None)[:1])
    column_names = column_names.dtype.names
    row_names = np.array(filename)
    return data,column_names,row_names

A: You can use numpy.genfromtxt(...,skip_header=0) to retrieve data from the csv file. However, the strings will be formatted to type numpy.bytes_, so you need to convert that to string using decode('UTF-8') function.
def load_training_data(filename):
    data = np.genfromtxt(filename, delimiter=",", skip_header=0, dtype=None)
    column_names = [name.decode('UTF-8') for name in data[0,:]][1:]
    person_names = [name.decode('UTF-8') for name in data[:,0]][1:]
    return data[1:,1:].astype(float), column_names, person_names


text:
Q: readonly array union cannot be searched I want to search an element inside an readonly array union
const areas = {
  area1: {
    adjacencies: [2, 3, 4, 5]
  },
  area2: {
    adjacencies: [6, 7, 8]
  }
} as const;
let area: keyof typeof areas;
if (Math.random() < 0.5) {
  area = "area1";
} else {
  area = "area2"
}

// Argument of type 'number' is not assignable to parameter of type 'never'
areas[area].adjacencies.includes(3);

I also tried indexOf, but it didn't work either. And I found the includes type is ReadonlyArray<T>.includes(searchElement: never, fromIndex: number | undefined): boolean .
I suppose the includes type should be the union of the elements of two readonly array, just like below:
const areas = {
  area1: {
    adjacencies: [2, 3, 4, 5]
  },
  area2: {
    adjacencies: [6, 7, 8]
  }
} as const;

type ValueOf<T extends object> = T[keyof T];
type Values = ValueOf<ValueOf<typeof areas>>
type ElementUnion = Values[number];

let area: keyof typeof areas;
if (Math.random() < 0.5) {
  area = "area1";
} else {
  area = "area2"
}

areas[area].adjacencies.includes(3);

How can I apply ElementUnion to includes or indexOf??
Here is the playground

A: When you do as const you tell typescript "even if encounter a literal like 0 or "hello", rather than inferring it as a general number or string, infer it literally".
So unless both of the arrays has the element you search for, it wont work.
const areas = {
  area1: {
    adjacencies: [2, 3, 4, 5]
  },
  area2: {
    adjacencies: [6, 7, 8, 3]
  }
} as const;

type ValueOf<T extends object> = T[keyof T];
type Values = ValueOf<ValueOf<typeof areas>>
type ElementUnion = Values[number];

let area: keyof typeof areas;
if (Math.random() < 0.5) {
  area = "area1";
} else {
  area = "area2"
}

areas[area].adjacencies.includes(3);

Notice how I added a 3 to the second array.
Playground
Edit:
Look at the signature of the function, only the union of the arrays can be passed to it.
(method) ReadonlyArray<T>.includes(searchElement: 3, fromIndex: number | undefined): boolean

Edit 2:
Example:
const areas = {
  area1: {
    adjacencies: [2, 3, 4, 5]
  },
  area2: {
    adjacencies: [6, 7, 8]
  }
} as const;

type ValueOf<T extends object> = T[keyof T];
type Values = ValueOf<ValueOf<typeof areas>>
type ElementUnion = Values[number];

let area: keyof typeof areas;

if (Math.random() < 0.5) {
  area = "area1";
} else {
  area = "area2"
}

// uh oh, .adjacencies can be either one of the arrays
// if the variable was declared without as const, the function would accept a number
// however since that it not the case, typescript takes the intersection
// (elements present in both arrays) as literal arguments
areas[area].adjacencies.includes(3);

///////////////////////////////////////////////////////////////
if (area === 'area1') {
  // here typescript knows what the elements are
  // but since the variable was declared as const, only literal values
  // that are in the array can be passed to the function
  //                          v Hover over this
  areas[area].adjacencies.includes(2);
} else {
  //                          v Hover over this
  areas[area].adjacencies.includes(6);
}

// Direct access
//                         v Hover over this
areas.area1.adjacencies.includes(2);
//                         v Hover over this
areas.area2.adjacencies.includes(6);
//                         v Hover over this
areas['area1'].adjacencies.includes(2)
//                         v Hover over this
areas['area2'].adjacencies.includes(6)

View in playground for hovers
Playground

A: Thanks for @zerkms mentioning of https://stackoverflow.com/a/53035048/251311, there seems to be two workarounds.
const areas = {
  area1: {
    adjacencies: [2, 3, 4, 5]
  },
  area2: {
    adjacencies: [6, 7, 8]
  }
} as const;

type ValueOf<T extends object> = T[keyof T];
type Values = ValueOf<ValueOf<typeof areas>>
type ElementUnion = Values[number];

let area: keyof typeof areas;
if (Math.random() < 0.5) {
  area = "area1";
} else {
  area = "area2"
}

// first solution using type assertion
(areas[area].adjacencies as unknown as ElementUnion[]).includes(3); // works!

// second solution attempting using declaration merging
// from lib.es2016.array.include.d.ts, which I thick is quite ok
interface ReadonlyArray<T> {
  includes<T>(searchElement: T, fromIndex?: number): boolean;
}

areas[area].adjacencies is of type readonly [2, 3, 4, 5] | readonly [6, 7, 8], which should be equivalent of ReadonlyArray<2 | 3 | 4 | 5 | 6 | 7 | 8>, and I made an experiment
const readonlyArr = [1, 2, 3] as const;
readonlyArr.includes(3); // typescript successfully inferred T is 1 | 2 | 3

It seems like typescript is not able to convert union of readonly array to union of array members, which may be on purpose or not


text:
Q: ASP.NET Core 5 MVC and Identity in EF Core - resource based authorization I have a project for learning purposes. I want to implement resource-based authorization for the users. I have developed a protected method UserId() in the controller, which I call on the get and post methods, Something like the code shown below.
I just wanted to ask, is this solution okay or there is even a better way to do this using the Identity framework, any ideas are very much welcomed :)
// protected UserId method
protected string UserId()
{
    return User.FindFirstValue(ClaimTypes.NameIdentifier);
}

// GET view for categories, here I call the UserId method to check if items for that user exist.
public IActionResult Index()
{
    List<Category> model = _categoryService.GetCategories().Where(x => UserId().Contains(x.UserId)).ToList();
    return View(model);
}

// POST method for category
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Category category)
{
    if (ModelState.IsValid)
    {
        category.UserId = UserId();
        _categoryService.CreateCategory(category);
        return RedirectToAction("Index");
    }

    return View(category);
}

// my Category model
public class Category
{
    [Key]
    public int ID { get; set; }

    public string Name { get; set; }
    public string UserId { get; set; }
}

A: In my opinion, this solution is the best one. The FindFirstValue method is directly find the claims according to the claimType.
This will just search the value inside the claims(in the server memory), it will not contact the sql server.


text:
Q: Forcing bazel _not_ to statically embed external dependencies? I'm investigating the use of bazel to build some of my software. Unfortunately, I think I've come across a show-stopping issue, which is that bazel binaries can't be packaged for distributions like Debian.
The issue is that bazel is very keen on downloading external dependencies as source code and then compiling and linking them into the resulting binary. The protobuf libraries are an example of this. This is strictly forbidden for most Linux (and other) distributions; legally packaged binaries need to link to the system libraries rather than embedding their own copies.
I suspect there's no easy fix for this and that I'll just have to give up on bazel, but on the off-chance that anyone's thought about this: is there one? I think this would need something like the ability to prevent certain external dependencies being fetched, instead replacing them with local placeholder copies. For example, for the protobuf case I'd need to make sure that somehow tell bazel that any attempt to download com_github_protocolbuffers_protobuf should instead use a local version I had made which used the system library. Of course, this would also require telling bazel to ignore the hash, which is terrible...


text:
Q: flutter : unable to forward BluetoothDevice to next page I try to connect to a bluetooth device, I manage to list and retrieve the addresses.
Thanks to a button, I want to go to a next page and transfer the information of the selected bluetooth device. But when I print I get an error message:
'print' must have a method body because '_HomeappiState' isn't abstract.
Try making '_HomeappiState' abstract, or adding a body to 'print'.

I used the same type of constructor but it doesn't work.
Error message and unable to retrieve variable. I tried to transfer just a String but without success.
I go well to the second page when I do not transfer data
Here is the code for my button :
 onTap: () {
          Navigator.of(context).push(MaterialPageRoute(
              builder: (context) => Homeappi(serverlist: serverlist)));
        },

Code of the page that receives the variable:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';

class Homeappi extends StatefulWidget {
  final BluetoothDevice serverlist;
  const Homeappi({Key? key, required this.serverlist}) : super(key: key);

  @override
  _HomeappiState createState() => _HomeappiState();
}

class _HomeappiState extends State<Homeappi> {
  print(serverlist);
  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    return Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Colors.transparent,
        appBar: AppBar(
          title: const Text('Connexion'),
          backgroundColor: Colors.transparent,
          elevation: 0.0,
        ),
        body: Container(
            alignment: Alignment.topCenter,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Colors.blue,
                  Colors.greenAccent.shade400,
                  Colors.blue,
                ],
              ),
            ),
            child: const Text('Test Test')));
  }
}

I can't find my mistake
thank you

A: You can't use print without a method.
I suggest create an initState method and when compiler reach Homeappi the print will work.
Do like this:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';

class Homeappi extends StatefulWidget {
  final BluetoothDevice serverlist;
  const Homeappi({Key? key, required this.serverlist}) : super(key: key);

  @override
  _HomeappiState createState() => _HomeappiState();
}

class _HomeappiState extends State<Homeappi> {

   void initState() {
    // TODO: implement initState
    super.initState();
    print(widget.serverlist); // instead of print(serverlist)
  }
  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    return Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Colors.transparent,
        appBar: AppBar(
          title: const Text('Connexion'),
          backgroundColor: Colors.transparent,
          elevation: 0.0,
        ),
        body: Container(
            alignment: Alignment.topCenter,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Colors.blue,
                  Colors.greenAccent.shade400,
                  Colors.blue,
                ],
              ),
            ),
            child: const Text('Test Test')));
  }
}


text:
Q: Updating GUI: Runnables vs Messages To update the GUI from other threads, there are basically two main approaches:

*

*Use java.lang.Runnable with any of these methods:
Activity.runOnUiThread(Runnable)
View.post(Runnable)
View.postDelayed(Runnable, long)
Handler.post(Runnable)

*Use android.os.Message:
Handler.sendMessage(Message) / Handler.handleMessage(Message)

You can also use AsyncTask, but my question is more focused on the use case of updating a very simple component. Let's see how it would be done using both approaches:

*

*Using Runnables:
TextViev tv = ...;
final String data = "hello";
Runnable r = new Runnable() {

    @Override
    public void run(){
        tv.setText(data);
    }

};
//Now call Activity.runOnUiThread(r) or handler.post(r), ...

*Using messages:
Message m = handler.obtainMessage(UPDATE_TEXT_VIEW, "hello");
handler.sendMessage(m);

//Now on handler implementation:
    @Override
    public void handleMessage(Message msg) {
        if(msg.what == UPDATE_TEXT_VIEW){
            String s = (String) msg.obj;
            tv.setText(data);
        } ... //other IFs?
    }

IMHO, Messages are not the way to go because:

*

*Not easy to understand for new non-android programmers (handler hooks to its thread during construction).

*Object payload should be Parcellable if the message crosses process boundaries.

*Messages are reused (error prone if not properly cleaned up?)

*The handler has a dual role (it sends messages, but also handles them)

*Message attributes are public, but also offer getter/setter.

On the other hand, Runnables follow the well known command pattern, and are more programmer-friendly and readable.
So what are the advantages of using Messages over Runnables? Are Messages pushed into the background in modern day Android programming? Is there anything you can do with Messages that can't be done with Runnables?
Thanks in advance.

A: Handler interface provides much more functionality than runOnUiThread(), according to docs:

There are two main uses for a Handler:
  (1) to schedule messages and runnables to be executed as some point in the future
  (2) to enqueue an action to be performed on a different thread than your own.

runOnUiThread does only a subset of (2). ie "enqueue an action to be performed on UI thread"
So IMO unless you need those extra features runOnUiThread is sufficient and preferred way.

A: I prefer Runnable to Message. I think code using Runnable is much clearer than Message, because the event handling code is very close to the event. Also, You can avoid the overhead of defining constants and switch cases.
And I don't think using Runnable violates encapsulation. You can extract the code in Runnable.run() into another method in the outer class, for example on...Event(), or even wrap it into an EventHandler object. Both ways are much clearer than using Message, especially when you need store references in Message, because using Runnable avoids downcasting msg.obj. And the nameless field msg.obj is also error prone and sometimes inefficient to understand.
And Runnable can also be reused by storing it as a field.

A: I would say there is little difference between using a Message vs a Runnable. It'll mostly boil down to personal preference. Why? Looking at the source code you'll find that posting a Runnable uses the same exact messaging mechanism. It simply attaches the Runnable to a Message and sends that.
4.4.2 Source Code
public final boolean post(Runnable r) {
    return  sendMessageDelayed(getPostMessage(r), 0);
}

private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}

Ref: Grep Code - Handler

A: Messages can be reused, so it results in fewer objects created and less GC. You also end up with fewer classes and anonymous types.
One big advantage is that a class sending a Message to a Handler doesn't need to know anything about the implementation of that Message. That can aid in encapsulation depending on where it's used.
Lastly consider the difference in cleanliness between
mHandler.obtainMessage(DO_STUFF, foo).sendToTarget();

vs
final Foo tempFoo = foo;
mHandler.post(new Runnable(){
    @Override
    public void run(){
        doStuff(tempFoo);
    }
};

If you have several places where you would have to doStuff(), the former is MUCH more readable and you'll have less code duplication.


text:
Q: Step down transformer for a 1 HP Kitchenaid mixer Hoping I can get some feedback here. I've been bought a really nice Kitchenaid mixer (110v/60hz) from the US as a gift...However, I live in South Africa where the voltage/frequency is 220-240v/50hz.
The mixer has a 1 HP DC motor, and based on my limited research this equates to 746 watts (although this site claims the output power is really 350 watts).
I'm going to purchase a step down transformer, but considering they are already hefty beasts, I'd prefer to get the smallest one possible for the job. I've read one should allow for roughly a 20% buffer for appliances with motors, so I'm thinking that a 1000w 220v-110v transformer should be good enough.
Is anyone able to confirm if this should be safe or are there other things I should consider? Thanks.

A: There are two types of transformer (amongst the other types).
You can buy an isolating transformer, the sort that's used for most applications. As the name suggests, these have a mains winding, and a secondary winding, with no electrical connection between the two.
Or you can buy a non-isolating auto transformer. This shares a winding between input and output. While a no-no for applications needing isolation, powering appliances that are designed to be direct connected to the mains is just fine. Because it shares a winding, it's about 50% lighter and smaller (but I doubt as much as 50% cheaper) than an equivalently rated isolating transformer.
What size to get?
If you assume that 350watt rating is the output power of the motor, then it sounds quite reasonable that 1HP (~750 watts) could be the input power.
So 750 watts is a safe size to go for.
However, transformers can be overloaded for a while, and if turned off before they get too hot, that's OK. Does the mixer draw full power all the time, or only when making ground beef? Take those two together, and you may get away with a lower rated transformer that you use intermittently, and keep an eye on the temperature.


text:
Q: Show element on hover of different element I'm trying to create an interactive map, in which a group of people's locations is shown on the map permanently, and on hover of these location indicators, a table appears giving 4 pieces of information on that particular person.
I've created two elements to represent the location and the information table respectively, and am now trying to make one of these elements appear on hover of the other one.
Please see fiddle below:
https://jsfiddle.net/8ymdmzv1/
I have browsed the site, and found various methods including changing the opacity with css and showing/hiding with jquery (see below for suggestions found - I have reset the the element styling in the current fiddle) but without joy. Problem seems to be linking the two elements together but after a full afternoon.
.dot:hover + .info { opacity: 1 }
.dot:hover > .info { opacity: 1 }
.dot:hover .info { opacity: 1 }

$(".dot").hover(function() {
   $('.info').show();
   }, function(){
$('.info').hide();
});

My first real project for fun so would appreciate anyones assistance on getting me past this roadblock.
Cheers!

A: In your code you have:
// create info table
var info = document.createElement( 'a' );
info.className = 'info';
holder.appendChild( info );

// create fixed dot
var dot = document.createElement( 'a' );
dot.className = 'dot';
holder.appendChild( dot );

So .info element goes before .dot and .dot:hover + .info selector not worknig.
It works, if you can reorder elements to this:
// create fixed dot
var dot = document.createElement( 'a' );
dot.className = 'dot';
holder.appendChild( dot );

// create info table
var info = document.createElement( 'a' );
info.className = 'info';
holder.appendChild( info );

It is probably better to hide/show elements with display property in your case. So, you can do something like this in your css:
.info { display: none; } /* Hide .info by default */
.dot:hover + .info { display: block; } /* Show .info, if .dot hovered */
.info:hover { display: block; } /* And stays visible, while .info hovered itself */


text:
Q: Wordpress Help on post I'm having a bit of a problem I have created a post and it shows on my blog but as soon as you click on the title link it says "Sorry, no posts were found." and even in the homepage where the recent post doesn't work.

A: Sounds like a permalink issue. If you turned on "pretty" urls, make sure you've created the appropriate .htaccess file. Once you edit your permalink structure, WP  will generate the contents you need to put inside your htaccess file. Copy the contents, paste inside a file, save it as .htaccess and upload to your blog root folder.


text:
Q: What resources do folks use for learning about Xcode templates? I do a lot of prototyping and need more Xcode templates for the different classes of apps that I prototype. My current source of information for Xcode templates is a set of links from the web. What other resources do folks use for Xcode iPhone templates design and development?

A: there are several resources on the web as you pointed out.
One of the most important things that I use are the Xcode Templates Expansion Macros, this are heavily used in Apple's templates, and can make your templates a lot better. Here's a great tutorial and table that shows all the Xcode Template Macros and some ideas of how to use them.
You seem to have several pointers in your links to how to actually make the template, so I think this would be helpful for you.


text:
Q: Able to find path using DFS but not able specify the right directions to Pacman _ Python I am working on an assignment found on an AI course page at berkley website for fun. I need to write a depth-first search for the pacman game so that it can find its path.The problem is the pacman gets stuck. I'll paste the code first to make what I am saying more clear :
import util

class SearchProblem:
  """
  This class outlines the structure of a search problem, but doesn't implement
  any of the methods (in object-oriented terminology: an abstract class).

  You do not need to change anything in this class, ever.
  """

  def getStartState(self):
     """
     Returns the start state for the search problem
     """
     util.raiseNotDefined()

  def isGoalState(self, state):
     """
       state: Search state

     Returns True if and only if the state is a valid goal state
     """
     util.raiseNotDefined()

  def getSuccessors(self, state):
     """
       state: Search state

     For a given state, this should return a list of triples,
     (successor, action, stepCost), where 'successor' is a
     successor to the current state, 'action' is the action
     required to get there, and 'stepCost' is the incremental
     cost of expanding to that successor
     """
     util.raiseNotDefined()

  def getCostOfActions(self, actions):
     """
          actions: A list of actions to take

     This method returns the total cost of a particular sequence of actions.  The sequence must
     be composed of legal moves
     """
     util.raiseNotDefined()

def tinyMazeSearch(problem):
  """
      Returns a sequence of moves that solves tinyMaze.  For any other
  maze, the sequence of moves will be incorrect, so only use this for tinyMaze
  """
  from game import Directions
  s = Directions.SOUTH
  w = Directions.WEST
  return  [s,s,w,s,w,w,s,w]

def depthFirstSearch(problem):

  """
  Search the deepest nodes in the search tree first [p 74].

  Your search algorithm needs to return a list of actions that reaches
  the goal.  Make sure to implement a graph search algorithm [Fig. 3.18].

  To get started, you might want to try some of these simple commands to
  understand the search problem that is being passed in:

  print 'Start:', problem.getStartState()
  print 'Is the start a goal?', problem.isGoalState(problem.getStartState())
  print 'Start's successors:', problem.getSuccessors(problem.getStartState())

  """

  # *** YOUR CODE HERE ***

  start = [problem.getStartState()]
  for item in start:
      Open=[item]
  State=[]
  Closed=[]
  Path=[]

  if problem.isGoalState(Open[0]) is True:
      return State
  else:
       while Open:
                visit= Open.pop()
                Closed.append(visit)
                if State:
                  Path.append(State.pop())

                if problem.isGoalState(visit) is True:
                    print Closed
                    return Path
                else:
                    Successors= problem.getSuccessors(visit)
                    for index in Successors:
                            it=iter(index)
                            data=it.next()

                            if data not in Closed :
                              Open.append(data)
                              State.append(it.next())
                            else:
                              print Path

Now if you will read my code under dfs you will see that open list contains all the points I visit and expanded.
The Path file contains the direction set for the pacman. The problem arises when I face the condition that both successors I get are unvisited, my pacman takes a path which leads to a dead end so it needs to backtrace. My Open does it and finds the solution but I am not able to find a way on how to provide the directions of backtracing in my path list. If you will go to http://inst.eecs.berkeley.edu/~cs188/sp09/projects/search/search.html and download the zip and paste my code in search.py under dfs search you will understand my problem.

A: Some hints:

*

*Each node you check should encapsulate the data of how you got there.

*DFS is like a stack; you start by pushing the start state. You pop the stack, and push back the nodes that can follow from the node you popped.

*Since you are ultimately trying to find a path, the node data must hold your location and the path you took to get there.

A: How you store your path is a VERY important topic, when you consider that some of your searches might result in paths 200+ steps long. Iterating over a list that many times.... O(2^N) or O(3^N)? lists for any kind of search as a path storing mechanism are the wrong answer, especially when you get into BFS and any time you have multiple objectives (meaning, multiple paths through the same node can exist). List complexity and the data storage is ridiculous.
I recommend linklisting as a path storage mechanism. When you push your nodes into the fringe, simply key them into a dictionary with a unique key and push the key. Then when you pull a node from the fringe, you can get the entire state, as is, from the dictionary.
If part of your state is the node that that state was in one step previously, then you have a path to the start; the end node links to the one behind it, which links to the one behind it, etc. Using a unique key system like this allows multiple paths through the same point, at EXTREMELY low data cost; you still must be rational about which paths you pull off the fringe. However, any time you pull anything off the fringe, you pull it's entire path, with only 1 number.

A: I did get it work by making sure each move is only 1 distance. One of the issue with your code was at the end it try to jump 5 or 6 places. Make sure every move it make is one and reverse till move distance become 1 to your next destination. Hint manhattanDistance().

A:  start = [problem.getStartState()]
  for item in start:
      Open=[item]
  Closed=[]
  Path=[]

  if problem.isGoalState(Open[0]) is True:
      return
  else:
       count=0
       while Open:
                if count==0:
                  visit=Open.pop()
                else:
                  temp=Open.pop()
                  visit=temp[0]

                Closed.append(visit)
                if problem.isGoalState(visit) is True:
                    return Path
                else:
                    Successors= problem.getSuccessors(visit)
                    for index in Successors:
                            if index[0] not in Closed :
                              Open.append((index[0],index[1]))
                print Open
                count=count+1

i changed the code as u said. right now i am not having anything in path.
this open after finding the solution -( 1,1 is the solution)
[((5, 4), 'South'), ((4, 5), 'West')]
[((5, 4), 'South'), ((3, 5), 'West')]
[((5, 4), 'South'), ((2, 5), 'West')]
[((5, 4), 'South'), ((1, 5), 'West')]
[((5, 4), 'South'), ((1, 4), 'South')]
[((5, 4), 'South'), ((1, 3), 'South')]
[((5, 4), 'South'), ((2, 3), 'East')]
[((5, 4), 'South'), ((2, 2), 'South')]
[((5, 4), 'South'), ((2, 1), 'South'), ((3, 2), 'East')]
[((5, 4), 'South'), ((2, 1), 'South'), ((4, 2), 'East')]
[((5, 4), 'South'), ((2, 1), 'South'), ((4, 3), 'North')]
[((5, 4), 'South'), ((2, 1), 'South'), ((5, 3), 'East')]
[((5, 4), 'South'), ((2, 1), 'South'), ((5, 4), 'North')]
[((5, 4), 'South'), ((2, 1), 'South')]
[((5, 4), 'South'), ((1, 1), 'West')]

now if you will notice when it gets three list members it takes a path which was a dead end now the Open is able to backtrace and find the correct path but i need a way to somewhow specify the return direction in the Path variable like
for eg Path = ['south',west' west'.................] etc


text:
Q: Linux kernel: Unlocking an unlocked mutex I am trying to understand the "unlocking an unlocked mutex" is not allowed will lead to unpredictable behavior w.r.t Linux kernel mutex, when i look at the code i do not see anything to this effect.
Specifically:
/**
 * try to promote the mutex from 0 to 1. if it wasn't 0, call <function>
 * In the failure case, this function is allowed to either set the value to
 * 1, or to set it to a value lower than one.
 * If the implementation sets it to a value of lower than one, the
 * __mutex_slowpath_needs_to_unlock() macro needs to return 1, it needs
 * to return 0 otherwise.
 */
static inline void
__mutex_fastpath_unlock(atomic_t *count, void (*fail_fn)(atomic_t *))
{
    if (unlikely(atomic_xchg(count, 1) != 0))
        fail_fn(count);
}

where fail_fn is
static inline void
__mutex_unlock_common_slowpath(atomic_t *lock_count, int nested)
{
    struct mutex *lock = container_of(lock_count, struct mutex, count);
    unsigned long flags;

    spin_lock_mutex(&lock->wait_lock, flags);
    mutex_release(&lock->dep_map, nested, _RET_IP_);
    debug_mutex_unlock(lock);

    /*
     * some architectures leave the lock unlocked in the fastpath failure
     * case, others need to leave it locked. In the later case we have to
     * unlock it here
     */
    if (__mutex_slowpath_needs_to_unlock())
        atomic_set(&lock->count, 1);

    if (!list_empty(&lock->wait_list)) {
        /* get the first entry from the wait-list: */
        struct mutex_waiter *waiter =
                list_entry(lock->wait_list.next,
                       struct mutex_waiter, list);

        debug_mutex_wake_waiter(lock, waiter);

        wake_up_process(waiter->task);
    }

    spin_unlock_mutex(&lock->wait_lock, flags);
}

From what i can tell if it is unlocked it will remain unlocked regardless of what __mutex_slowpath_needs_to_unlock() is, am i missing something here?

A: As suggested by Wyzard, the documentation may want to keep some ways open. For example, some other implementations can use atomic increment instead of the exchange, like this one:
static inline void __mutex_fastpath_unlock(atomic_t *v,
                                           void (*fail_fn)(atomic_t *))
{
        asm_volatile_goto(LOCK_PREFIX "   incl %0\n"
                          "   jg %l[exit]\n"
                          : : "m" (v->counter)
                          : "memory", "cc"
                          : exit);

As you can see, it is not safe to call it twice in a row since accompanying try_lock does not expect any other values except 0 and 1:
static inline int __mutex_fastpath_trylock(atomic_t *count,
                                           int (*fail_fn)(atomic_t *))
{
        if (likely(atomic_cmpxchg(count, 1, 0) == 1))