text:
Q: Clean out repository indexes on 16.04 How do i clear out my repo indexes completely, start from scratch etc.
I have a lot of bad or old indexes that I'd like to clean up

W: Failed to fetch http://archive.linux.duke.edu/ubuntu/dists/saucy/restricted/binary-amd64/Packages  404  Not Found
W: Failed to fetch http://archive.linux.duke.edu/ubuntu/dists/saucy/multiverse/binary-amd64/Packages  404  Not Found
W: Failed to fetch http://archive.linux.duke.edu/ubuntu/dists/saucy-updates/main/binary-amd64/Packages  404  Not Found
W: Failed to fetch http://archive.linux.duke.edu/ubuntu/dists/saucy-updates/universe/binary-amd64/Packages  404  Not Found
W: Failed to fetch http://archive.linux.duke.edu/ubuntu/dists/saucy-updates/restricted/binary-amd64/Packages  404  Not Found
W: Failed to fetch http://archive.linux.duke.edu/ubuntu/dists/saucy-updates/multiverse/binary-amd64/Packages  404  Not Found to re
E: Some index files failed to download. They have been ignored, or old ones used instead.

ubuntu@ubuntu:/usr$ sudo add-apt-repository ppa:webupd8team/jupiter
Cannot add PPA: 'ppa:webupd8team/jupiter'.
Please check that the PPA name or format is correct.

I do know how to remove repo's from the command line

A: Simply edit your /etc/apt/sources.list for normal repositories. PPA entries you can find in /etc/apt/sources.list.d/. Simply edit with sudo nano.
Or you can use banish404 which you can find in the official repositories:
sudo apt-get install banish404 gksu

And starting it with:
gksudo banish404


text:
Q: Phaser Tetris Clone, line won't disappear when full I'm making a game that is part Tetris clone, but I'm having trouble making lines disappear once their full of blocks. The game currently has 11 rows that can be filled, each represented by an array of sprites that is made in the create method.
this.row1 = [null, null, null, null, null, null, null, null, null, null];
this.row2 = [null, null, null, null, null, null, null, null, null, null];
this.row3 = [null, null, null, null, null, null, null, null, null, null];
this.row4 = [null, null, null, null, null, null, null, null, null, null];
this.row5 = [null, null, null, null, null, null, null, null, null, null];
this.row6 = [null, null, null, null, null, null, null, null, null, null];
this.row7 = [null, null, null, null, null, null, null, null, null, null];
this.row8 = [null, null, null, null, null, null, null, null, null, null];
this.row9 = [null, null, null, null, null, null, null, null, null, null];
this.row10 = [null, null, null, null, null, null, null, null, null, null];
this.row11 = [null, null, null, null, null, null, null, null, null, null];

I'm only trying to get the bottom row, row1, working before working on the others. I have the array filled when blocks land with this code in the update method:
if (this.activeBlock.y == 672){
    if(this.activeBlock.x == 352){
        this.row1[0] = this.activeBlock;
    }
    else if(this.activeBlock.x == 416){
        this.row1[1] = this.activeBlock;
    }
    else if(this.activeBlock.x == 480){
        this.row1[2] = this.activeBlock;
    }
    else if(this.activeBlock.x == 544){
        this.row1[3] = this.activeBlock;
    }
    else if(this.activeBlock.x == 608){
        this.row1[4] = this.activeBlock;
    }
    else if(this.activeBlock.x == 672){
        this.row1[5] = this.activeBlock;
    }
    else if(this.activeBlock.x == 736){
        this.row1[6] = this.activeBlock;
    }
    else if(this.activeBlock.x == 800){
        this.row1[7] = this.activeBlock;
    }
    else if(this.activeBlock.x == 864){
        this.row1[8] = this.activeBlock;
    }
    else if(this.activeBlock.x == 928){
        this.row1[9] = this.activeBlock;
    }

When the bottom row is full, this code is triggered to clear it and mover everything above down:
 if (this.isFull(this.row1)){
    this.clearRow(this.row1);
    this.moveDown(this.row1, this.row2);
    this.moveDown(this.row2, this.row3);
    this.moveDown(this.row3, this.row4);
    this.moveDown(this.row4, this.row5);
    this.moveDown(this.row5, this.row6);
    this.moveDown(this.row6, this.row7);
    this.moveDown(this.row7, this.row8);
    this.moveDown(this.row8, this.row9);
    this.moveDown(this.row9, this.row10);
    this.moveDown(this.row10, this.row11);
}

And these are the custom methods I'm using to perform that last part:
isFull(row){
this.result = true;
this.i = 0;
while(this.i < row.length){
    if (row[this.i] == null){
        this.result = false;
    }
    this.i = this.i + 1;
}
return this.result;
}

clearRow(row){
    this.i = 0;
    while(this.i < row.length){
        row[this.i].destroy();
        row[this.i] = null;
    }
}

moveDown(bottRow, topRow){
    this.i = 0;
    while(this.i < bottRow.length()){
        topRow[this.i] = topRow[this.i].y + 64;
        bottRow[this.i] = topRow[this.i];
        topRow[this.i] = null;
        this.i = this.i + 1;
    }
}

For the most part, the code seems to be working, but the game freezes when the bottom row is full, and when checking the inspect screen for errors, it pointed to the destroy() in the clearRow(row) method. The error message reads: Cannot read properties of null (reading 'destroy')
I'm not sure what's wrong. Can anyone tell?
If it helps, I'm using Phaser 3 in VSCode employing arcade physics.

A: You never increment i in your loop, so after you set row[0] to null, you then try to access it again next time through the loop. Make clearRow more like your isFull function. So it's:
clearRow(row){
    this.i = 0;
    while(this.i < row.length){
        row[this.i].destroy();
        row[this.i] = null;
        this.i = this.i + 1; // Add this line
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: user input string with arraylist How do I Compare user input string to array list then remove user string letters from the arraylist here's my code:
I want to get user input as string e.g Apple then I want to remove the letters "a" "p" "l" "e" from the arraylist.
public static void playgame() {

    ArrayList<String> obj = new ArrayList<String>(
    Arrays.asList("a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z"));

        while(!obj.isEmpty()) {

            System.out.println(name1 + " enter your word:");
            String word1 = reader.nextLine().toLowerCase();
            System.out.println("Enter (y) yes if both players agree on the word and (n) no word is incorrect");
            String y = reader.next();

            String yes = "y";
            String no = "n";

            if(y.equals(yes)) {

                countScore1++;
                char[] wordToString = word1.toCharArray();

                System.out.println(wordToString.length);

                for(int i=0;i<wordToString.length;i++) {

                    String output=Character.toString(wordToString[i]);

                    System.out.println(output);

                        if(obj.contains(output)){
                            obj.remove(output);
                        }
                }
                System.out.println("Alphabet letters left:" + obj);
                System.out.println("Correct word #######");
            }

A: See Andy Turner's message about single string. In practice, replace
ArrayList<String> obj = new ArrayList<String>(
Arrays.asList("a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z"));

for example with this
List<String> obj = new ArrayList<String>();
for(char c = 'a'; c <= 'z'; c++) {
    obj.add(String.valueOf(c));
}

However, I would use HashSet instead of ArrayList. I guess HashSet has faster lookup algorithm when looking for the item to remove.
Set<String> obj = new HashSet<String>();
for(char c = 'a'; c <= 'z'; c++) {
    obj.add(String.valueOf(c));
}


text:
Q: Fuse keeps blowing on AC/DC Adapter Recently I have noticed high freq. screeching noise coming out from my laptop's adaptor. I opened it up and found that it came from somewhere around a diode named egp10a. I checked it (unplugged) with a multimeter disoldering only one end and saw that it works fine (no reverse voltage leak detected).
Later, I wanted to power the board without soldering the cathode to the board to see if the noise really caused by this diode. As I plugged the adapter the fuse blew and gave that burning smell. I found another identical fuse and replaced it and soldered the diode completely back again. Hovewer the new fuse also blew.
As someone who is very keen on learning electronics I would like to know what would be the problem and what I did wrong. I would appreciate if you guys guide me through learning the basics of electronics or share a source where I can learn this stuff.
Update:
I have noticed a new component with a burn mark on it located near the FETs (?). I do not know how it's named.
This adapter is becoming my learning kit now I guess since I consider buying a new adapter.
Do you guys think that the SMD caps under the board close to the diode legs I removed would be the cause of the noise I mentioned before?
Edit & Update 2:

*

*I have replaced components shown in the pictures with the equivalent once (I suppose(!))

****Used 11N60C3 instead of damaged STP11NM60AFP

*With the new parts put together I get no output voltage at all. (Fuse don't blow anymore)

*Do shorted caps might cause this?

*Please refer to the picture below where I get 308v output. Is it normal? (standard for my country is 220v)

Note: The power supply's model is ADP-65YB B and rated as 19V @ 3,42A. (Would it be okay if I used 19V @ 4,74A which I already have lying around?

A: Powering up with a random component removed is a bad idea unless you know its function and understand what will happen without it in the circuit.
It could be part of a clamp that prevented overvoltage damage to your switching FET for example.  So by removing it you could cause damage to other components.  (Which it sounds like you did.)
Diodes don't create noise in power supplies, noise comes primarily from ceramic capacitors and magnetic components.
Without a schematic of you converter, or at least some good photos we won't be able to comment much further.

A: First of all, consider that fiddling with mains voltage can kill you should the discharge go through the heart. SMPS have large caps inside which will keep deadly voltage for hours after you pull the plug. Are you sure you can work safely with it?
If yes, you should check if the hot (high voltage) side of the PSU still works. My guess would be that by removing the diode you cut the power coming from the auxiliary winding to the SMPS IC. That would be D4 in the schematic below (keep in mind it's a reference design, not the schematic of your particular supply). A good PSU should have survived that (providing output voltage for a split second every once in a while), but considering the blown fuse, yours was not as forgiving.
First of all, if the short persists after you have put back the diode, you should localize it. Perhaps you have just accidentally shorted something and the short is already gone, in that case you should see the big 400V cap charging to nominal voltage after power up.

If there's no AC voltage on the transformer, check the gate of the MOSFET: if there's a PWM signal there, the SMPS IC is still alive, and replacing the FET can bring the PSU back to life. If not, you need to replace the IC, and I wouldn't bother trying to repair it.
If you see AC voltage on the transformer's primary but there's nothing on the output, the problem is likely on the cold (low-voltage) side of the schematic.

A: The answer is clear:  Buy a new supply and find something else much simpler to "learn" on.    Switching power supplies are outrageously complex and not something you're gonna be able to wrap your head around without a good understanding of electronic theory.

A: Some additional general comments meant as a complement to what's already posted.

*

*High-frequency 'squealing' noises coming from power supplies generally implies incorrect / abnormal behaviour. Magnetorestriction caused by high pulsed currents (i.e. the power supply hiccupping energy into a shorted part) can cause acoustic noise. When you hear this, DISCONNECT THE INPUT POWER IMMEDIATELY as bad things are bound to happen in short order. (This noise will make the hair of an experienced power-supply designer or repairperson stand on end.)

*The long dashed line on the silkscreen (top to bottom) is a reprentation of the isolation barrier between the mains-connected lethal part of the power supply and the galvanically-isolated non-lethal part. By non-lethal, I mean: if the power supply is working correctly (and designed correctly) on the secondary (isolated) side there should not be sufficient voltage present to produce a shock hazard. The mains side must always be considered lethal and appropriate precautions must be taken: never live-probe, always discharge HV capacitors before handling, etc. The other dashed lines seem to be following the two AC input traces are are likely meant to indicate to the PCB designer to keep separation between them to avoid flashovers.

*Based on the appearance of the power electronics (single transformer, no boost inductor, no output filter inductors) I agree with others that this power supply is a flyback converter with no active PFC - the mains voltage is rectified and the DC voltage is down-converted via a high-frequency (10s to 100s of kHz) flyback converter topology. The primary switch will see high voltage during the off-time of the converter due to the coupled-inductor action of the transformer (energy is stored during the on-time and supplied to the load during the off-time).

*MOSFET replacement only from a datasheet for a switching power supply is a big no-no. You need to carefully consider gate charge, switching loss, avalanche energy handling capability, reverse recovery time and Rds_on among many other parameters, many of which require in-situ measurements to qualify. The datasheet may give you a good starting point, but you really need to take a lot of measurements to be sure. That said, your replacement choice - on paper - looks to me like a good candidate for trials. (I still would not blindly swap it in).

*Bridge rectifier substitution by datasheet is a little bit safer than MOSFET substitution. As long as the diodes are rated for comparable-or-higher current, comparable-or-higher reverse voltage, and have comparable forward voltage drop, it's not unreasonable to try a different bridge. I would still keep an eye on device temperature though.


text:
Q: How to run FragmentBasics sample in Android Studio I'm new to Android development. I am following the tutorial to the Fragment section. I downloaded the FragmentBasics.zip and unzipped it to my drive. In Android Studio 3.0, I imported it as a project but I found under "Android", there is no "App" which I could try to run it. Can someone show me how to try this example please?
Thanks


text:
Q: insert in database using json jquery and php i want to add  data to my database by passing as a json string then using php  what i have done but adds an empty line in the database instead of adding the data that i sent and i get the alert("fail") message  where is the mistake please
here is my save function
function save(){
    var eml = document.getElementById("tbemail").value;
    var mp = document.getElementById("tbmdp").value;
 var data = {email: eml, mdp: mp};
            $.ajax({
            url: "http://localhost:800/test/insert.php",
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                                 alert('success');
                                     },
                error: function () {
                                 alert("fail");
                                   }
        });

and here is my php file insert.php
 <?php
$json = isset($_POST['data']) ? $_POST['data'] : "";
$new=json_decode($json, true);
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$sql = "INSERT INTO user (email,mdp)  VALUES    ('".$new['email']."','".$new['mdp']."') ";
$insert=mysqli_query($conn, $sql);
if ($insert) {
echo "created ";
} else {
echo "Error: " . $sql . "
" . mysqli_error($conn);
}
?>

A: Can you try this:
JS:
function save(){
    var eml = document.getElementById("tbemail").value;
    var mp = document.getElementById("tbmdp").value;
 var data = {email: eml, mdp: mp};
            $.ajax({
            url: "http://localhost:800/test/insert.php",
            type: 'POST',
            dataType: 'json',
            data: data,
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                alert('success');
            },
                error: function () {
                   alert("fail");
            }
        });
 }

PHP Code:
 <?php
$email = isset($_POST['email']) ? $_POST['email'] : "";
$mdp = isset($_POST['mdp']) ? $_POST['mdp'] : "";

$new=json_decode($json, true);
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");

mysqli_select_db($conn,"bd") or die ("no database");

$sql = "INSERT INTO user (email,mdp)  VALUES    ('".$email."','".$mdp."') ";
$insert=mysqli_query($conn, $sql);
if ($insert) {
echo "created ";
} else {
echo "Error: " . $sql . "
" . mysqli_error($conn);
}

?>

A: Get data using this way in PHP
$data = json_decode(file_get_contents('php://input'));
$email =  $data ->email;
$mdp = $data ->mdp;

A: In your PHP, each individual variable that you're passing through (i.e. email and mdp) is passed as individual $_POST data, not into a single $_POST variable called 'data'. Right after your opening PHP tag, check for the email and mdp:
$email = (isset($_POST['email']) ? $_POST['email'] : "");
$mdp = (isset($_POST['mdp']) ? $_POST['mdp'] : "");

$conn= ....

A: You can try this:
 function save(){
        var eml = document.getElementById("tbemail").value;
        var mp = document.getElementById("tbmdp").value;
     var data = {'email': eml,'mdp': mp}; //json
                $.ajax({
                url: "http://localhost:800/test/insert.php",
                type: 'POST',
                dataType: 'json',
                data: data,//pass it here
                contentType: "application/json; charset=utf-8",
                success: function (data) {

                    alert('success');
                },
                    error: function () {

                       alert("fail");

                }

            });

     }

php:
<?php
if(isset($_POST['email'],$_POST['mdp']) {
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");

mysqli_select_db($conn,"bd") or die ("no database");

$sql = "INSERT INTO user (email,mdp)  VALUES    ('".$_POST['email']."','".$_POST['mdp']."') ";
$insert=mysqli_query($conn, $sql);
if ($insert) {
echo "created ";
 } else {
 echo "Error: " . $sql . "
" . mysqli_error($conn);
 }
}

?>

A: try like this,
function save(){
    var eml = document.getElementById("tbemail").value;
    var mp = document.getElementById("tbmdp").value;
 var data = {email: eml, mdp: mp};
            $.ajax({
            url: "http://localhost:800/test/insert.php",
            type: 'POST',
           // dataType: 'json',
            data: {"data":JSON.stringify(data)},
           // contentType: "application/json; charset=utf-8",
            success: function (data) {

                alert('success');
            },
                error: function () {

                   alert("fail");

            }

        });
 }

A: Try this :
function save() {
    var eml = document.getElementById("tbemail").value;
    var mp = document.getElementById("tbmdp").value;
    var data = {email: eml, mdp: mp};
            $.ajax({
                type: 'POST',
                url: "http://localhost:800/test/insert.php",
                //dataType: 'json',
                data: {"data": JSON.stringify(data)},
                //contentType: "application/json; charset=utf-8",
            success: function (data) {
                if (data == 'created')
                    alert('Success');
                else
                    alert('Fail');
            }
        });
 }


text:
Q: Group of k-Algebra Automorphisms over a Polynomial Ring In Commutative Algebra with a View Toward Algebraic Geometry (which I'm clearly not ready for, but anyway...), there's the following example in section 1.3:

Let $S = k[x_1,...,x_r]$ by the polynomial ring, and let $\Sigma$ by
  the symmetric group of all permutations of $\{1,...,r\}$. The group
  $\Sigma$ acts on $S$ as follows: If $\sigma \in \Sigma$ and $f \in S$,
  we define
$$\sigma(f)(x_1,...,x_r) = f(x_{\sigma^{-1}(1)},\dots,x_{\sigma^{-1}(r)}).$$
The group $\Sigma$ acts as a group of $k$-algebra automorphisms of
  $S$.
Blah blah blah more stuff anjruu doesn't understand.

So, I get that $\sigma \in \Sigma$ is an automorphism from $S$ to $S$, since it is injective, and preserves the ring structure.
I also get that $\Sigma$ is a group, since, well, it's based off of the group of permutations.
What I don't get is how $\sigma \in \Sigma$ is a k-algebra. You need to be a module to be a k-algebra (or so I thought), but one of the properties of a module is scalar multiplication, and I don't understand how you would multiply $\sigma$ (what I was thinking of as the vector in this hypothetical module) with an element from $S$ (the scalars).
Can anyone enlighten me as to what's going on?

A: It's not saying that each $\sigma$ is a $k$-algebra, but that each $\sigma$ is an automorphism of $k$-algebras.   That is, in addition to being a ring-homomorphism, each $\sigma$ is also $k$-linear.

A: Recall that the transpositions generate $S_n$, so we lose no generality by merely considering $k[x,y]$. Then $k$-linearity boils down to the fact that:
1.) If we switch independently $x$ and $y$ in two polynomials $f(x,y), g(x,y)$, and then add them, we get the same polynomial as if we added first, then switched $x$ and $y$.
2.) If we switch $x$ and $y$ in a polynomial $f(x,y)$, and then multiply every coefficient by $\alpha \in k$ , we obtain the same polynomial as we do if we multiply every coefficient by $\alpha$ first, and then swap $x$ and $y$.
It is clear that such a map $\sigma$ is bijective, so all we lack for $\sigma$ to be a $k$-algebra automorphism is to show $\sigma$ is multiplicative (which is similar to 1.) above).
In other words, all we are "really" doing with $\sigma$ is indexing "variable-relabeling" by a corresponding "finite-set-shuffling" of the indices of the variables (or indeterminates, more properly speaking). The discussion above indicates we can do this "two indeterminates at a time".


text:
Q: C Adding each char into array For C++ - I can add each char to each index in string array:
   string *x=new string[10];
    x[0] += "a";
    x[0] += "b";
    x[0] += "c";
    x[1] += "x";
    x[1] += "y";
    x[1] += "z";
    cout << "x[0]=" << x[0] << endl; // would be "abc"
    cout << "x[1]=" << x[1] << endl; // would be "xyz"

How can I do same functionality in C? I have buff2 pointer to a char array and am trying to add char value from each index of buf. I keep getting weird values when I print out buff2 value.
char buf[255];
char *buff2;
int i=0, count=0;
buff2=(char*)malloc(512*sizeof(char));

  while((n = read(fd, buf, sizeof(buf[g]))) > 0){
    for(i=0; i<n; i++){
      if(buf[i] == '\n'){
        l++;
        count2++;
      }
       else
     {
       buff2[count2]+=buf[i];
     }
  }

A: There are several problems in your C code

*

*buff is an array for nothing  because you only use buff[0]

*the variable l seems never defined/initialized, and you modify it for nothing

*buff2[count2]+=buf[i]; always modify the same buff2[count2] until a newline because you do not increase buff2 in that case but only when reading a newline, are you sure you want that ?

*you do not end buff2 with a null character, that probably explain I keep getting weird values when I print out buff2 value.

*you do not have a protection in case you write out of buff2 producing an undefined behavior

string *x=new string[10];

can be in C
char ** x = calloc(10, sizeof(char *));

I use calloc to initialize with null pointers
and an equivalent of :

x[0] += "a";

can be
 strCat(&x[0], "a");

with:
char * const strCat(char ** p, const char * s)
{
   if (s != NULL) {
     if (*p == NULL)
       *p = strdup(s);
     else {
       size_t len = strlen(*p);

       *p = realloc(*p, len + strlen(s) + 1); /* may be detect realloc returns NULL on error */
       strcpy(*p + len, s);
     }
   }

   return *p;
}

So for instance :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char * const strCat(char ** p, const char * s)
{
   if (s != NULL) {
     if (*p == NULL)
       *p = strdup(s);
     else {
       size_t len = strlen(*p);

       *p = realloc(*p, len + strlen(s) + 1); /* may be detect realloc returns NULL on error */
       strcpy(*p + len, s);
     }
   }

   return *p;
}

int main()
{
  char ** x = calloc(10, sizeof(char *));

  strCat(&x[0], "a");
  strCat(&x[0], "b");
  strCat(&x[0], "c");

  strCat(&x[1], "x");
  strCat(&x[1], "y");
  strCat(&x[1], "z");

  printf("x[0]=%s\n", x[0]);
  printf("x[1]=%s\n", x[1]);

  free(x[0]);
  free(x[1]);
  free(x);

  return 0;
}

Compilation and execution:
% gcc -Wall a.c
% ./a.out
x[0]=abc
x[1]=xyz
%

Running under valgrind:
% valgrind ./a.out
==113490== Memcheck, a memory error detector
==113490== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==113490== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==113490== Command: ./a.out
==113490==
x[0]=abc
x[1]=xyz
==113490==
==113490== HEAP SUMMARY:
==113490==     in use at exit: 0 bytes in 0 blocks
==113490==   total heap usage: 7 allocs, 7 frees, 98 bytes allocated
==113490==
==113490== All heap blocks were freed -- no leaks are possible
==113490==
==113490== For counts of detected and suppressed errors, rerun with: -v
==113490== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
%

Note however each time you concatenate a new string it is needed to go through the current string to know its length, this is not done by  std::string whose knows the used length whatever the way for that, as this is the case in the answer of KamilCuk

A:
How can I do same functionality in C?

First implement/invent a "string".
After that you can implement the functionality. Remember about proper error handling. I just used abort() for brevity below, in normal code destructors should be run.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct string {
    char *begin;
    char *end;
    size_t free;
} string;
void string_init(string *t) {
   t->begin = t->end = NULL;
   t->free = 0;
}
void string_fini(string *t) {
   free(t->begin);
}
// iadd convention from python
int string_iadd_cstr(string *t, const char *str) {
   const size_t addlen = strlen(str);
   if (t->free < addlen + 1) {
       const size_t curlen = t->end - t->begin;
       const size_t newlen = curlen + 1 + addlen;
       void *tmp = realloc(t->begin, newlen);
       if (tmp == NULL) {
           return -1;
       }
       t->begin = tmp;
       t->end = t->begin + curlen;
       t->free = newlen - curlen;
   }
   memcpy(t->end, str, addlen + 1);
   t->end += addlen;
   t->free -= addlen;
   return 0;
}
int string_print(string *t) {
    return printf("%s", t->begin);
}

int main() {
    // string *x=new string[10];
    string *x = malloc(10 * sizeof(*x));
    if (x == NULL) abort();
    for (size_t i = 0; i < 10; ++i) {
        string_init(&x[i]);
    }

    if (string_iadd_cstr(&x[0], "a")) abort();
    if (string_iadd_cstr(&x[0], "b")) abort();
    if (string_iadd_cstr(&x[0], "c")) abort();
    if (string_iadd_cstr(&x[1], "x")) abort();
    if (string_iadd_cstr(&x[1], "y")) abort();
    if (string_iadd_cstr(&x[1], "z")) abort();

    // cout << "x[0]=" << x[0] << endl;
    printf("%s", "x[0]=");
    string_print(&x[0]);
    printf("\n");
    fflush(stdout);

    // cout << "x[1]=" << x[1] << endl;
    printf("%s", "x[1]=");
    string_print(&x[1]);
    printf("\n");
    fflush(stdout);

    // run destructors
    for (size_t i = 0; i < 10; ++i) {
        string_fini(&x[i]);
    }
    free(x);
}

A: Here is a simple example if you do not want to use strcat. This is a minimal example to demonstrate how one could concatenate strings, things like reallocation of memory have not been implemented.
#include <stdio.h>
#include <stdlib.h>

int main(void) {

    char buf[30] = "LOREM \n IPSUM DOLOR SIT AMET\0";
    char *buff2;
    int i = 0, n = 30;
    buff2 = (char*)malloc(512 * sizeof(char));

    //set first element of buff2 to be terminating null char
    buff2[0] = '\0';

    for(i = 0; i < n; i++) {
        if(buf[i] != '\n') {
            buff2[i + 1] = '\0'; // shift terminating null char forward
            buff2[i] = buf[i];
        } else {
            buff2[i + 1] = '\0'; // shift terminating null char forward
            buff2[i] = 'n';
        }
    }

    printf("%s\n",buff2);

    return EXIT_SUCCESS;
}

It replaces newlines with an "n" character; you can change this if you want. Of course, you want to be careful only to address elements which have actually been allocated. Does not include function to read from file because we don't have the file; this is easily implemented. I suggest you look into fgetc.


text:
Q: Heavy rendering task (in canvas) in JavaFX blocks GUI I want to create an application that performs many renderings in a canvas.
The normal JavaFX way blocks the GUI: It is realy hard to press the button in the application code below (run with Java 8).
I searched the web, but JavaFX does not support background rendering: All rendering operation (like strokeLine) are stored in a buffer and are executed in the JavaFX application thread later. So I cannot even use two canvases and exchange then after rendering.
Also the javafx.scene.Node.snapshot(SnapshotParameters, WritableImage) cannot be used to create an image in a background thread, as it needs to run inside the JavaFX application thread and so it will block the GUI also.
Any ideas to have a non blocking GUI with many rendering operations? (I just want to press buttons etc. while the rendering is performed somehow in background or paused regularly)
package canvastest;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.StrokeLineCap;
import javafx.stage.Stage;

public class DrawLinieTest extends Application
{
    int             interations     = 2;

    double          lineSpacing     = 1;

    Random          rand            = new Random(666);

    List<Color>     colorList;

    final VBox      root            = new VBox();

    Canvas          canvas          = new Canvas(1200, 800);

    Canvas          canvas2         = new Canvas(1200, 800);

    ExecutorService executorService = Executors.newSingleThreadExecutor();

    Future<?>       drawShapesFuture;

    {
        colorList = new ArrayList<>(256);
        colorList.add(Color.ALICEBLUE);
        colorList.add(Color.ANTIQUEWHITE);
        colorList.add(Color.AQUA);
        colorList.add(Color.AQUAMARINE);
        colorList.add(Color.AZURE);
        colorList.add(Color.BEIGE);
        colorList.add(Color.BISQUE);
        colorList.add(Color.BLACK);
        colorList.add(Color.BLANCHEDALMOND);
        colorList.add(Color.BLUE);
        colorList.add(Color.BLUEVIOLET);
        colorList.add(Color.BROWN);
        colorList.add(Color.BURLYWOOD);

    }

    public static void main(String[] args)
    {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage)
    {
        primaryStage.setTitle("Drawing Operations Test");

        System.out.println("Init...");

        // inital draw that creates a big internal operation buffer (GrowableDataBuffer)
        drawShapes(canvas.getGraphicsContext2D(), lineSpacing);
        drawShapes(canvas2.getGraphicsContext2D(), lineSpacing);

        System.out.println("Start testing...");
        new CanvasRedrawTask().start();

        Button btn = new Button("test " + System.nanoTime());
        btn.setOnAction((ActionEvent e) ->
        {
            btn.setText("test " + System.nanoTime());
        });

        root.getChildren().add(btn);
        root.getChildren().add(canvas);

        Scene scene = new Scene(root);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void drawShapes(GraphicsContext gc, double f)
    {
        System.out.println(">>> BEGIN: drawShapes ");

        gc.clearRect(0, 0, gc.getCanvas().getWidth(), gc.getCanvas().getHeight());

        gc.setLineWidth(10);

        gc.setLineCap(StrokeLineCap.ROUND);

        long time = System.nanoTime();

        double w = gc.getCanvas().getWidth() - 80;
        double h = gc.getCanvas().getHeight() - 80;
        int c = 0;

        for (int i = 0; i < interations; i++)
        {
            for (double x = 0; x < w; x += f)
            {
                for (double y = 0; y < h; y += f)
                {
                    gc.setStroke(colorList.get(rand.nextInt(colorList.size())));
                    gc.strokeLine(40 + x, 10 + y, 10 + x, 40 + y);
                    c++;
                }
            }
        }

        System.out.println("<<< END: drawShapes: " + ((System.nanoTime() - time) / 1000 / 1000) + "ms");
    }

    public synchronized void drawShapesAsyc(final double f)
    {
        if (drawShapesFuture != null && !drawShapesFuture.isDone())
            return;
        drawShapesFuture = executorService.submit(() ->
        {
            drawShapes(canvas2.getGraphicsContext2D(), lineSpacing);

            Platform.runLater(() ->
            {
                root.getChildren().remove(canvas);

                Canvas t = canvas;
                canvas = canvas2;
                canvas2 = t;

                root.getChildren().add(canvas);
            });

        });
    }

    class CanvasRedrawTask extends AnimationTimer
    {
        long time = System.nanoTime();

        @Override
        public void handle(long now)
        {
            drawShapesAsyc(lineSpacing);
            long f = (System.nanoTime() - time) / 1000 / 1000;
            System.out.println("Time since last redraw " + f + " ms");
            time = System.nanoTime();
        }
    }
}

EDIT Edited the code to show that a background thread that sends the draw operations and than exchange the canvas does not resolve the problem! Because All rendering operation (like strokeLine) are stored in a buffer and are executed in the JavaFX application thread later.

A: You are drawing 1.6 million lines per frame.  It is simply a lot of lines and takes time to render using the JavaFX rendering pipeline.  One possible workaround is not to issue all drawing commands in a single frame, but instead render incrementally, spacing out drawing commands, so that the application remains relatively responsive (e.g. you can close it down or interact with buttons and controls on the app while it is rendering).  Obviously, there are some tradeoffs in extra complexity with this approach and the result is not as desirable as simply being able to render extremely large amounts of draw commands within the context of single 60fps frame.  So the presented approach is only acceptable for some kinds of applications.
Some ways to perform an incremental render are:

*

*Only issue a max number of calls each frame.

*Place the rendering calls into a buffer such as a blocking queue and just drain a max number of calls each frame from the queue.

Here is a sample of the first option.
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.concurrent.*;
import javafx.scene.Scene;
import javafx.scene.canvas.*;
import javafx.scene.control.Button;
import javafx.scene.image.*;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.StrokeLineCap;
import javafx.stage.Stage;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.*;

public class DrawLineIncrementalTest extends Application {
    private static final int FRAME_CALL_THRESHOLD = 25_000;

    private static final int ITERATIONS = 2;
    private static final double LINE_SPACING = 1;
    private final Random rand = new Random(666);
    private List<Color> colorList;
    private final WritableImage image = new WritableImage(ShapeService.W, ShapeService.H);

    private final Lock lock = new ReentrantLock();
    private final Condition rendered = lock.newCondition();
    private final ShapeService shapeService = new ShapeService();

    public DrawLineIncrementalTest() {
        colorList = new ArrayList<>(256);
        colorList.add(Color.ALICEBLUE);
        colorList.add(Color.ANTIQUEWHITE);
        colorList.add(Color.AQUA);
        colorList.add(Color.AQUAMARINE);
        colorList.add(Color.AZURE);
        colorList.add(Color.BEIGE);
        colorList.add(Color.BISQUE);
        colorList.add(Color.BLACK);
        colorList.add(Color.BLANCHEDALMOND);
        colorList.add(Color.BLUE);
        colorList.add(Color.BLUEVIOLET);
        colorList.add(Color.BROWN);
        colorList.add(Color.BURLYWOOD);
    }

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Drawing Operations Test");

        System.out.println("Start testing...");
        new CanvasRedrawHandler().start();

        Button btn = new Button("test " + System.nanoTime());
        btn.setOnAction(e -> btn.setText("test " + System.nanoTime()));

        Scene scene = new Scene(new VBox(btn, new ImageView(image)));
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private class CanvasRedrawHandler extends AnimationTimer {
        long time = System.nanoTime();

        @Override
        public void handle(long now) {
            if (!shapeService.isRunning()) {
                shapeService.reset();
                shapeService.start();
            }

            if (lock.tryLock()) {
                try {
                    System.out.println("Rendering canvas");
                    shapeService.canvas.snapshot(null, image);
                    rendered.signal();
                } finally {
                    lock.unlock();
                }
            }

            long f = (System.nanoTime() - time) / 1000 / 1000;
            System.out.println("Time since last redraw " + f + " ms");
            time = System.nanoTime();
        }
    }

    private class ShapeService extends Service<Void> {
        private Canvas canvas;

        private static final int W = 1200, H = 800;

        public ShapeService() {
            canvas = new Canvas(W, H);
        }

        @Override
        protected Task<Void> createTask() {
            return new Task<Void>() {
                @Override
                protected Void call() throws Exception {
                    drawShapes(canvas.getGraphicsContext2D(), LINE_SPACING);

                    return null;
                }
            };
        }

        private void drawShapes(GraphicsContext gc, double f) throws InterruptedException {
            lock.lock();
            try {
                System.out.println(">>> BEGIN: drawShapes ");

                gc.clearRect(0, 0, gc.getCanvas().getWidth(), gc.getCanvas().getHeight());
                gc.setLineWidth(10);
                gc.setLineCap(StrokeLineCap.ROUND);

                long time = System.nanoTime();

                double w = gc.getCanvas().getWidth() - 80;
                double h = gc.getCanvas().getHeight() - 80;

                int nCalls = 0, nCallsPerFrame = 0;

                for (int i = 0; i < ITERATIONS; i++) {
                    for (double x = 0; x < w; x += f) {
                        for (double y = 0; y < h; y += f) {
                            gc.setStroke(colorList.get(rand.nextInt(colorList.size())));
                            gc.strokeLine(40 + x, 10 + y, 10 + x, 40 + y);
                            nCalls++;
                            nCallsPerFrame++;
                            if (nCallsPerFrame >= FRAME_CALL_THRESHOLD) {
                                System.out.println(">>> Pausing: drawShapes ");
                                rendered.await();
                                nCallsPerFrame = 0;
                                System.out.println(">>> Continuing: drawShapes ");
                            }
                        }
                    }
                }

                System.out.println("<<< END: drawShapes: " + ((System.nanoTime() - time) / 1000 / 1000) + "ms for " + nCalls + " ops");
            } finally {
                lock.unlock();
            }
        }
    }
}

Note that for the sample, it is possible to interact with the scene by clicking the test button while the incremental rendering is in progress. If desired, you could further enhance this to double buffer the snapshot images for the canvas so that the user doesn't see the incremental rendering.  Also because the incremental rendering is in a Service, you can use the service facilities to track rendering progress and relay that to the UI via a progress bar or whatever mechanisms you wish.
For the above sample you can play around with the FRAME_CALL_THRESHOLD setting to vary the maximum number of calls which are issued each frame.  The current setting of 25,000 calls per frame keeps the UI very responsive.  A setting of 2,000,000 would be the same as fully rendering the canvas in a single frame (because you are issuing 1,600,000 calls in the frame) and no incremental rendering will be performed, however the UI will not be responsive while the rendering operations are being completed for that frame.
Side Note
There is something weird here. If you remove all of the concurrency stuff and the double canvases in the code in the original question and just use a single canvas with all logic on the JavaFX application thread, the initial invocation of drawShapes takes 27 seconds, and subsequent invocations take less that a second, but in all cases the application logic is asking the system to perform the same task. I don't know why the initial call is so slow, it seems like a performance issue in the JavaFX canvas implementation to me, perhaps related to inefficient buffer allocation.  If that is the case, then perhaps the JavaFX canvas implementation could be tweaked so that a hint for a suggested initial buffer size could be provided, so that it more efficiently allocates space for its internal growable buffer implementation.  It might be something worth filing a bug or discussing it on the JavaFX developer mailing list.  Also note that the issue of a very slow initial rendering of the canvas is only visible when you issue a very large number (e.g. > 500,000) of rendering calls, so it won't effect all applications.

A: The issue that is described here has also been discussed on the JavaFX mailing list some months ago in this thread
http://mail.openjdk.java.net/pipermail/openjfx-dev/2015-September/017939.html
The proposed solution is similar to the one given by jewelsea.


text:
Q: textfield on alert view issue of key board dismiss i have critical problem in my code, i have 3 textField in alert view, 2 times i tap the text field and press ok button of alert view keyboard resign, but third time its not dismissed.
Here my code

A: Add action to textfield for hide keyboard like followings:
 [ptextfield
 addTarget:self action:@selector(hideKeyboard:) forControlEvents:UIControlEventEditingDidEndOnExit];

and for hiding keyboard:
- (void)hideKeyboard:(id)textField
{
    [textField resignFirstResponder];
}

A: Your code should work.. Better do check your alert tag.. Else do like this..  in
textFieldBeginEditing
 method get that textfield and assign it to one global textfield like
ActiveTextfield = textField.
Then in alertview delegate resign that ActiveTextfield.

A: I put my answer in here. Please check. You don't need to open too many questions about a single thing.


text:
Q: Выборка данных из массива Есть переменная
$mas = array('1', '2', '5');

Формируется в зависимости от нужных значений id категорий.
Также имеется вот такой массив, используется для хранения инфы о категориях
array {
   [1]=> array {
      ["id"]=> "1"
      ["parent_id"]=> ""
      ["name"]=> "color"
   }
   [2]=> array {
      ["id"]=> "2"
      ["parent_id"]=> "1"
      ["name"]=> "blue"
   }
   [3]=> array {
      ["id"]=> "3"
      ["parent_id"]=> "1"
      ["name"]=> "orange"
   }
   [4]=> array {
      ["id"]=> "4"
      ["parent_id"]=> "1"
      ["name"]=> "gray"
   }
   [5]=> array {
      ["id"]=> "5"
      ["parent_id"]=> "1"
      ["name"]=> "yellow"
   }
}

Подскажите, как вывести именно ключи из $mas

A: Первый вариант - простой для понимания.
Предположим второй массив будет $mas2
foreach ($mas as $mas_value) {
  $result_mas[$mas_value]=$mas2[$mas_value];
}

В переменной $result_mas будет Ваш массив, ну а дальше крутите как хотите.
Второй вариант "элегантный", как в подсказал в комментариях @ArchDemon через array_keys думаю тоже сработает, но я спросонья сразу не соображу, надо потестить.

A: Страшненько, но работает :) Думаю, тут всё понятно
$mas1 = [1,3];
$mas2 = [['id'=>5],['id'=>4],['id'=>3],['id'=>2],['id'=>1]];

print_r(array_intersect_key($mas2, array_intersect(array_column($mas2, 'id'), $mas1))); // [ [id => 3], [id => 1] ]

демо тут


text:
Q: issue "unexpectedly found nil" with downloading image from firebase swift I have an issue when I'm downloading an image from firebase here is my code:
func getuser(){

FIRDatabase.database().reference().child("users").child(userID!).child("credentials").observeSingleEvent(of: .value, with: { (snapshot) in

        let value = snapshot.value as? NSDictionary
        let name = value?["name"] as! String
        let email = value?["email"] as! String
        let profilePicLink = value?["profilePicLink"] as? String ?? ""

        Variables.userName = name as String
        Variables.userEmail = email as String
        self.username.text = Variables.userName
        print(profilePicLink)
        // Create a storage reference from the URL
        let storageRef = self.storage.reference(forURL: profilePicLink)
        // Download the data, assuming a max size of 1MB (you can change this as necessary)
        storageRef.data(withMaxSize: 1 *  1000 * 1000 ) { (data, error) -> Void in

            let pic = UIImage(data: data!)
            self.img.image = pic

        }

    })

}

I'm getting this error:
==> this the link as printed https://firebasestorage.googleapis.com/v0/b/eswitch-72b56.appspot.com/o/usersProfilePics%2FKYe6fIQReNM8Oog4ELOdRLsC99J3?alt=media&token=6f2392bc-d35b-4ebc-b2c1-2dc34bc4b95a
fatal error: unexpectedly found nil while unwrapping an Optional value

The error that I'm getting is in this line
let storageRef = self.storage.reference(forURL: profilePicLink)

below is my snapshot readings:
snap (credentials) {
    email = "bilal@me.com";
    mobile = 50955514;
    name = Bilal;
    profilePicLink = "https://firebasestorage.googleapis.com/v0/b/eswitch-72b56.appspot.com/o/usersProfilePics%2FKYe6fIQReNM8Oog4ELOdRLsC99J3?alt=media&token=6f2392bc-d35b-4ebc-b2c1-2dc34bc4b95a";
    role = user;
}

Thanks
Here is the solution:
Added this line to func viewDidLoad()
storage = FIRStorage.storage()

A: You need to make sure that self.storage is initialized.
storage = FIRStorage.storage()


text:
Q: How to identify in jQuery whether an image src is a path or base64 string I am working with image in jQuery. Actually I have an image tag which sometimes has src with base 64 like these
 <img id="profileImage" src="images/blank_photo.png" width="240" height="240"  />

Sometimes on the image src there will be an base64 string like these:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD......

and sometimes the image src will be the image path
https://lh4.googleusercontent.com/-f87Bg7JWR4A/AAAAAAAAAAI/AAAAAAAAABg/sT5evwC9ziw/photo.jpg

So the problem is how can I identify in jQuery whether its an base64 or an image path... Is there any method in jQuery by which we can identify or we have to general methods like applying if condition and searching for an substring like http.
Is there any better solution for these.....

A: You have base64 in src attribute for images.To get objects having src containing base64 :
var withbase64img = $("img[src*='base64']");

For looping through them:
$("img[src*='base64']").each(function(){
    //code here
});


text:
Q: How to handle concerns shared by module namespaced controllers I have a controller that looks something like this:
module Guardians
  class StudentsController < ApplicationController

    def show
      @student = Student.find params[:id]

      authorize @student, policy_class: StudentPolicy
    end
  end
end

Because the controller is within a module, the policy class which is used is Guardians::StudentPolicy, which is what I want.
However I now have another controller:
module Teachers
  class StudentsController < ApplicationController

    def show
      @student = Student.find params[:id]

      authorize @student, policy_class: StudentPolicy
    end
  end
end

Here the policy_class used is Teachers::StudentPolicy
But because the show method itself is identical, ideally I would like to dry this up with a concern. However if I cannot seem to do this, as
authorize @student, policy_class: StudentPolicy
will no longer automatically call the namespaced policy class when it is called from inside the concern.
What is the DRYest way to achieve this?

A: If you create a concern like this:
module StudentsConcern
  extend ActiveSupport::Concern
  included do
    before_action :find_and_authorize_student, only:[:show]
  end

  private

  def find_student_and_authorize
    @student = Student.find(params[:id])
    if self.class.name.deconstantize == 'Teachers'
      authorize @student, policy_class: Teachers::StudentPolicy
    else
      authorize @student, policy_class: Guardians::StudentPolicy
    end
  end
end

And then include this in both of the controllers and clear the show actions.


text:
Q: Thread handle leak in .Net service (Not win32 threads. i.e not observable in Task Manager) I'm trying to debug a handle leak in a .Net service and I'm puzzled by a Thread Handle leak.
Could someone please describe how this can happen? Task Manager reports only 22 active threads after each test period, but the handle count keeps increasing.
I send a message to force GC after each test period, and before getting the handle count.
There is, of course, an event handle leak also, but that is easier to explain/fix.
D:\log\SEEService>handle -p 82080 -s

Handle v3.46
Copyright (C) 1997-2011 Mark Russinovich
Sysinternals - www.sysinternals.com

Handle type summary:
  ALPC Port       : 8
  Desktop         : 1
  Directory       : 3
  EtwRegistration : 35
  Event           : 97397
  File            : 36
  IoCompletion    : 3
  Key             : 38
  KeyedEvent      : 1
  Mutant          : 9
  Section         : 23
  Semaphore       : 15
  Thread          : 22845
  Timer           : 5
  Token           : 1
  TpWorkerFactory : 4
  WindowStation   : 2
Total handles: 120426

A: This link might still be relevant: Thread handle leak. Have you tried calling GC.WaitForPendingFinalizers() after GC.Collect()?

A: I found the bug :) I removed one and one module from the execution path, and found the "bad" module. It was a communication module, and it was the classic "added object to list, but not removed" bug :) The thread handle ++ was not able to be GC'd because a list held a referense to a object.. Thanks for the reply


text:
Q: How did the number of elements in each array end up being less than they were in their parent array (array of arrays) This problems seems to go away when I dont use shuffle(train_data). I also tried doing shuffle(train_data_1) and shuffle(train_data_2) seperately but in that case too, the distribution seems to change.
import numpy as np
import pandas as pd
from collections import Counter
from random import shuffle

train_data_1 = np.load('training_data_v1.npy', allow_pickle=True)
train_data_2 = np.load('training_data_v2.npy', allow_pickle=True)

train_data = np.vstack((train_data_1, train_data_2))

df = pd.DataFrame(train_data)
print(df.head())
print(Counter(df[1].apply(str)))

Output :
                                                 0          1
0  [[33, 255, 255, 255, 255, 255, 255, 255, 255, ...  [0, 1, 0]
1  [[33, 255, 255, 255, 255, 255, 255, 255, 255, ...  [0, 1, 0]
2  [[33, 255, 255, 255, 255, 255, 255, 255, 255, ...  [0, 1, 0]
3  [[33, 255, 255, 255, 255, 255, 255, 255, 255, ...  [0, 1, 0]
4  [[33, 255, 255, 255, 255, 255, 255, 255, 255, ...  [0, 1, 0]
Counter({'[0, 1, 0]': 6064, '[1, 0, 0]': 542, '[0, 0, 1]': 394})

Seperating the forwards, lefts and rights into their respective arrays
shuffle(train_data)

lefts = []
rights = []
forwards = []

for data in train_data:
    img = data[0]
    choice = data[1]

    if choice == [1,0,0]:
        lefts.append([img,choice])
    elif choice == [0,1,0]:
        forwards.append([img,choice])
    elif choice == [0,0,1]:
        rights.append([img,choice])
    else:
        print('no matches')

print (len(forwards), len(lefts), len(rights))

Output:
6086 763 151

At start, the distribution of forward, left, right was (6064, 542, 394)
Now, it is (6096, 763, 151)
How has the distribution changed??
What am I doing wrong!?

A: Dont use shuffle(train_data) instead after the formation of forwards, lefts and rights array, use shuffle() on them individually.
shuffle(forwards)
shuffle(lefts)
shuffle(rights)

Now there isn't any problem with the distribution and shuffling is also performed correctly.


text:
Q: Locally Hölder Continuous Function I want to show that the fuction $\frac{1}{1+x^2}$ is locally Hölder continuous, I used the mean value theorem, but does not work. Tools that I need to resolve?.
Also does definitión is:
if $f$ is a function $(f:\Omega\longrightarrow\mathbb{R})$, then $f$ locally Hölder continuous iff there are $M$, $\alpha$ such that for each $k\subseteq \Omega $, $k$ compact
$$|f(x)-f(y)|\leq M|x-y|^\alpha\;\;\;\;\;\;\forall x,y\in k?$$
Thanks for your help, I do not speak good English and I'm new.

A: The function is locally Hölder continuous because it is $C^1$. In fact it is locally Lipschitz continuous (that is, you can take $\alpha=1$ in each compact set).


text:
Q: Как извлечь данные из кнопки Яндекс.Денег У меня на сайте есть кнопка такого вида:

Вот её код:

Мне нужно иметь возможность оперировать с вот этой цифрой внутри кнопки (в данном случае - 98), а конкретно - чтобы я мог работать с ней в javascript'e. То есть сохранить её в переменную с возможностью автоматического обновления её значения при изменении суммы, указанной в кнопке.

A: Никак.
В качестве бэкграунда блока выводится картинка, сформированная на сайте Яндекс.


text:
Q: Gain value for PI controller using Simulink I am doing project in Matlab Simulink. I want to find the proportional and integral gain value for PI controller. Is there any way to find the PI controller gain value which does not have transfer function? I  have two inputs for PI controller one is the  the reference voltage and  and the other is voltage from the capacitor. Please help me in finding the gain value.
Please let me know if more information is needed.

A: One way is to use PID Tuner in MATLAB/SIMULINK. PID Tuner provides a fast and widely applicable single-loop PID tuning method for the Simulink PID Controller blocks. With this method, you can tune PID parameters to achieve a robust design with the desired response time. Here you can find a rather good [example].
But if you know the transfer function of your system you can easily use something like this:
sys = zpk([],[-1 -1 -1],1); % define the plant
[C_pi,info] = pidtune(sys,'pi')


text:
Q: How to show stack trace in pudb? How do I see my stack trace in pudb? (i.e., the equivalent of the w / where command in the pdb Python debugger)
References:

*

*pudb on PyPI

*pudb source on github

A: There is no such command.  The information is available in the "Stack" list in the sidebar:


text:
Q: Problema utilizando la función cin.getline() con puntero a arreglo de estructuras Mi programa es simple: registrar 3 datos de 10 usuarios (Identificación, nombre y edad).
Estoy utilizando la estructura User para generar un puntero dinámico de tipo User que recorra cada estructura para ingresar los datos de los usuarios por consola en la función ingresoDatos() y luego mostrarlos con la función mostrarUsuarios()
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <conio.h>
using namespace std;

struct User{
    char id[20];
    char nombre[20];
    char edad[3];
} *user_ptr = new User[10];

// Prototipos
int ingresoDatos();
void mostrarUsuarios(User *, int);

int main()
{
    system("cls"); // Limpiar terminal
    int num_users = ingresoDatos();
    mostrarUsuarios(user_ptr, num_users);

    delete[] user_ptr;
    return 0;
}

int ingresoDatos()
{
    char continuar;
    int num_users = 0;
    for (num_users = 0; num_users < 100; num_users++)
    {
        // fflush(stdin);
        cout << "Ingrese el ID: ";
        cin.getline((user_ptr + num_users)->id, 20, '\n');

        cout << "Ingrese el nombre: ";
        cin.getline( (user_ptr + num_users) -> nombre, 20, '\n');

        cout << "Ingrese la edad: ";
        cin.getline((user_ptr + num_users)->edad, 3, '\n');

        cout << "Usuario registrado con exito, registrar otro? [s/n]: ";
        cin >> continuar;
        if (continuar == 'n')
            return ++num_users;
    }
    return 100;
}

void mostrarUsuarios(User *ptr, int num_users)
{
    system("clear");
    cout << "Mostrando lista de usuarios registrados:"<<endl;
    for (int user = 0; user < num_users; user++)
    {
        cout << (ptr + user )->id << ' '
             << (ptr + user )->nombre << ' '
             << (ptr + user )->edad << " anios"
             << endl;
    }
}

El problema está en que cuando voy a pedir el dato del segundo o más usuarios, el campo de ID no me lo pide, el cin.getline() falla en ese momento y no sé por qué. Creo que tiene que ver con el hecho de usar una función para capturar datos.


text:
Q: How to plot multiple lines from data in a JSON file I have a json file containing x and y values (x is the number of steps while y are the values of the loss function). I want to plot this but i am not a programmer by profession so i am having a bit of a hard time unpacking these values first into a dataframe and then plotting it.
[
  {
    "x": [49,99,149,199,249,299,349,399,449,499,549,599,649,699,749,799,849,899,949,999,1049,1099,1149,1199,1249,1299,1349,1399,1449,1499,1549,1599,1649,1699,1749,1799,1849,1899,1949,1999,2049,2099,2149,2199,2249,2299,2349,2399,2449,2499,2549,2599,2649,2699,2749,2799,2849,2899,2949,2999,3049,3099,3149,3199,3249,3299,3349,3399,3449,3499,3549,3599,3649,3699,3749,3799,3849,3899,3949,3999,4049,4099,4149,4199,4249,4299,4349,4399,4449,4499,4549,4599,4649,4699,4749,4799,4849,4899,4949,4999],
    "y": [0.8078442215919495,0.6924954056739807,0.637282133102417,0.5666537284851074,0.4263683557510376,0.29408636689186096,0.22852952778339386,0.19844533503055573,0.19280606508255005,0.16006380319595337,0.18059080839157104,0.27476057410240173,0.16974058747291565,0.13871365785598755,0.15893904864788055,0.11171692609786987,0.09724593907594681,0.1499839723110199,0.17183662950992584,0.1576225459575653,0.12323413789272308,0.12138434499502182,0.09343212097883224,0.10920502990484238,0.11386646330356598,0.09778832644224167,0.14350709319114685,0.13651356101036072,0.15092197060585022,0.09928392618894577,0.12458140403032303,0.10494255274534225,0.10528195649385452,0.13158175349235535,0.0788651630282402,0.09537861496210098,0.08444802463054657,0.09358047693967819,0.11348600685596466,0.11421093344688416,0.13024120032787323,0.09298647195100784,0.10095459222793579,0.12882551550865173,0.06175372377038002,0.11043348163366318,0.07273056358098984,0.07597362995147705,0.07747262716293335,0.10011449456214905,0.09275206923484802,0.11640968173742294,0.07466059923171997,0.06264252215623856,0.10496743023395538,0.12706291675567627,0.07618371397256851,0.05997024476528168,0.0738396868109703,0.07691851258277893,0.04857499152421951,0.08904716372489929,0.09522826969623566,0.0718853548169136,0.06508275866508484,0.0604521669447422,0.0327882245182991,0.043644022196531296,0.0742092877626419,0.06414887309074402,0.05483072251081467,0.06133958697319031,0.05271274596452713,0.051848240196704865,0.04392067342996597,0.07057813555002213,0.051781173795461655,0.19890470802783966,0.046647973358631134,0.04351358115673065,0.06602110713720322,0.05368412658572197,0.046410009264945984,0.05693329870700836,0.05165236443281174,0.03220716118812561,0.05031270533800125,0.05368302762508392,0.048431843519210815,0.055765118449926376,0.03884245455265045,0.05483575165271759,0.027131063863635063,0.042943283915519714,0.03232723847031593,0.043425388634204865,0.03555495664477348,0.05412492901086807,0.0535135492682457,0.03369136527180672],
    "type": "scattergl",
    "name": "train_loss"
  }
]

Multiple curves which I want in the same plot:
[{"x":[553,1107,1661,2215,2769,3323,3877,4431,4985],"y":[0.3421344757080078,0.21656209230422974,0.2768174707889557,0.21082060039043427,0.2538467049598694,0.24818505346775055,0.2378658652305603,0.2655095160007477,0.27708765864372253],"type":"scattergl","name":"val_loss"},{"x":[553,1107,1661,2215,2769,3323,3877,4431,4985],"y":[0.8641330599784851,0.922535240650177,0.9076007604598999,0.9262991547584534,0.9157357811927795,0.9193783402442932,0.9227780699729919,0.9205925464630127,0.9188926815986633],"type":"scattergl","name":"val_acc"},{"x":[49,99,149,199,249,299,349,399,449,499,549,599,649,699,749,799,849,899,949,999,1049,1099,1149,1199,1249,1299,1349,1399,1449,1499,1549,1599,1649,1699,1749,1799,1849,1899,1949,1999,2049,2099,2149,2199,2249,2299,2349,2399,2449,2499,2549,2599,2649,2699,2749,2799,2849,2899,2949,2999,3049,3099,3149,3199,3249,3299,3349,3399,3449,3499,3549,3599,3649,3699,3749,3799,3849,3899,3949,3999,4049,4099,4149,4199,4249,4299,4349,4399,4449,4499,4549,4599,4649,4699,4749,4799,4849,4899,4949,4999],"y":[0.8078442215919495,0.6924954056739807,0.637282133102417,0.5666537284851074,0.4263683557510376,0.29408636689186096,0.22852952778339386,0.19844533503055573,0.19280606508255005,0.16006380319595337,0.18059080839157104,0.27476057410240173,0.16974058747291565,0.13871365785598755,0.15893904864788055,0.11171692609786987,0.09724593907594681,0.1499839723110199,0.17183662950992584,0.1576225459575653,0.12323413789272308,0.12138434499502182,0.09343212097883224,0.10920502990484238,0.11386646330356598,0.09778832644224167,0.14350709319114685,0.13651356101036072,0.15092197060585022,0.09928392618894577,0.12458140403032303,0.10494255274534225,0.10528195649385452,0.13158175349235535,0.0788651630282402,0.09537861496210098,0.08444802463054657,0.09358047693967819,0.11348600685596466,0.11421093344688416,0.13024120032787323,0.09298647195100784,0.10095459222793579,0.12882551550865173,0.06175372377038002,0.11043348163366318,0.07273056358098984,0.07597362995147705,0.07747262716293335,0.10011449456214905,0.09275206923484802,0.11640968173742294,0.07466059923171997,0.06264252215623856,0.10496743023395538,0.12706291675567627,0.07618371397256851,0.05997024476528168,0.0738396868109703,0.07691851258277893,0.04857499152421951,0.08904716372489929,0.09522826969623566,0.0718853548169136,0.06508275866508484,0.0604521669447422,0.0327882245182991,0.043644022196531296,0.0742092877626419,0.06414887309074402,0.05483072251081467,0.06133958697319031,0.05271274596452713,0.051848240196704865,0.04392067342996597,0.07057813555002213,0.051781173795461655,0.19890470802783966,0.046647973358631134,0.04351358115673065,0.06602110713720322,0.05368412658572197,0.046410009264945984,0.05693329870700836,0.05165236443281174,0.03220716118812561,0.05031270533800125,0.05368302762508392,0.048431843519210815,0.055765118449926376,0.03884245455265045,0.05483575165271759,0.027131063863635063,0.042943283915519714,0.03232723847031593,0.043425388634204865,0.03555495664477348,0.05412492901086807,0.0535135492682457,0.03369136527180672],"type":"scattergl","name":"train_loss"},{"x":[49,99,149,199,249,299,349,399,449,499,549,599,649,699,749,799,849,899,949,999,1049,1099,1149,1199,1249,1299,1349,1399,1449,1499,1549,1599,1649,1699,1749,1799,1849,1899,1949,1999,2049,2099,2149,2199,2249,2299,2349,2399,2449,2499,2549,2599,2649,2699,2749,2799,2849,2899,2949,2999,3049,3099,3149,3199,3249,3299,3349,3399,3449,3499,3549,3599,3649,3699,3749,3799,3849,3899,3949,3999,4049,4099,4149,4199,4249,4299,4349,4399,4449,4499,4549,4599,4649,4699,4749,4799,4849,4899,4949,4999],"y":[0.375,0.5637500286102295,0.6387500166893005,0.706250011920929,0.8224999904632568,0.9012500047683716,0.9262499809265137,0.9350000023841858,0.9237499833106995,0.9537500143051147,0.9350000023841858,0.875,0.9212499856948853,0.949999988079071,0.9212499856948853,0.956250011920929,0.9637500047683716,0.9399999976158142,0.9350000023841858,0.9375,0.9549999833106995,0.9574999809265137,0.9642857313156128,0.9549999833106995,0.9574999809265137,0.9537500143051147,0.9462500214576721,0.9437500238418579,0.9437500238418579,0.9624999761581421,0.949999988079071,0.9637500047683716,0.9637500047683716,0.9464285969734192,0.9750000238418579,0.9637500047683716,0.9674999713897705,0.9662500023841858,0.9512500166893005,0.9599999785423279,0.9587500095367432,0.9612500071525574,0.9549999833106995,0.9524999856948853,0.9821428656578064,0.9612500071525574,0.9725000262260437,0.9700000286102295,0.9674999713897705,0.9624999761581421,0.96875,0.949999988079071,0.9700000286102295,0.9787499904632568,0.9662500023841858,0.9642857313156128,0.9725000262260437,0.981249988079071,0.9762499928474426,0.9712499976158142,0.9862499833106995,0.9637500047683716,0.9674999713897705,0.9712499976158142,0.9750000238418579,0.9800000190734863,0.9821428656578064,0.9887499809265137,0.9750000238418579,0.9837499856948853,0.9787499904632568,0.9787499904632568,0.9850000143051147,0.9775000214576721,0.9850000143051147,0.9762499928474426,0.981249988079071,0.9464285969734192,0.9862499833106995,0.9850000143051147,0.9762499928474426,0.9825000166893005,0.9862499833106995,0.9862499833106995,0.9800000190734863,0.9925000071525574,0.9837499856948853,0.9825000166893005,0.9821428656578064,0.9787499904632568,0.9862499833106995,0.9825000166893005,0.9887499809265137,0.9887499809265137,0.9900000095367432,0.9862499833106995,0.9887499809265137,0.9825000166893005,0.9825000166893005,0.9642857313156128],"type":"scattergl","name":"train_acc"}]

The plot should look something like this:

A: Another variant:
import pandas as pd
import json
import matplotlib.pyplot as plt
data = [
    {"x": [49, 99, 149, 199, 249, 299, 349, 399, 449, 499, 549, 599, 649, 699, 749, 799, 849, 899, 949, 999, 1049, 1099, 1149, 1199, 1249, 1299, 1349, 1399, 1449, 1499, 1549, 1599, 1649, 1699, 1749, 1799, 1849, 1899, 1949, 1999, 2049, 2099, 2149, 2199, 2249, 2299, 2349, 2399, 2449, 2499, 2549, 2599, 2649, 2699, 2749, 2799, 2849, 2899, 2949, 2999, 3049, 3099, 3149, 3199, 3249, 3299, 3349, 3399, 3449, 3499, 3549, 3599, 3649, 3699, 3749, 3799, 3849, 3899, 3949, 3999, 4049, 4099, 4149, 4199, 4249, 4299, 4349, 4399, 4449, 4499, 4549, 4599, 4649, 4699, 4749, 4799, 4849, 4899, 4949, 4999],
     "y":[0.8078442215919495, 0.6924954056739807, 0.637282133102417, 0.5666537284851074, 0.4263683557510376, 0.29408636689186096, 0.22852952778339386, 0.19844533503055573, 0.19280606508255005, 0.16006380319595337, 0.18059080839157104, 0.27476057410240173, 0.16974058747291565, 0.13871365785598755, 0.15893904864788055, 0.11171692609786987, 0.09724593907594681, 0.1499839723110199, 0.17183662950992584, 0.1576225459575653, 0.12323413789272308, 0.12138434499502182, 0.09343212097883224, 0.10920502990484238, 0.11386646330356598, 0.09778832644224167, 0.14350709319114685, 0.13651356101036072, 0.15092197060585022, 0.09928392618894577, 0.12458140403032303, 0.10494255274534225, 0.10528195649385452, 0.13158175349235535, 0.0788651630282402, 0.09537861496210098, 0.08444802463054657, 0.09358047693967819, 0.11348600685596466, 0.11421093344688416, 0.13024120032787323, 0.09298647195100784, 0.10095459222793579, 0.12882551550865173, 0.06175372377038002, 0.11043348163366318, 0.07273056358098984, 0.07597362995147705, 0.07747262716293335, 0.10011449456214905, 0.09275206923484802, 0.11640968173742294, 0.07466059923171997, 0.06264252215623856, 0.10496743023395538, 0.12706291675567627, 0.07618371397256851, 0.05997024476528168, 0.0738396868109703, 0.07691851258277893, 0.04857499152421951, 0.08904716372489929, 0.09522826969623566, 0.0718853548169136, 0.06508275866508484, 0.0604521669447422, 0.0327882245182991, 0.043644022196531296, 0.0742092877626419, 0.06414887309074402, 0.05483072251081467, 0.06133958697319031, 0.05271274596452713, 0.051848240196704865, 0.04392067342996597, 0.07057813555002213, 0.051781173795461655, 0.19890470802783966, 0.046647973358631134, 0.04351358115673065, 0.06602110713720322, 0.05368412658572197, 0.046410009264945984, 0.05693329870700836, 0.05165236443281174, 0.03220716118812561, 0.05031270533800125, 0.05368302762508392, 0.048431843519210815, 0.055765118449926376, 0.03884245455265045, 0.05483575165271759, 0.027131063863635063, 0.042943283915519714, 0.03232723847031593, 0.043425388634204865, 0.03555495664477348, 0.05412492901086807, 0.0535135492682457, 0.03369136527180672],
     "type":"scattergl", "name":"train_loss"}
]
data_json = json.dumps(data[0])
df = pd.read_json(data_json)
data_json_plot = df.plot(x='x', y='y')
plt.show()

A: *

*Given the json file with multiple names

*pandas uses matplotlib as the default plotting backend. In this case, it is easier to use seaborn, a high-level API for matplotlib.

*

*seaborn.relplot is a figure-level plot.

*df = df[df.name.isin(['train_loss', 'train_acc'])] can be used to select specific data in the 'name' column, after doing .explode.

*Tested in python 3.10, pandas 1.5.0, matplotlib 3.5.2, seaborn 0.12.0
import pandas as pd
import seaborn as sns

# load the data from the file
df = pd.read_json('data/test.json')

# each row of x and y is a list; explode the values in the lists to separate rows
df = df.explode(['x', 'y'], ignore_index=True)

# the easiest option is to use seaborn, which is an api for matplotlib
g = sns.relplot(kind='line', data=df, x='x', y='y', hue='name', marker='.')

*

*Alternative with sns.lineplot, which is an axes-level plot.

import matplotlib.pyplot as plt

# create the figure
fig, ax = plt.subplots(figsize=(8, 6))

# plot
sns.lineplot(data=df, x='x', y='y', hue='name', marker='.', ax=ax)

# move the legend if desired
_ = ax.legend(bbox_to_anchor=(1, 0.5), loc='center left', frameon=False)

*

*Plot directly with pandas.DataFrame.plot
import matplotlib.pyplot as plt

# create the figure
fig, ax = plt.subplots(figsize=(8, 6))

# iterate through each data group by 'name'
for name, data in df.groupby('name'):

    # plot the dataframe
    data.plot(x='x', y='y', marker='.', label=name, ax=ax)

# move the legend as desired
_ = ax.legend(bbox_to_anchor=(1, 0.5), loc='center left', frameon=False)

display(df.head())
      x         y       type      name
0   553  0.342134  scattergl  val_loss
1  1107  0.216562  scattergl  val_loss
2  1661  0.276817  scattergl  val_loss
3  2215  0.210821  scattergl  val_loss
4  2769  0.253847  scattergl  val_loss

display(df.tail())
        x         y       type       name
213  4799   0.98625  scattergl  train_acc
214  4849   0.98875  scattergl  train_acc
215  4899    0.9825  scattergl  train_acc
216  4949    0.9825  scattergl  train_acc
217  4999  0.964286  scattergl  train_acc

test.json
[{
        "x": [553, 1107, 1661, 2215, 2769, 3323, 3877, 4431, 4985],
        "y": [0.3421344757080078, 0.21656209230422974, 0.2768174707889557, 0.21082060039043427, 0.2538467049598694, 0.24818505346775055, 0.2378658652305603, 0.2655095160007477, 0.27708765864372253],
        "type": "scattergl",
        "name": "val_loss"
    }, {
        "x": [553, 1107, 1661, 2215, 2769, 3323, 3877, 4431, 4985],
        "y": [0.8641330599784851, 0.922535240650177, 0.9076007604598999, 0.9262991547584534, 0.9157357811927795, 0.9193783402442932, 0.9227780699729919, 0.9205925464630127, 0.9188926815986633],
        "type": "scattergl",
        "name": "val_acc"
    }, {
        "x": [49, 99, 149, 199, 249, 299, 349, 399, 449, 499, 549, 599, 649, 699, 749, 799, 849, 899, 949, 999, 1049, 1099, 1149, 1199, 1249, 1299, 1349, 1399, 1449, 1499, 1549, 1599, 1649, 1699, 1749, 1799, 1849, 1899, 1949, 1999, 2049, 2099, 2149, 2199, 2249, 2299, 2349, 2399, 2449, 2499, 2549, 2599, 2649, 2699, 2749, 2799, 2849, 2899, 2949, 2999, 3049, 3099, 3149, 3199, 3249, 3299, 3349, 3399, 3449, 3499, 3549, 3599, 3649, 3699, 3749, 3799, 3849, 3899, 3949, 3999, 4049, 4099, 4149, 4199, 4249, 4299, 4349, 4399, 4449, 4499, 4549, 4599, 4649, 4699, 4749, 4799, 4849, 4899, 4949, 4999],
        "y": [0.8078442215919495, 0.6924954056739807, 0.637282133102417, 0.5666537284851074, 0.4263683557510376, 0.29408636689186096, 0.22852952778339386, 0.19844533503055573, 0.19280606508255005, 0.16006380319595337, 0.18059080839157104, 0.27476057410240173, 0.16974058747291565, 0.13871365785598755, 0.15893904864788055, 0.11171692609786987, 0.09724593907594681, 0.1499839723110199, 0.17183662950992584, 0.1576225459575653, 0.12323413789272308, 0.12138434499502182, 0.09343212097883224, 0.10920502990484238, 0.11386646330356598, 0.09778832644224167, 0.14350709319114685, 0.13651356101036072, 0.15092197060585022, 0.09928392618894577, 0.12458140403032303, 0.10494255274534225, 0.10528195649385452, 0.13158175349235535, 0.0788651630282402, 0.09537861496210098, 0.08444802463054657, 0.09358047693967819, 0.11348600685596466, 0.11421093344688416, 0.13024120032787323, 0.09298647195100784, 0.10095459222793579, 0.12882551550865173, 0.06175372377038002, 0.11043348163366318, 0.07273056358098984, 0.07597362995147705, 0.07747262716293335, 0.10011449456214905, 0.09275206923484802, 0.11640968173742294, 0.07466059923171997, 0.06264252215623856, 0.10496743023395538, 0.12706291675567627, 0.07618371397256851, 0.05997024476528168, 0.0738396868109703, 0.07691851258277893, 0.04857499152421951, 0.08904716372489929, 0.09522826969623566, 0.0718853548169136, 0.06508275866508484, 0.0604521669447422, 0.0327882245182991, 0.043644022196531296, 0.0742092877626419, 0.06414887309074402, 0.05483072251081467, 0.06133958697319031, 0.05271274596452713, 0.051848240196704865, 0.04392067342996597, 0.07057813555002213, 0.051781173795461655, 0.19890470802783966, 0.046647973358631134, 0.04351358115673065, 0.06602110713720322, 0.05368412658572197, 0.046410009264945984, 0.05693329870700836, 0.05165236443281174, 0.03220716118812561, 0.05031270533800125, 0.05368302762508392, 0.048431843519210815, 0.055765118449926376, 0.03884245455265045, 0.05483575165271759, 0.027131063863635063, 0.042943283915519714, 0.03232723847031593, 0.043425388634204865, 0.03555495664477348, 0.05412492901086807, 0.0535135492682457, 0.03369136527180672],
        "type": "scattergl",
        "name": "train_loss"
    }, {
        "x": [49, 99, 149, 199, 249, 299, 349, 399, 449, 499, 549, 599, 649, 699, 749, 799, 849, 899, 949, 999, 1049, 1099, 1149, 1199, 1249, 1299, 1349, 1399, 1449, 1499, 1549, 1599, 1649, 1699, 1749, 1799, 1849, 1899, 1949, 1999, 2049, 2099, 2149, 2199, 2249, 2299, 2349, 2399, 2449, 2499, 2549, 2599, 2649, 2699, 2749, 2799, 2849, 2899, 2949, 2999, 3049, 3099, 3149, 3199, 3249, 3299, 3349, 3399, 3449, 3499, 3549, 3599, 3649, 3699, 3749, 3799, 3849, 3899, 3949, 3999, 4049, 4099, 4149, 4199, 4249, 4299, 4349, 4399, 4449, 4499, 4549, 4599, 4649, 4699, 4749, 4799, 4849, 4899, 4949, 4999],
        "y": [0.375, 0.5637500286102295, 0.6387500166893005, 0.706250011920929, 0.8224999904632568, 0.9012500047683716, 0.9262499809265137, 0.9350000023841858, 0.9237499833106995, 0.9537500143051147, 0.9350000023841858, 0.875, 0.9212499856948853, 0.949999988079071, 0.9212499856948853, 0.956250011920929, 0.9637500047683716, 0.9399999976158142, 0.9350000023841858, 0.9375, 0.9549999833106995, 0.9574999809265137, 0.9642857313156128, 0.9549999833106995, 0.9574999809265137, 0.9537500143051147, 0.9462500214576721, 0.9437500238418579, 0.9437500238418579, 0.9624999761581421, 0.949999988079071, 0.9637500047683716, 0.9637500047683716, 0.9464285969734192, 0.9750000238418579, 0.9637500047683716, 0.9674999713897705, 0.9662500023841858, 0.9512500166893005, 0.9599999785423279, 0.9587500095367432, 0.9612500071525574, 0.9549999833106995, 0.9524999856948853, 0.9821428656578064, 0.9612500071525574, 0.9725000262260437, 0.9700000286102295, 0.9674999713897705, 0.9624999761581421, 0.96875, 0.949999988079071, 0.9700000286102295, 0.9787499904632568, 0.9662500023841858, 0.9642857313156128, 0.9725000262260437, 0.981249988079071, 0.9762499928474426, 0.9712499976158142, 0.9862499833106995, 0.9637500047683716, 0.9674999713897705, 0.9712499976158142, 0.9750000238418579, 0.9800000190734863, 0.9821428656578064, 0.9887499809265137, 0.9750000238418579, 0.9837499856948853, 0.9787499904632568, 0.9787499904632568, 0.9850000143051147, 0.9775000214576721, 0.9850000143051147, 0.9762499928474426, 0.981249988079071, 0.9464285969734192, 0.9862499833106995, 0.9850000143051147, 0.9762499928474426, 0.9825000166893005, 0.9862499833106995, 0.9862499833106995, 0.9800000190734863, 0.9925000071525574, 0.9837499856948853, 0.9825000166893005, 0.9821428656578064, 0.9787499904632568, 0.9862499833106995, 0.9825000166893005, 0.9887499809265137, 0.9887499809265137, 0.9900000095367432, 0.9862499833106995, 0.9887499809265137, 0.9825000166893005, 0.9825000166893005, 0.9642857313156128],
        "type": "scattergl",
        "name": "train_acc"
    }
]


text:
Q: ASP.NET MVC - How exactly to use View Models Let's say I have a page that allows the editing of a user's details, so I have a ViewModel like this:
public class UserViewModel {
    public string Username { get; set; }
    public string Password { get; set; }
    public int ManagerId { get; set; }
    public string Category { get; set; }
}

So on my EditUser action I can have this passed back by the model binder and then I can map that to the Domain Model:
public ActionResult EditUser(UserViewModel user) {
    ...

However, the page that displays the form also needs details such as a list of Managers and Categories to provide dropdowns for those fields.  It might also display a list of other users in a sidebar so you can switch between the different users you're editing.
So then I have another view model:
public class ViewUserViewModel {
    public UserViewModel EditingUser { get; set; }
    public IEnumerable<SelectListItem> Managers { get; set; }
    public IEnumerable<SelectListItem> Categories { get; set; }
    public IEnumerable<SelectListItem> AllUsers { get; set; }
}

Is this the correct way to do it?  Are they both View Models?  If so, is there a naming convention I should use so I can distinguish between VMs that are like models and VMs that just contain data for the page?
Have I got this all wrong?

A: "View Model" is just a pattern. There's nothing magical about the name, but generally any class being passed to a view (whether for simply displaying data or for the purposes of form submissions) is referred to as a "view model" and given a name like FooViewModel or FooVM to indicate that it's part of that "view model" pattern.
I don't want to go too philosophical on you, but I think a little bit of reference about the patterns in play will be helpful. ASP.NET MVC obviously enough encourages an MVC (Model-View-Controller) architectural model. In MVC the Model is the container for all the application's business logic. The Controller is responsible for handling the request, fetching the model, rendering the View with that model and returning a response. That seems like a lot of responsibility but in actuality the framework handles most of this behind the scenes, so Controllers are typically (and should be) very light on code. They are responsible for the bare minimum amount of functionality to wire everything up. Finally, the View is responsible for creating the UI layer that allows the user to interact with the data in the Model. It is not responsible for the data itself, nor should it be (ViewData/ViewBag is a pretty big violation here, at least in as much as the way it ends up being used by developers in practice).
So, that means the bulk of your application logic should be in your model, and typically that's a good thing. However, since the model is the haven of application data, it generally gets persisted in a database or similar. That creates some conflict of interest as you now need to start a balancing act between what data should be persisted and what data should only exist for the purpose of display.
This is where view models come in. MVVM (Model-View-View Model), a somewhat parallel pattern to MVC, recognizes the inherent issues in a one-model-to-rule-them-all approach. I won't go into much detail here, because MVC doesn't use this pattern. However, most ASP.NET MVC developers have co-opted the View Model of MVVM. What you essentially end up with is a database-backed entity (the traditional model) and then usually many different view models that represent that entity in various states. This allows your model to contain the business logic that's relevant to persistence while the view model(s) contain the business logic relevant to displaying, creating and updating that model.
I've gone off track a little, but the long and short is that what you're doing is perfectly acceptable. In fact, it's good practice. Create as many view models as your application requires, and use them to actually store the data and business logic necessary for your views. (That includes things like SelectLists. Neither your controller nor view should need to know how to create a SelectList for a dropdown.)

A: I personally prefer to put all the information required for the page to render in the ViewModel, as that is the purpose of the ViewModel - to provide all of the data for the View.  So my UserViewModel would contain properties for Managers, Categories and AllUsers and the controller would fill those collections prior to passing the ViewModel off to the view.
This is essentially what you have done - it just removes the extra ViewModel from the equation.
I have also seen other programmers use the ViewData to send the dropdown lists to the view, but I dislike that because ViewData is not strongly typed, whereas a ViewModel is.

A: How I do this in shortcut:

*

*Create separate ViewModel class for each form on the page, then I render these classes with PartialViews as @{Html.RenderPartial("PartialName", Model.PartialModel);}.

*If page contains things like html metas I make separated class for metas and put it in section on the page.

*Rest cases like "should I put this in separated class?" is your judgement.

So for example you have page which has some kind of login/register bar or popup whatever.
public class SomePageViewModel
{
    public RegisterBarVM Register { get; set; }
    public LoginBarVM LoginBar { get; set; }

    public MetasVM Metas { get; set; }
    public string MaybePageTitle { get; set;}
    public string MaybePageContent { get; set;}

    [HiddenInput(DisplayValue = false)]
    public int IdIfNeeded { get; set; }

    public IEnumerable<SelectListItem> SomeItems {get; set;}
    public string PickedItemId { get;set; }
}

public class RegisterBarVM
{
    public string RegisterUsername {get;set;}
    public string RegisterPassword {get;set;}
    //...
}

public class LoginBarVM
{
    public string LoginUserame {get;set;}
    public string LoginPassword {get;set;}
    //...
}

//cshtml
@model yourClassesNamespace.SomePageViewModel
@{
    Html.RenderPartial("LoginBar", Model.LoginBar); //form inside
    Html.RenderPartial("RegisterBar", Model.RegisterBar); //form inside

    using(Html.BeginForm())
    {
        @Html.EditorFor(m => m.IdIfNeeded)
        @Hmtl.EditorFor(m => m.MaybePageTitle)
        @Hmtl.EditorFor(m => m.MaybePageContent)

        @Hmtl.DropDownListFor(m => m.PickedItemId, new SelectList(Model.SomeItems))

        <input type="submit" value="Update" />
    }
}

@section Metas {
    @{Html.RenderPartial("Meatas", Model.Metas}
}

About editor templates Brad Wilsons Blog and just google or look for stacks resources about display/editor templates and HtmlHelpers. They all are very useful for building consistent websites.


text:
Q: (MongoDB) database structure for Q&Answer website I'm trying to make a website similar to Yahoo & Answer or StackOverflow (different category, no competition), and I'm stuck at this point, I'll really appreciate any guidance from you guys as I'm very new to MongoDB.
I'm using Express framework on Node.js and MongoDB by the way.
The problem is to find the most efficient way to structure the database for users and questions/answers data.
Currently, there is a Questions model, inside there's a document for each category. Each document contains the question itself, the answers, and other info as described below:
math{
    OpenQuestions{
        'x+2=5, whats x?' : {
            asker: 'peter',
            likes: 12,
            answers: {
                'x is 3' : {
                    answerer: 'john',
                    likes: 25
                },
                'x is 2' : {
                    answerer: 'MATHSUX',
                    likes: 0
                }
            }
        }
    }
    ClosedQuestions{
        //same as OpenQuestions
    }
}

In this way it's very easy to display the questions as we can easily retrieve questions based on the object's creation time and fetch them accordingly on the main question page.
However, if an user wants to see the questions he has asked, the only way I can think of is going through each subject.OpenQuestions.QuestionItSelf.asker, and check if it's the user himself, then fetch all the object matches for this username, it would be an immense calculation. I'm sure there exists a much better way, what do you all think?

A: MongoDB has a limit of 16MB per document. Also, MongoDB doesn't behave very well when you have documents which grow in size. For performance reasons, MongoDB tries to keep a document in a contiguous section on the hard drive, so when a document grows, the hard drive space needs to be reallocated constantly.
For these reasons, it is not a good idea to store all questions in a single document.
It would be better to create a collection of questions and have a separate document for each question. To increase search performance, you can create some appropriate indices.
By the way: I am not sure if MongoDB is the right tool for your project. Your application sounds very relational and not like it can benefit from the document-oriented concept of MongoDB. On the other hand, your hierarchical way of thinking sounds more in tune with the Redis philosophy. But that's just a subjective opinion.

A: First, it's a bad idea to have the question as a key.  Make a question attribute and have the value of that attribute be the text of the question.  MongoDB does not have much in the way of tools to query on key values.  Pretty much all you have is $exists and that doesn't even support wildcards.  Do the same thing for each answer, instead of having the text of the answer be a key, have an answer key and have the value be the text of the answer.
Next, there's no reason to keep all your questions as sub-documents.  You can move the status to an attribute of the document (status: 'open' or status: 'closed' or status: 'answered but not closed' for example).  If you need to pre-compute the status at all that is - it might make more sense to have the answers as sub-documents and then you can derive the status based on the status of the answers (i.e. if a question doesn't have any answers then it's displayed as unanswered, if it has answers but none are marked as the solution then it's answered but not solved, if it has an answer marked as solution then it's closed, etc.).
Then, have the subject be an attribute of the question as opposed to a collection for each subject.  If you do that then finding questions for an asker is as easy as
db.questions.find({asker: 'John'}, {question:1, _id:0})

That will display the text of all questions John has asked
Your final schema will be a questions collection with a document structure that looks like this:
    {
        question: 'x+2=5, whats x?'
        asker: 'peter',
        likes: 12,
        subject: 'math',
        answers: [
            { answer: 'x is 3', answerer: 'john', likes: 25, solution: true },
            { answer: 'x is 2', answerer: 'MATHSUX', likes: 0}
        ],
        status: 'solved'
    }


text:
Q: Youtube video is not showing controllers in uiwebview in ipad hi all i am playing YouTube videos in ipad and iphone it is universal app.in iphone it is showing controlles but in ipad it is not showing the controllers.the code what i have writeen is as below.
-(void)viewWillAppear:(BOOL)animated
{if(self.interfaceOrientation == UIInterfaceOrientationPortrait||self.interfaceOrientation ==UIInterfaceOrientationPortraitUpsideDown)
{

    NSLog(@" before portrait  videowebveiw frame is %f %f %f %f",self.videowebveiw.frame.origin.x,self.videowebveiw.frame.origin.y,self.videowebveiw.frame.size.width,self.videowebveiw.frame.size.height);

    CGRect webviewframe=self.videowebveiw.frame;

    webviewframe.size.width=748.0;
    webviewframe.size.height=1024.0;
    self.videowebveiw.frame=webviewframe;
    embedHTML=[NSString stringWithFormat:@"<embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\"width=768.0 height=1024.0></embed>",self.weburl];

    NSLog(@" after portrait  videowebveiw frame is %f %f %f %f",self.videowebveiw.frame.origin.x,self.videowebveiw.frame.origin.y,self.videowebveiw.frame.size.width,self.videowebveiw.frame.size.height);

}
else if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft||self.interfaceOrientation== UIInterfaceOrientationLandscapeRight)
{

        NSLog(@" before landscape  webview frame is %f %f %f %f",self.videowebveiw.frame.origin.x,self.videowebveiw.frame.origin.y,self.videowebveiw.frame.size.width,self.videowebveiw.frame.size.height);
    CGRect webviewframe=self.videowebveiw.frame;

    webviewframe.size.width=1024.0;
    webviewframe.size.height=748.0;
    self.videowebveiw.frame=webviewframe;

    embedHTML=[NSString stringWithFormat:@"<embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\"width=1024.0 height=768.0></embed>",self.weburl];

        NSLog(@" After landscape  webview frame is %f %f %f %f",self.videowebveiw.frame.origin.x,self.videowebveiw.frame.origin.y,self.videowebveiw.frame.size.width,self.videowebveiw.frame.size.height);

}

    [self loadwebview];

}

-(void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{

    if(toInterfaceOrientation == UIInterfaceOrientationPortrait||toInterfaceOrientation ==UIInterfaceOrientationPortraitUpsideDown)
    {
        NSLog(@" before portrait  videowebveiw frame is %f %f %f %f",self.videowebveiw.frame.origin.x,self.videowebveiw.frame.origin.y,self.videowebveiw.frame.size.width,self.videowebveiw.frame.size.height);
        CGRect webviewframe=self.videowebveiw.frame;

        webviewframe.size.width=748.0;
        webviewframe.size.height=1024.0;
        self.videowebveiw.frame=webviewframe;

        embedHTML=[NSString stringWithFormat:@"<embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\"width=768.0 height=1024.0></embed>",self.weburl];
        NSLog(@" after portrait  videowebveiw frame is %f %f %f %f",self.videowebveiw.frame.origin.x,self.videowebveiw.frame.origin.y,self.videowebveiw.frame.size.width,self.videowebveiw.frame.size.height);

    }
    else if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft||toInterfaceOrientation== UIInterfaceOrientationLandscapeRight)
    {
        NSLog(@" before landscape  webview frame is %f %f %f %f",self.videowebveiw.frame.origin.x,self.videowebveiw.frame.origin.y,self.videowebveiw.frame.size.width,self.videowebveiw.frame.size.height);

        CGRect webviewframe=self.videowebveiw.frame;

        webviewframe.size.width=1024.0;
        webviewframe.size.height=748.0;
        self.videowebveiw.frame=webviewframe;

        embedHTML=[NSString stringWithFormat:@"<embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\"width=1024.0 height=768.0></embed>",self.weburl];
        NSLog(@" After landscape  webview frame is %f %f %f %f",self.videowebveiw.frame.origin.x,self.videowebveiw.frame.origin.y,self.videowebveiw.frame.size.width,self.videowebveiw.frame.size.height);

    }
}


text:
Q: How do I fix "could not activate cellular data network" problem when returning to US after traveling and using a different SIM card? After traveling overseas (Vietnam & Japan) and using a SIM card for each country, I restored my AT&T SIM card into my iPhone and got:

I tried the suggestions in https://support.apple.com/en-us/HT201415 and all of the suggestions in https://appletoolbox.com/2013/04/iphone-could-not-activate-cellular-data-network-fix/ except backing up and restoring, but nothing worked.

A: I called AT&T and was asked to see if there is a profile at the bottom of Settings->General. There was, and deleting it fixed the problem. Apparently profiles are often installed when using overseas SIM cards.


text:
Q: Mongoose Follower and Following query optimization I have a document in mongo for maintaining following and followers for my social app using this one schema.I have close to 3000 records in this document.
var FollowSchema = new Schema({
                uid : {
                    type: Schema.ObjectId,
                    ref: 'User'
                },
                fid : {
                    type: Schema.ObjectId,
                    ref: 'User'
                }
            });

Currently I am fetching all the users who are followers of the logged in users like the below :
       Follow.find({ fid : req.user._id})
      .populate('fid' , {name,_id}).lean().exec(function(err,               details) {
                if (err) {
                    res.status(500).json(err);
                } else {
                    res.status(200).json(details);
                }
            });

Without using inner query or Asycn , is it possible to find if the logged-in user is mutually "following" the followers ?
I looked at MapReduce and aggregation but not sure if that would work.
Any sample code is appreciated.

A: Can't do the mongoose mapping of this in my head, but this is one way to do it in mongodb (4711 here being your uid, note that it's mentioned 3 times in the query)
db.follow.aggregate(
 {$match: {$or: [{uid:4711},{fid:4711}]}},    // Find all entries regarding user.
 {$project:                                   // Project user to uid,
  {z:                                         // followed/follower to fid and
   {$cond:[                                   // the type to followed/followed.
    {$eq:["$uid",4711]},
     {fid:"$fid", following:{$literal:1}},
     {fid:"$uid", followed:{$literal:1}}]
   }
  }
 },
 {$group:{_id:"$z.fid",                       // Group by fid to get the total
          following:{$sum:"$z.following"},    // type of the other user
          followed:{$sum:"$z.followed"}}
 }
)

# You're followed by 3
# { "_id" : 3, "following" : 0, "followed" : 1 }
# You're following 4 and he/she is following you back
# { "_id" : 4, "following" : 1, "followed" : 1 }
# You're follwing 2
# { "_id" : 2, "following" : 1, "followed" : 0 }


text:
Q: change specific span text based on array value using jquery I have some input hidden value in jquery array and i want to change the value of span based on array. Here is the jsfiddle.
Now what i want is when 0 is triggered in an alert box then my current span text will change with some text, not all span text like at this time.

A: You can set the text you want like so:
$('input[name="quantity"][value="0"]').parent().find('button span').html('some text');