text:
Q: Android Studio Installer stuck on "Patching Google APIs Intel x86 Atom_64 System Image 13 to 14" Its been an hour but the progress bar does not respond at all even though wifi connection is quite powerful(100Mb/s) and probably stable. I also tried cancelling, restarting and reinstalling twice before but it always gets stuck at this point.
Although this probably did not affect my workflow till now but I would like to keep everything updated and also know why did this happen and any help will be highly appreciated.


text:
Q: How can I run an application in gnome-terminal automatically when booting? I need to run an application automatically when Ubuntu starts. I've got this app running without opening the terminal. However, this application displays some information in a terminal window and, therefore, I need that the app runs strictly after opening gnome-terminal (automatically). To this end I've tried to create a script file in init.d as it is explained here. The content of the script is:
#!/bin/bash
cd /home/mediambient/programa
/usr/bin/gnome-terminal -e ./driver &

This works if I execute the file, but does not seem to do anything when I reboot the computer. Can anyone tell me what I'm doing wrong?
Thanks in advance.

A: You cannot make a script that runs from init.d and displays a gnome-terminal window, because scripts in init.d run before there is any login session in which to display one. They run even before the graphical user interface is running.
Logging to a File Instead
If you need to run this script when the machine boots up, then instead of trying to make it display text automatically, you should make it write its output to a log file. To make it run both regular output and error output to a log file, make the script as follows:
#!/bin/bash
cd /home/mediambient/programa
./driver &>> logfile
Replace logfile with the name of the log file you want to use. You might have that file in the /home/mediambient/programa folder, or you might put it in the folder for system log files (/var/log). It's your choice. Please note that the &>> operator will append the output to the end of the log file. If you want it to overwrite the log file each time, you should use the &> operator instead.
Running Commands from an Init Script as a non-root User
Please also note that scripts in init.d will be run as root. If you don't want that, but instead want to run programa as user mediambient, you can write the script as follows:
#!/bin/bash
cd /home/mediambient/programa
sudo -u mediambient ./driver &>> logfile
This runs the program as mediambient but still records the log file as root. If you also want to record the log file as mediambient (which you should probably do if you're putting it inside mediambient's home folder), you can use:
#!/bin/bash
cd /home/mediambient/programa
sudo -u mediambient ./driver 2>&1 | sudo -u mediambient tee logfile > /dev/null
(If you're interested in exactly how that works, this explains 2>&1 and this explains tee.)
(By the way, please note that nothing in this script specifically requires bash, which is an excellent interactive shell but is a bit resource-intensive to use for init and background scripts. For quite some time the default shell for running such scripts in Ubuntu has been dash, which is much more lightweight. If you use #!/bin/sh instead of #!/bin/bash, that uses the OS's preferred shell for running POSIX-style shell scripts. For this script, it doesn't matter much, but it's a good habit to get into.)
Running the Script When A User Logs On Graphically, Instead of at Boot Time
Alternatively, if what you really need is for the script to run when the user mediambient logs on graphically (rather than when the computer starts up), then you can make it run driver in a gnome-terminal window. You cannot use init.d for this; instead, you have to use the facility provided by your desktop environment.
If you're running a GNOME-based Ubuntu (with Unity, Unity 2D, GNOME Classic/Fallback, or GNOME Shell as your desktop environment)--which I guess you are, since you want to display the output in a gnome-terminal--then you can do this by pressing Alt+F2 and running gnome-session-properties. This gives you the opportunity to edit your Startup Applications. Put the following in the Command: field:
gnome-terminal --working-directory=/home/mediambient/programa -e ./driver
Running the Script at Boot Time, Logging to a File, and Automatically Viewing the Log when a User Logs On Graphically
Or you can (sort of) get the best of both worlds by putting the script in init.d to run when Ubuntu first starts up, and then automatically spawning a gnome-terminal window showing the output as it progresses, once mediambient logs in graphically. To do that, add an entry to Startup Applications with this command:
gnome-terminal --working-directory=/home/mediambient/programa -x tail -n 512 -f logfile
(Or if logfile is an absolute rather than relative path to the log file, then you can leave out --working-directory=/home/mediambient/programa.)
-n 512 means it displays up to 512 lines of the log file from before it started displaying the log file. (It will then display each line as it is added to the log file.) This is usually a reasonable choice since a gnome-terminal window only remembers up to 512 lines by default anyway. If you run gnome-terminal with a modified profile that remembers more than 512 lines, then you can edit the tail command accordingly.
Limiting the Size of the Log File
If you're concerned about the growing size of the log file, the first thing to do is figure out if this is actually likely to be a problem. You might just be able to estimate. Suppose the log file grows by one line per second (which is much faster than most log files) and each line is 80 characters long. Then in a month, the file is a little of 200 MB in size. In a year it grows to be about 2.5 GB. A couple hundred megabytes is probably fine and multiple gigabytes probably is not, so the question is, will you be able to manually edit the log file to clear it out, at least every few months?
If it's closer to one line per minute, then the file grows at a rate less than 50 MB per year, in which case you probably never have to worry about clearing out the file.
There are two simple ways to clear out the file. You can edit it and remove part (or all) of it. Or you can delete it, and let it be created again. If you delete it, it will continue to take up space on disk until nothing is accessing it anymore, which means you may need to restart driver. You'd also have to restart tail, but you can fix this problem by using a modified tail command that doesn't keep the file open:
gnome-terminal --working-directory=/home/mediambient/programa -x tail -n 512 --follow=name logfile
(I have replaced -f with --follow=name.)
For more advanced, or automatic, management of growing log files, you can use the logrotate command. The logrotate command checks to see if log files have exceeded their maximum size or age, and "rotates" them, compressing them into numbered archives (which are themselves eventually deleted) and making a fresh log file. logrotate will even send you email about the logs, if you set it up to do that. The logrotate manual page explains how to write configuration files to tell logrotate which logs to operate on.
You could run logrotate automatically from mediambient's user crontab. (A crontab lists tasks that are performed on a periodic schedule by the cron daemon.) The crontab command installs and operates on user crontabs. Or you could add an entry to the system crontab, /etc/crontab (which would be a reasonable choice if you're running the script in init.d and having it run driver as root rather than as as mediambient). Please note that Ubuntu's system logs are rotated with logrotate, though in Ubuntu's current default configuration, it is not called directly from any crontab.
This overview of log rotation with logrotate and task scheduling with cron should help you get started, but feel free to ask more detailed questions on AskUbuntu about these topics or, if you prefer, to comment here or edit your question to provide more detail about what you want to do (then I may be able to give more detailed explanations for how to do it).

A: You have this written:
/usr/bin/gnome-terminal -e ./driver &

The & parameter which is at the end of the line means that the program is going to be hidden. This is useful for running background apps like web servers of boot sounds, but in your case you shouldn't use it.  The solution is as simple as removing it:
/usr/bin/gnome-terminal -e ./driver

And I saw that you're not using GNOME for autostart. Use this instructions instead of the Server ones (replace google-chrome with the command above!): Chrome autostart on ubuntu

redpajama_set_name: RedPajamaStackExchange


text:
Q: Open more than one dataset with pandas I would like to implement a function which is able to open more than one dataset at the same time. Dataseth path and names would be passed as argument of the function (path as optional).Datasets are within the same directory and can have different extensions (csv, json and sql) so I can't choose before what of the "xxx" methods I would have to use (.read_csv, .read_json o .read_sql). If l is a list where I have the name of the datasets, for instance:
l = [d1.csv, d2.json]

I think something like the following, syntactically and semantically wrong:
df = []
ext = [".json",".csv",".sql"]

def fun(path, l):
    for i in range(len(l)):
        if "condition on names of l[i] and files on path is TRUE": #controls if the file is within the path
            for j in range(len(ext)):
                if "condition on "ext" is TRUE": #controls the extension of the file
                    df [i] = pandas.read_ext[j](path, l[i])
    return df

Any help?

A: Maybe something like this:
ext_to_fn = {
    ".csv": pd.read_csv,
    ".json": pd.read_json,
    ".xls": pd.read_excel,
}

def pd_open(basename, **kwargs):
    for ext, fn in ext_to_fn.items():
        filename = basename + ext
        if os.path.isfile(filename):
            return fn(filename, **kwargs)
    raise ValueError('No file/loader matching %s' % basename)

It will try each of the known extensions and loaders:
d1 = pd_open("d1")  # tries d1.json, d1.csv, d1.xls
d2 = pd_open("d2")  # etc.

You can also pass any kwargs that are supported by all of the loaders, e.g. dtype and so on.

A: I have some similar function to AKX, in Databricks that invokes a stored procedure in SQL to gather various metadata :
you can use Path.(..).is_file to write some error handling.
r.glob will trawl child directories.
from pathlib import Path
def open_variable_files(parent_path, child_paths=False):
    reader_dict = {
        ".txt": pd.read_csv,
        ".csv": pd.read_csv,
        ".json": pd.read_json,
        ".xlsx": pd.read_excel,
        '.sql'  : pd.read_sql

    }
    if child_paths == False:
        return {f.name: reader_dict[f.suffix](f) for f in Path(parent_path).glob("*")}
    elif child_paths == True:
        return {f.name: reader_dict[f.suffix](f) for f in Path(parent_path).rglob("*")}

variable_files = open_variable_files(path_to_files,child_paths=False)

for k,v in variable_files.items():
    print(k,v.head(1))

File20200610.csv    Unnamed: 0  e  f
0           0  0  0
File20201012.json   Unnamed: 0  c  d
0           0  0  0
File20201012.sql    Unnamed: 0  c  d
0           0  0  0
File20201012.txt    Unnamed: 0  c  d
0           0  0  0
output.xlsx    a
0  1


text:
Q: Do memory mapped objects get freed up automatically after a thread terminates? I have a few quick questions. If I create a new child thread in C, after the thread has finished its processing and it terminates, do:

*

*Memory mapped objects get "automatically" freed up? (I know C does not have a garbage collector, but at this point the child has terminated)

Guess I posted too fast. Found the answer to the second question (for future ref): http://www.ibm.com/developerworks/linux/library/l-memory-leaks/index.html?ca=drs-

*

*Can the child return a value to the parent thread? (Is this possible using some common routine? I know that the memory space of the child and parent are the same?)

Also I would like to mention that the OS is POSIX compliant.
Thanks,
Neco

A: As you already found out, the answer to your first question is "no". That goes for objects allocated on the heap too.
There is no parent&child relationship between threads in a process, so "parent thread" is meaningless. But, yes, threads can return a value when they exit. The prototype for a thread's toplevel function is:
void *function(void *);

Observe that the return type is void *. Threads can return a pointer (to anything you like). This return value will be retrieved by any other thread that waits for the returning thread to complete using pthread_join().

A: Resources like memory, file handles, mutexs, etc. are not released when a thread exits.  However, all process related resources are released when a process exits which includes all those types of objects.


text:
Q: Table width -different in different browsers when sending via Gmail I have following table:

                        some text

                        some text

                        some text

                        some text

                        another text

                        another text

                        another text

                        another text

In Mozilla, this table has width:600px, but in Google Chrome, it has width: 700px. My code is the same. If I make
 in Mozilla, it looks good, but in Chrome, it should be
.
How could I make my table compatible with different browsers? I also tried with Bootstrap Grid System, but t's still the same. Problem is different width of div or table.
Edited: This happens when when I send this table as html file via Gmail. When I see it as a view in different browsers, it's good. But when I send it in Gmail, there are differences of table width.


text:
Q: How to load data in hive without using the variable name I have a list of 2000 variables in a weekly file. These 2000 variables are not fixed and i wanted to load this data into hive.
Currently,I  am getting the list of variables in the file using pearl and then manually loading the file by changing my hive code.
Is there any way i can automate the process?


text:
Q: How do I take a photo programmatically I'm developing an app which get image whenever server call and send that image to server. Here is some code in CameraSurfaceView class which I define.
private SurfaceHolder holder;
private Camera camera;
private Bitmap osb;
public void takeImage(){
    Camera camera = this.getCamera();
    CameraSurfaceView.HandlePictureStorage c = this.new HandlePictureStorage();
    camera.takePicture(null, null, c);
}
public byte[] getImage(String type) {
    if (osb==null) {
        System.err.println("Camera.getImage: osb NULL");
        return  null;
    }

    CompressFormat format = CompressFormat.JPEG;
    if (type.equals("PNG")) {
        format = CompressFormat.PNG;
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        System.err.println("Camera.getImage: decoded");
        osb.compress(format, 100, out);
        System.err.println("Camera.getImage: compressed");
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } finally {
        //lock.unlock();
    }

    byte[] bytes = out.toByteArray();
    return bytes;
}

public void saveImage(byte[] picture) {
    System.err.println("saveImage");
    osb = BitmapFactory.decodeByteArray(picture, 0, picture.length);
}

and inner class HandlePictureStorage implements PictureCallBack
@Override
public void onPictureTaken(byte[] picture, Camera camera)
{
    CameraSurfaceView.this.saveImage(picture);
}

when I call takeImage() and then getImage() function from outer , i expected that the code on onPictureTaken(byte[] picture, Camera camera) of class HandlePictureStorage will be executed right after takeImage()  to save image and before getImage() so getImage() have data to retrieve.

Unfortunately, when i see on the logcat, the getImage() function run right after takeImage() and before onPictureTaken(). hence, it's obvious that takeImage can only get null data because there is no picture was saved before.
if run takeImage() and getImage() again, function getImage() will return the picture of previous shot.

A:     CameraProjectActivity.java ----> main activity

    public class CameraProjectActivity extends Activity
    {
        public static ImageView image;
        private Button btn_camera;

        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            image = (ImageView) findViewById(R.id.image);

            btn_camera = (Button) findViewById(R.id.btn_camera);
            btn_camera.setOnClickListener(new View.OnClickListener()
            {

                @Override
                public void onClick(View v)
                {
                    Intent i = new Intent(CameraProjectActivity.this,CameraView.class);
                    startActivityForResult(i, 999);
                }

            });
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent intent)
        {
           if(requestCode==999)
           {
               if(resultCode==585)
               {
                   //Intent Works
               }
               else
               {
                   alert("Picture not Captured!");
               }
           }
        }

        private void alert(String string)
        {
            AlertDialog.Builder alert=new AlertDialog.Builder(CameraProjectActivity.this);
            alert.setMessage(string);
            alert.setTitle("Alert");
            alert.setNeutralButton("Ok",null);
            alert.show();
        }
    }

    CameraView.java

    public class CameraView extends Activity implements SurfaceHolder.Callback, OnClickListener
    {
        private static final String TAG = "CameraTest";
        Camera mCamera;
        boolean mPreviewRunning = false;

        public void onCreate(Bundle icicle)
        {
            super.onCreate(icicle);
            Log.e(TAG, "onCreate");

            getWindow().setFormat(PixelFormat.TRANSLUCENT);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
            setContentView(R.layout.cameraview);
            mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
            mSurfaceView.setOnClickListener(this);
            mSurfaceHolder = mSurfaceView.getHolder();
            mSurfaceHolder.addCallback(this);
            mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }

        @Override
        protected void onRestoreInstanceState(Bundle savedInstanceState)
        {
            super.onRestoreInstanceState(savedInstanceState);
        }

        Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {

            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                // TODO Auto-generated method stub
                if (data != null)
                {
                    //Intent mIntent = new Intent();
                    //mIntent.putExtra("image",imageData);

                    mCamera.stopPreview();
                    mPreviewRunning = false;
                    mCamera.release();

                     try
                       {
                       BitmapFactory.Options opts = new BitmapFactory.Options();
                       Bitmap bitmap= BitmapFactory.decodeByteArray(data, 0, data.length,opts);
                       bitmap = Bitmap.createScaledBitmap(bitmap, 480, 480, false);
                       CameraProjectActivity.image.setImageBitmap(bitmap);
                       }
                       catch(Exception e)
                       {
                             e.printStackTrace();
                       }
                    //StoreByteImage(mContext, imageData, 50,"ImageName");
                    //setResult(FOTO_MODE, mIntent);
                    setResult(585);
                    finish();
                }
            }
        };

        protected void onResume()
        {
            Log.e(TAG, "onResume");
            super.onResume();
        }

        protected void onSaveInstanceState(Bundle outState)
        {
            super.onSaveInstanceState(outState);
        }

        protected void onStop()
        {
            Log.e(TAG, "onStop");
            super.onStop();
        }

        public void surfaceCreated(SurfaceHolder holder)
        {
            Log.e(TAG, "surfaceCreated");
            mCamera = Camera.open();
        }

        public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
            Log.e(TAG, "surfaceChanged");

            // XXX stopPreview() will crash if preview is not running
            if (mPreviewRunning)
            {
                mCamera.stopPreview();
            }

            Camera.Parameters p = mCamera.getParameters();
            p.setPreviewSize(w, h);
            mCamera.setParameters(p);
            try
            {
                mCamera.setPreviewDisplay(holder);
            }
            catch (Exception e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            mCamera.startPreview();
            mPreviewRunning = true;
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            Log.e(TAG, "surfaceDestroyed");
            //mCamera.stopPreview();
            //mPreviewRunning = false;
            //mCamera.release();
        }

        private SurfaceView mSurfaceView;
        private SurfaceHolder mSurfaceHolder;

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            mCamera.takePicture(null, mPictureCallback, mPictureCallback);
        }
    }

    cameraview.xml

    <?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:orientation="vertical">
        <SurfaceView android:id="@+id/surface_camera"
            android:layout_width="fill_parent" android:layout_height="10dip"
            android:layout_weight="1">
        </SurfaceView>
    </LinearLayout>

    main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <Button android:id="@+id/btn_camera"
            android:text="Take a Picture from Camera"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:gravity="center"
            >
            </Button>
            <ImageView
            android:layout_height="480px"
            android:layout_width="480px"
            android:scaleType="fitXY"
            android:id="@+id/image"
            android:src="@drawable/android"
            />
    </LinearLayout>

// Dont forgot to add the below code in AndroidManifest.xml
// <uses-permission android:name="android.permission.CAMERA"></uses-permission>
//    <uses-feature android:name="android.hardware.camera" />
// <uses-feature android:name="android.hardware.camera.autofocus" />

A: Camera application runs in a separate  process and your callback is executed  at later time ( say, it trains autofocus,  fires flasch  , encodes JPEG - it takes time )  and you can not control duration. So, you have to change control flow.  Why not call your getImage() from  picture callback?


text:
Q: Allow user to login from one device only I want to allow user to be able to login in one device only
I had this idea which is once user is logged in I will send his device token and is logged in flag.
Once he try to login using another device I will check if he's logged in in another device. If yes I will overwrite his token to the new device then I will perform log out from first device.
I don't want to prevent user from logging in from second device cause user might uninstall the app or the user phone is lost or any other case that we can't handle.
But the question is how can I perform logout from first device automatically
I don't want to send device token with all our APIs call and then check if against the saved token.
I'm not actually sure if it's doable. If it's not how can I handles cases like
uninstall app?
UPDATE
I found that snapchat use this approach they allow user to login in new device then they log him out from the old device. still not sure how they do this?


text:
Q: tksnack- Trying to create waveform I am trying to use tksnack to create a waveform that moves in real time to the sound being played. I found some example code that more or less does what I want.
#! /usr/bin/env python

from Tkinter import *
from tkSnack import *

root = Tkinter.Tk()
initializeSnack(root)
snd = Sound()
def start():
    snd.record()

c = SnackCanvas(height=500, width=1920, bg='white')
c.pack()
c.create_waveform(1,1,sound=snd,width=1920,height=500,pixelspersec=500)

start()
root.mainloop()

However this example takes in audio from the microphone but I want to just give it an mp3. How would I go about doing this? I tried substituting snd.read(file)  for snd.record() but that didn't work.

A: You can also use the package snackogg...the tksnack works in Linux with the libsnack-alsa fine. I dont know with snackogg.
Here in example with record a track - I put buttons to youre source.
#! /usr/bin/env python

    from Tkinter import *
    from tkSnack import *

    root = Tkinter.Tk()
    root.geometry("650x560+100+80")
    initializeSnack(root)
    snd = Sound()

    def start():
        snd.record()

    def stop():
        snd.stop()

    def play():
        snd.play()

    def save():
        file = root.tk.call('eval', 'snack::getSaveFile')
        snd.write(file)

    c = SnackCanvas(height=500, width=820, bg='white')
    c.pack()

    c.create_waveform(1,1,sound=snd,width=1920,height=500,pixelspersec=500)

    record=Button(root,width=50,height=50,fg='red', bitmap='snackRecord',command=start).place(x=5,y=501)
    stop=Button(root,width=50,height=50,fg='black', bitmap='snackStop',command=stop).place(x=60,y=501)
    play=Button(root,width=50,height=50,fg='black', bitmap='snackPlay', command=play).place(x=115,y=501)
    save=Button(root,width=5,height=3,fg='black', text='Save', command=save).place(x=170,y=501)
    root.mainloop()


text:
Q: PHP does not receive complete data when send it by AJAX So I'm building a mobile (cordova) app using a mySQL server, PHP, javascript (jQuery) but I have encountered a rather annoying problem.
When sending a test string with AJAX the recieving end, a PHP script does not receive all the data:
function testJson() {
  $.ajax({
    type: 'POST',
    data: {
      text: "hello, this is a test to see if the string is send."
    },
    url: 'http://a.working.url/save.php',
    success: function(data) {
      alert('succes');
    },
    error: function(data) {
      alert('There was an error adding your comment');
    }
  });

  return false;
}

then at the serverside I have a small PHP script:
<?php
$server = "localhost:3307";
//changed port to 3307
$username = "user";
$password = "pass";
$database = "test";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());

mysql_select_db($database, $con);

$comment = $_POST['text'];
echo $comment;

$sql = "INSERT INTO data (comment) ";
$sql .= "VALUES ('$comment')";

if (!mysql_query($sql, $con)) {
    die('Error: ' . mysql_error());
} else {
    echo "Comment added";
}

mysql_close($con);
?>

but this PHP script did not recieve the full string, when I check using:
echo $_POST['text']

It only got: "hello, this is a test to see if the" (without quotes).
If anybody can help me it would be great cause I cannot continue working on the app unless the data transfer works.
Thanks in advance.


text:
Q: resizing image while saving it's exif orientation with node-gm I'm writing a nodeJS 5.3.0 application using gm (http://aheckmann.github.io/gm/)
I know that it uses the GraphicsMagicK library.
the problem is that I'm having is that after I resize an image, it loses it's exif format. the code samples actually shows that the exif format is lost.
for example:
var fs = require('fs')
  , gm = require('gm').subClass({imageMagick: true});

// resize and remove EXIF profile data
gm('/path/to/my/img.jpg')
.resize(240, 240)

in this example they say that exif profile data is removed.
I know that I can get the orientation of an image before resizing using:
gm('path/tp/my/img.jpg').orientation(function(err,value){
                var orientation = value;
});

the question is..
can I preserve exif data when resizing ? and If not.. can I set exif orientation data after resizing ?
thanks

A: More specifically in the following code, only noProfile() function remove EXIF, so if you remove it you can preserve EXIF data
 // resize and remove EXIF profile data
gm('/path/to/my/img.jpg')
   .resize(240, 240)
   .noProfile()
   .write('/path/to/resize.png', function (err) {
   if (!err) console.log('done');
});

Otherwise you can check the gm doc here


text:
Q: Necesito ayuda con laravel y jquery y ajax, estoy aprendiendo me podran dar una mano   estoy tratando de hacer un enviar de un form de un solo campo email con ajax y jquery pero no lo logro hacer función, no me envía alguien me puede ayudar, es la primera vez que trabajo con ajax

este es el script del formulario

A: Prueba poniendo los métodos done(), fail(), always() en tu petición y trata de ordenar el código, veo que en el form hay dos input y uno no tiene el atributo name. Si vas usar jQuery para manipular el DOM que así sea:
document.getElementById('contact_us').reset();
$('#contact_us')[0].reset();

Intenta con este script:
$('#contact_us').on('submit', function (e) {
    if (!e.isDefaultPrevented()) {
        let url = "/correo";
        $.ajax({
            type: "POST",
            dataType: 'json',
            url: url,
            data: $(this).serialize(),
            success: function (response) {
                console.log(response);
                //respuesta exitosa del servidor
                //código con la respuesta del servidor
            }
        })
            .done(function (response) {
                //código cuando se complete el request
                console.log('ERROR: ' + response.err);
                $('#contact_us')[0].reset();
            })
            .fail(function (response) {
                //código cuando falle el request
                console.log('ERROR: ' + response.err);
            })
            .always(function () {
                //código que se ejecuta siempre request exitoso o request erroneo
                console.log("COMPLETE");
                $('#contact_us')[0].reset();
            });
        return false;
    }
});


text:
Q: Cannot check if point is on polyline. Islocationonedge function does not work I have a route and a point that's on the route. However, When I use the islocationonedge function to check, it doesn't work. I've adjusted the tolerance level but that doesn't solve the problem. I know this point is on the route but why isn't islocationonedge function confirming this? What am I doing wrong here?
 var addresses = [
  [
    [43.674687, -79.430955],
    [43.668560, -79.394924]
  ],
  [
    [43.674934, -79.426182],
    [43.675452, -79.423602]
  ],
  [
    [43.640381, -79.394508],
    [43.640575, -79.394586]
  ]
];

 var directionsRenderer = new google.maps.DirectionsRenderer();
 var directionsService = new google.maps.DirectionsService();
    var map = new google.maps.Map(document.getElementById("map"), {
      zoom: 7,
      center: {
        lat: 41.85,
        lng: -87.65
      }
    });

    directionsRenderer.setMap(map);

    var start = new google.maps.LatLng(43.674687, -79.430955);
    var end = new google.maps.LatLng(43.668560, -79.394924);

    directionsService.route(
      {
        origin: start,
        destination: end,
        travelMode: "DRIVING"
      },
      function(response, status) {
        if (status === "OK") {
      directionsRenderer.setDirections(response);
      var paths = response.routes[0].overview_path;
          var polyline = new google.maps.Polyline({
          path: paths
          });

         if (google.maps.geometry.poly.isLocationOnEdge(new google.maps.LatLng(addresses[1][1]), polyline, 1e-3)) {
    alert("Working");
  } else {
      alert("not working");
  }

        } else {
          window.alert("Directions request failed due to " + status);
        }

      }

    );

A: The isLocationOnEdge function takes 2 or 3 arguments, per the documentation:

isLocationOnEdge(point, poly[, tolerance])
Parameters:
point:  LatLng
poly:  Polygon|Polyline
tolerance:  number optional
Return Value:  boolean
Computes whether the given point lies on or near to a polyline, or the edge of a polygon, within a specified tolerance. Returns true when the difference between the latitude and longitude of the supplied point, and the closest point on the edge, is less than the tolerance. The tolerance defaults to 10-9 degrees.

The point argument must be a google.maps.LatLng
addresses[1][1] is an array of numbers.  The google.maps.LatLng constructor takes two numbers, not an array of two numbers. From the documentation:

Constructor LatLng
LatLng(lat, lng[, noWrap])
Parameters:
lat:  number
lng:  number
noWrap:  boolean optional
Creates a LatLng object representing a geographic point. Latitude is specified in degrees within the range [-90, 90]. Longitude is specified in degrees within the range [-180, 180]. Set noWrap to true to enable values outside of this range. Note the ordering of latitude and longitude.

proof of concept fiddle

code snippet:

"use strict";

function initMap() {
  var addresses = [
    [
      [43.674687, -79.430955],
      [43.668560, -79.394924]
    ],
    [
      [43.674934, -79.426182],
      [43.675452, -79.423602]
    ],
    [
      [43.640381, -79.394508],
      [43.640575, -79.394586]
    ]
  ];

  var directionsRenderer = new google.maps.DirectionsRenderer();
  var directionsService = new google.maps.DirectionsService();
  var map = new google.maps.Map(document.getElementById("map"), {
    zoom: 7,
    center: {
      lat: 41.85,
      lng: -87.65
    }
  });

  directionsRenderer.setMap(map);

  var start = new google.maps.LatLng(43.674687, -79.430955);
  var end = new google.maps.LatLng(43.668560, -79.394924);

  directionsService.route({
      origin: start,
      destination: end,
      travelMode: "DRIVING"
    },
    function(response, status) {
      if (status === "OK") {
        directionsRenderer.setDirections(response);
        var paths = response.routes[0].overview_path;
        var polyline = new google.maps.Polyline({
          path: paths,
          map: map
        });
        var marker = new google.maps.Marker({
          position: new google.maps.LatLng(addresses[1][1][0], addresses[1][1][1]),
          map: map,
          title: "1",
          icon: {
            url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
            size: new google.maps.Size(7, 7),
            anchor: new google.maps.Point(3.5, 3.5)
          }
        })
        if (google.maps.geometry.poly.isLocationOnEdge(new google.maps.LatLng(addresses[1][1][0], addresses[1][1][1]), polyline, 1e-3)) {
          document.getElementById('status').innerHTML = "Working";
        } else {
          document.getElementById('status').innerHTML = "not working";
        }

      } else {
        window.alert("Directions request failed due to " + status);
      }

    }

  );
}
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 90%;
}

/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>

  <title>Directions Service</title>


text:
Q: Unable to install vagrant-hostupdater plugin during Vagrant up with VVV I'm new to Vagrant and my aim is to install Varying Vagrant Vagrants. I was following the steps mentioned in VVV's GitHub page but I'm stuck up when installing vagrant-hostupdater mentioned in step 4.
I'm getting the following error when I tried to install the vagrant-hostupdater plugin.
Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

C:\Users\Daniel>vagrant plugin install vagrant-hostupdater
Installing the 'vagrant-hostupdater' plugin. This can take a few minutes...
Bundler, the underlying system Vagrant uses to install plugins,
reported an error. The error is shown below. These errors are usually
caused by misconfigured plugin installations or transient network
issues. The error from Bundler is:

Could not find gem 'vagrant-hostupdater (>= 0) x86-mingw32' in any of the gem so
urces listed in your Gemfile or available on this machine.

Warning: this Gemfile contains multiple primary sources. Using `source` more tha
n once without a block is a security risk, and may result in installing unexpect
ed gems. To resolve this warning, use a block to indicate which gems should come
 from the secondary source. To upgrade this warning to an error, run `bundle con
fig disable_multisource true`.

I'm running Windows 8.1 64-bit OS and I installed Virtual Box 5.0 and Vagrant 1.8.1
Has anyone encountered the above issue?
I found a question similar to mine, in stackoverflow. Will the answer mentioned in the specified similar question help in fixing mine?

A: I have tried it and seen the github page you have shared.
Well, in your case you are making a typo i.e. spelling error:
its not 'vagrant-hostupdater', it's called the 'vagrant-hostsupdater' package, you are missing an 's' in there.
Here is the github page hosting the vagrant-hostsupdater code:
https://github.com/cogitatio/vagrant-hostsupdater


text:
Q: How do i attach image form ui view to email body I have a small ui view that alows user to select a pic form camera roll, i want to attach it along with my text fields in email.
.h
 @property (strong, nonatomic) IBOutlet UIImageView *imageView;

 .m
  NSString *emailBody = [NSString stringWithFormat:@(textboxes and other outlets are      here)"%@"imageView.image];

When emailed  I get the text strings attached but not the image? Coul dsomeone point me in the right direction on this, thanks
xcode 4.3

A: try this link to send images by email
http://iosdevelopertips.com/email/how-to-send-email-with-attachments-example-using-iphone-camera-to-email-a-photo.html
if that is not what u want u may have to  convert image to nsdata using the functions
NSData *data=UIImageJPEGRepresentation(image, 1.0);

now convert this data to string by base64encoding and then attach to string.


text:
Q: Google Map API V2 in Fragment I want to use Google Maps in Fragment to show current location of user but before that I wanted just to show map. When I tested I have error as in the picture. What the best way to add Google Map API V2 and whats the reason to error?
fragment.xml
<fragment
         android:id="@+id/googleMap"
         android:layout_width="wrap_content"
         android:layout_height="match_parent"
         class="com.google.android.gms.maps.SupportMapFragment"/>

Fragment.java
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
       GoogleMap mGoogleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.googleMap)).getMap();
}

Manifect file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="www.smartavenue.com.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<uses-feature android:glEsVersion="0x00020000" android:required="true"/>

<!--meta-data is in the application-->
<meta-data
      android:name="com.google.android.gms.version"
      android:value="@integer/google_play_services_version" />

 <meta-data
       android:name="com.google.android.maps.v2.API_KEY"
       android:value="My key"/>

In build.gramble I added: compile 'com.google.android.gms:play-services:6.5.+'
Error:

A: Please try this :
 Google Map API V2 Demo

A: The problem is in this line :

Multiple dex file define Lcome/google/ads/Adrequest

you have two library in your gradle file which both use AdRequest library
In your gradle file, check and clean the conflict libraries.
try building with --debug or --stacktrace to see the exact libraries which have conflicts


text:
Q: How to portforward a site We have a website, and my superiors asked me to install the mail server that is packaged with Synology. As I mess around with port forwarding I was able to set the mail server and the NAS to connect in the internet (meaning I can now access the NAS through internet).
The problem is the website is gone.
How should I fix it? I am using a ZyXEL router and because of my idiocy I cannot remember the default settings in the port forward.

A: Websites typically run on port 80 and should be the default port. I would suspect you've changed all the ports to forward to your NAS. You need to convert it back to port 80.
This will then remove your mail server, but you can specificy the port after the domain name, eg, www.mysite.com:1234  (using port 1234).
You may be able to control this using different domain names, but it does depend on your set up...


text:
Q: Unable to locate packages on Linux Debian I am new to using Linux Debian. I am trying to run a python 2 file on a raspberry pi through ssh. However, I can't import modules through PuTTY. Whenever I try to import a module, I see this error:
~/Coding/raspberry pi/python 2 $ apt-get install keyboard
E: unable to locate package keyboard

I tried sudo-apt get update and sudo-apt get upgrade but it still gives the same error. I found a couple of answers such as this and this but none of them worked. Does anyone know why it can't locate modules? Should I try installing something like pip for this?

A: I got it working using pip as the root. Because the keyboard package uses the keyboard, it requires the root password.


text:
Q: GCC differently treats an object and a static library regarding undefined symbols Recently I discoved that Linux linker does not fail due to undefined symbols from static libraries, however does fail due to the same undefined symbols if I link directly with te object files. Here is a simple example:
Source code:
$ cat main.c
int main() { return 0; }
$ cat src.c
int outerUnusedFunc() {
    return innerUndefinedFunc();
}
int innerUndefinedFunc();

Creating *.o and *.a from it, comparing using "nm":
$ gcc -c -o main.o main.c
$ gcc -c -o src.o src.c
$ ar r src.a src.o
ar: creating src.a
$ nm src.o
                 U innerUndefinedFunc
0000000000000000 T outerUnusedFunc
$ nm src.a

src.o:
                 U innerUndefinedFunc
0000000000000000 T outerUnusedFunc

(Here we clearly see that both *.o and *.a contain the equal symbols list)
And now...
$ ld -o exe main.o src.o
src.o: In function `outerUnusedFunc':
src.c:(.text+0xa): undefined reference to `innerUndefinedFunc'
$ echo $?
1
$ ld -o exe main.o src.a
$ echo $?
0

What is the reason for GCC to treat it differenty?

A: If you read the static-libraries tag wiki
it will explain why no object files from src.a are linked into your program, and therefore
why it doesn't matter what undefined symbols are referenced in them.
The difference between an object file foo.o and a static library libfoo.a, as linker inputs, is
that an object file is always linked into your program, unconditionally, whereas the same object file
in a static library library, libfoo.a(foo.o), is extracted from libfoo.a and linked into
the program only if the linker needs it to carry on the linkage, as explained by the tag wiki.
Naturally, the linker will give errors only for undefined references in object files that are linked into the program.
The behaviour you are observing is behaviour of the linker, whether or not you invoke it via a GCC
front-end.
Giving the linker foo.o tells it: I want this in the program. Giving the linker
libfoo.a tells it: Here are some object files that you might or might not need.

A: In the second case — with static library — command line with  says "build exe from main.o and add all required things from src.a".
ld just ignores the library because no external symbols required for main.o (outerUnusedFunc is not referenced from main.o).
But in the first case command line says "build exe from main.o and src.o".
ld should place src.o content into output file.
Hence, it obligate to analyze src.o module, add outerUnusedFunc into output file and resolve all symbols for outerUnusedFunc despite it is unused.
You can enable garbage collection for code sections
gcc --function-sections -Wl,--gc-sections -o exe main.c src.c

In this case outerUnusedFunc (as well as all other functions) will be placed
in separate section. ld will see that this section unused (no symbols referenced). It will remove all the section from output file so that innerUndefinedFunc would not be referenced and the symbol should not be resolved — the same result as for library case.
On the other hand, you can manually reference outerUnusedFunc as "undefined" so that ld should find it in library and add to output file.
ld -o exe main.o -u outerUnusedFunc src.a

in this case the same error (undefined reference to innerUndefinedFunc) will be produced.


text:
Q: Why doesn't the "watch" command work on an alias? So I've made my customized alias command and tried to use it with alias, but my alias was not recognized while concatenated with the watch command.
So I tried to make a thread of it and fortunately, this one helped me out.
But what is the reason for this?
I've created an alias in my .bashrc which works perfectly fine.
alias gpu='sensors nouveau-pci-0100'
alias cpu='sensors coretemp-isa-0000'

and when I concatenate watch and gpu like this:
watch GPU

I get this below every 2 seconds:
sh: 1: gpu: not found

And I solved it regarding the mentioned thread above like this:
alias = watchh='watch '
watchh gpu

But why does this happen? Why can' It use my surely defined alias command?
My guess is it is something about the user because I've gone root once and I couldn't use my alias but I surely need an expert to answer this.

A: The watch command does not locate aliases, only commands in your search path. As an alternative, define gpu and cpu as shell scripts instead of aliases and place them in your search path. Then your watch gpu and watch cpu commands will work fine.
For example, if $HOME/bin is a directory in your search path, create a file $HOME/bin/gpu containing the line:
sensors nouveau-pci-0100

Make the file executable:
$ chmod +x $HOME/bin/gpu

and you're ready to go!
$ watch gpu

Then do the same for cpu.

A: It's nothing to do with users.
Aliases are only expanded in the interactive shell for which they are defined - so an interactive bash shell if you defined them via ~/.bashrc, or an interactive zsh shell if you define them in ~/.zshrc for example.
The watch command invokes commands via a non-interactive /bin/sh shell.
By aliasing watch itself, as alias watchh='watch ' (with a trailing space) and then using watchh gpu, you force the current interactive shell to expand gpu before it's passed to watch.
Note that in zsh, aliases may be defined as global which allows them to be expanded anywhere in a command - avoiding the need to alias watch with a trailing space.


text:
Q: Get shortest circle path without repeating any nodes I need a query that will get me the shortest circle path between nodes (so if there are multiple paths just returns the shortest one). In addition, these paths shouldn't contain repeated nodes. Examples:

In this case, if I pass "Item B" as input, I should receive the path "Item B -> Item C -> Item E -> Item B" since the other path "Item B -> Item C -> Item A -> Item C -> Item E - Item B" not only is longer but also contains repeated nodes (Item C)
Using the same picture, if I pass "Item A" as input, I should receive the path "Item A -> Item C  -> Item A"
In addition, it would be nice if the response could include all the nodes involved, without repeating the starting and final node that is the same in all cases.
Thanks in advance!

A: Try something like:
MATCH (n:Node{id:"a"})
MATCH p=(n)-[*..20]->(n)
WITH p, length(p) as len
ORDER by len ASC LIMIT 1
UNWIND nodes(p) as node
RETURN distinct node

Not sure how well it scales though, note that I added a filter that checks for paths only 20 or fewer hops away.


text:
Q: HTTP Post from Excel VBA RingCentral FaxoutAPI I need help getting this code to work. I'm completely new at programming in VBA as well as anything related to HTTP Post and forms. I've tried to do everything to make it work by reading questions here and following the API help but nothing seems to work.
Here is the website where you can find the API Reference:
http://service.ringcentral.com/faxoutapi/
Also here is the code I have so far:
Sub POST()
Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
Dim strURL As String
Dim PostData As String
strURL = "https://service.ringcentral.com/faxapi.asp"
Const Boundary As String = "---------------------------7d54b1fee05aa"
WinHttpReq.Open "POST", strURL, False

WinHttpReq.setRequestHeader "Content-Type", "multipart/form-data; boundary=" & Boundary

PostData = "--" & Boundary & vbCrLf
PostData = PostData & "Content-Disposition: form-data; name=""Username""" & vbCrLf
PostData = PostData & "username" & vbCrLf
PostData = PostData & "--" & Boundary & vbCrLf
PostData = PostData & "Content-Disposition: form-data; name=""Password""" & vbCrLf
PostData = PostData & "password" & vbCrLf
PostData = PostData & "--" & Boundary & vbCrLf
PostData = PostData & "Content-Disposition: form-data; name=""Recipient""" & vbCrLf
PostData = PostData & "faxnumber" & vbCrLf
PostData = PostData & "--" & Boundary & vbCrLf
PostData = PostData & "Content-Disposition: form-data; name=""Coverpagetext""" & vbCrLf
PostData = PostData & "This is a test fax from web" & vbCrLf
PostData = PostData & "--" & Boundary & vbCrLf

WinHttpReq.Send (PostData)
MsgBox WinHttpReq.ResponseText

End Sub

I keep getting a response value of 5 which means a generic error. I'm pretty sure the form doesn't match the correct format. I would also like to be able to upload a file as shown in the API's reference.
Thanks in advance

A: The FaxOut.asp API endpoint was end-of-lifed on August 9 2018.
See more in the noticed here:
https://support.ringcentral.com/article/Legacy-API-End-of-Life-Announcement-RingOut-asp-FaxOut-asp.html
Use the new endpoint at:
https://platform.devtest.ringcentral.com/restapi/v1.0/account/{accountId}/extension/{extensionId}/fax
https://developers.ringcentral.com/api-reference/Fax/createFaxMessage


text:
Q: How to control loading order when mixing auto-configure and component scan in Spring Boot The user story is like this:
We have exposed some APIs through library jars which use the Spring Boot auto-configure mechanism. The APIs need some glue logic during initialization, so we put them under @PostConstruct block of some @Configurations and register them as auto-configured.
The user code is based on @SpringBootApplication, while they prefer to use @ComponentScan to define beans instead auto-configure.
So the issue comes, Spring always tries to load the beans defined by @ComponentScan first, then those auto-configured beans. So if any user bean relies on the API that not been initialized, it sure will fail.
It seems there's no way to define the bean order when mixing the auto-configured and component-scanned beans. The @Order, @AutoConfigureOrder, @AutoConfigureAfter, @AutoConfigureBefore annotation and Ordered interface only work among all auto configured beans.
Of course if user uses auto-configure for their beans too, it will work without problem. But from user's perspective, @ComponentScan looks a more natural and easier way, especially @SpringBootApplication implies the @ComponentScan of current java package.
Our current workaround is to eager load those API initialization configures at a very-early stage. For web context, it's ServletContextInitializer.onStartup(), and for other generic context, it's LoadTimeWeaverAware's @PostConstruct.
@Configuration
@ConditionalOnWebApplication
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
public class EagerInitWebContextInitializer implements ServletContextInitializer, PriorityOrdered
{

    @Autowired
    private ApplicationContext appContext;

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        String[] beanNames = appContext.getBeanNamesForAnnotation(EagerInitializer.class);

        if (beanNames != null) {
            // pre-load all eager initializers
            for (String name : beanNames) {
                appContext.getBean(name);
            }
        }
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}

@Configuration
@ConditionalOnNotWebApplication
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
public class EagerInitGenericContextInitializer implements LoadTimeWeaverAware, PriorityOrdered
{

    @Autowired
    private ApplicationContext appContext;

    @PostConstruct
    protected void init() {
        String[] beanNames = appContext.getBeanNamesForAnnotation(EagerInitializer.class);

        if (beanNames != null) {
            // pre-load all eager initializers
            for (String name : beanNames) {
                appContext.getBean(name);
            }
        }
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    @Override
    public void setLoadTimeWeaver(LoadTimeWeaver loadTimeWeaver) {
        // does nothing
    }
}

This actually works well. But just wondering is there any better way to achieve this or whether future Spring version can provide a similar systematic way?


text:
Q: Input to different attributes values from a random.sample list so this is what I'm trying to do, and I'm not sure how cause I'm new to python. I've searched for a few options and I'm not sure why this doesn't work.
So I have 6 different nodes, in maya, called aiSwitch. I need to generate random different numbers from 0 to 6 and input that value in the aiSiwtch*.index.
In short the result should be
aiSwitch1.index = (random number from 0 to 5)
aiSwitch2.index = (another random number from 0 to 5 different than the one before)
And so on unil aiSwitch6.index
I tried the following:
import maya.cmds as mc
import random

allswtich = mc.ls('aiSwitch*')
    for i in allswitch:
    print i
    S = range(0,6)
    print S
    shuffle = random.sample(S, len(S))
    print shuffle
    for w in shuffle:
        print w
        mc.setAttr(i + '.index', w)

This is the result I get from the prints:
aiSwitch1 <-- from print i
[0,1,2,3,4,5] <--- from print S
[2,3,5,4,0,1] <--- from print Shuffle (random.sample results)
2
3
5
4
0
1  <--- from print w, every separated item in the random.sample list.

Now, this happens for every aiSwitch, cause it's in a loop of course. And the random numbers are always a different list cause it happens every time the loop runs.
So where is the problem then?
aiSwitch1.index = 1

And all the other aiSwitch*.index always take only the last item in the list but the time I get to do the setAttr. It seems to be that w is retaining the last value of the for loop. I don't quite understand how to

*

*Get a random value from 0 to 5

*Input that value in aiSwitch1.index

*Get another random value from 0 to 6 different to the one before

*Input that value in aiSwitch2.index

*Repeat until aiSwitch5.index.
I did get it to work with the following form:
 allSwitch = mc.ls('aiSwitch')
 for i in allSwitch:
     mc.setAttr(i + '.index', random.uniform(0,5))

This gave a random number from 0 to 5 to all aiSwitch*.index, but some of them repeat. I think this works cause the value is being generated every time the loop runs, hence setting the attribute with a random number. But the numbers repeat and I was trying to avoid that. I also tried a shuffle but failed to get any values from it.
My main mistake seems to be that I'm generating a list and sampling it, but I'm failing to assign every different item from that list to different aiSwitch*.index nodes. And I'm running out of ideas for this.
Any clues would be greatly appreciated.
Thanks.
Jonathan.

A: Here is a somewhat Pythonic way: shuffle the list of indices, then iterate over it using zip (which is useful for iterating over structures in parallel, which is what you need to do here):
import random

index = list(range(6))
random.shuffle(index)

allSwitch = mc.ls('aiSwitch*')
for i,j in zip(allSwitch,index):
    mc.setAttr(i + '.index', j)


text:
Q: Why is the c# EdgeDriver throwing an unknown error? This is my first question here so I apologize in advance if I haven't followed protocol in some fashion...
I'm getting the following exception when attempting to instantiate an instance of OpenQA.Selenium.Edge.EdgeDriver. I have separate .Net Core 2.2 and .Net Framework 4.7.2 applications and both get the same exception.
edgeDriver = new EdgeDriver();

This is the error message:
Message: OneTimeSetUp: OpenQA.Selenium.WebDriverException : Unexpected error. Unknown error

Stack Trace:
OpenQA.Selenium.WebDriverException : Unexpected error. Unknown error at
OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse) at
OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters) at
OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities desiredCapabilities) at
OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities) at OpenQA.Selenium.Edge.EdgeDriver..ctor(EdgeOptions options) at
OpenQA.Selenium.Edge.EdgeDriver..ctor() at
Selenium.EdgeTests.Setup()

Addtional information:

Windows 10 Pro v1903 (Developer Mode is on)
Edge v80.0.361.69(64-bit)
NUnit v3.12.0
NUnit3TestAdapter v3.16.1
Selenium Support v3.141.0
Selenium WebDriver v3.141.0
MicrosoftWebDriver.exe File & Product Version 10.0.17134.1

I have also tried adding Selenium.WebDriver.MicrosoftWebDriver v10.0.17134 and Selenium.WebDriver.MicrosoftDriver v17.17134.0, independently of each other, to no avail, same exception.

A: I'm posting this as an answer but the credit should go to @rfmodulator, as it was his suggestion.
I looked at https://learn.microsoft.com/en-us/microsoft-edge/webdriver-chromium and  I was able to utilize the example under the 'Selenium 4.00-alpha03 and earlier' section with a little tweaking to resolve the deprecated DesiredCapabilities.


text:
Q: Can I use a loop inside a react hook? Can i do this:
const [borderCountries, setBorderCountries] = useState([])
useEffect(() => {
    country.borders.forEach(c => {
        fetch(`https://restcountries.eu/rest/v2/alpha/${c}`)
            .then(res => res.json())
            .then(data => setBorderCountries([...borderCountries,data.name]))
    })
}, [])

Country borders is a prop passed to the component. If not what can I do?

A: You can, but not quite like that, for a couple of reasons:

*

*Each fetch operation will overwrite the results of the previous one, because you're using borderCountries directly rather than using the callback version of setBorderCountries.

*Since the operation depends on the value of a prop, you need to list that prop in the useEffect dependencies array.

The minimal change is to use the callback version:
.then(data => setBorderCountries(borderCountries => [...borderCountries,data.name]))
//                               ^^^^^^^^^^^^^^^^^^^

...and add country.borders to the useEffect dependency array.
That will update your component's state each time a fetch completes.
Alternatively, gather up all of the changes and apply them at once:
Promise.all(
    country.borders.map(c =>
        fetch(`https://restcountries.eu/rest/v2/alpha/${c}`)
            .then(res => res.json())
            .then(data => data.name)
    })
).then(names => {
    setBorderCountries(borderCountries => [...borderCountries, ...names]);
});

Either way, a couple of notes:

*

*Your code is falling prey to a footgun in the fetch API: It only rejects its promise on network failure, not HTTP errors. Check the ok flag on the response object before calling .json() on it to see whether there was an HTTP error. More about that in my blog post here.

*You should handle the possibility that the fetch fails (whether a network error or HTTP error). Nothing in your code is currently handling promise rejection. At a minimum, add a .catch that reports the error.

*Since country.borders is a property, you may want to cancel any previous fetch operations that are still in progress, at least if the border it's fetching isn't still in the list.
Putting #1 and #2 together but leaving #3 as an exercise for the reader (not least because how/whether you handle that varies markedly depending on your use case, though for the cancellation part you'd use AbortController), if you want to update each time you get a result
const [borderCountries, setBorderCountries] = useState([]);
useEffect(() => {
    country.borders.forEach(c => {
        fetch(`https://restcountries.eu/rest/v2/alpha/${c}`)
            .then(res => {
                if (!res.ok) {
                    throw new Error(`HTTP error ${res.status}`);
                }
                return res.json();
            })
            .then(data => setBorderCountries(borderCountries => [...borderCountries, data.name]))
            //                               ^^^^^^^^^^^^^^^^^^^
            .catch(error => {
                // ...handle and/or report the error...
            });
    });
}, [country.borders]);
//  ^^^^^^^^^^^^^^^

Or for one update:
const [borderCountries, setBorderCountries] = useState([]);
useEffect(() => {
    Promise.all(
        country.borders.map(c =>
            fetch(`https://restcountries.eu/rest/v2/alpha/${c}`)
                .then(res => res.json())
                .then(data => data.name)
        })
    )
    .then(names => {
        setBorderCountries(borderCountries => [...borderCountries, ...names]);
    })
    .catch(error => {
        // ...handle and/or report the error...
    });
}, [country.borders]);
//  ^^^^^^^^^^^^^^^

A: You can but it's Not a good practice.


text:
Q: AWK get attribute value from XML element Hello everyone I am trying to use AWK to extract the version= value from pkg-info from an XML file.
I would like to just do something like:
cat file_below.txt | awk some_commands

using the data below
<?xml version="1.0" encoding="utf-8"?>
<pkg-info overwrite-permissions="true" relocatable="false" identifier="com.application.something" version="1.2.3" format-version="2" generator-version="ABC" install-location="/Applications" auth="root">
</pkg-info>

The desired output would be:
1.2.3

Thank you in advance

A: A simple way is to use sed to locate the line beginning "<pkg-info..." and then isolating the version with a substitution capturing the version and reinserting as a backreference, e.g.
sed -E -n '/^<pkg-info/s/^.*[ ]version="([^"]+)".*$/\1/p' file

Where -E specifies extended regex and -n suppresses normal output of pattern space, and:

*

*/^<pkg-info/ locates the line beginning with "<pkg-info", then the normal

*s/find/replace/ substitution where find is:

*^.*[ ]version="([^"]+)".*$ ignores characters from the beginning of line to a space followed by version=", the capture group ([^"]+) captures one or more characters that follow that are not a '"' (i.e. the version number you want) and then ".*$ ignores from the closing '"' to end of line.

*the replace is \1 which simply inserts the first bacreference (the stuff captured in the first capture group above), and

*/p then prints the result.

Example Use/Output
With your example in file you would have:
$ sed -E -n '/^<pkg-info/s/^.*[ ]version="([^"]+)".*$/\1/p' file
1.2.3

A: With your shown samples, could you please try following. Written and tested in GNU awk. Also as per experts advise a xml parsing tool would be best to parse xml file since OP is already using awk to parse OP's file so going with it.
awk '
/^<pkg-info/ && match($0,/[[:space:]]+version="([0-9]+\.){2}[0-9]+"[[:space:]]+/){
  val=substr($0,RSTART,RLENGTH)
  gsub(/^ +| +$/,"",val)
  print val
}
' Input_file

Explanation: Adding detailed explanation for above.
awk '                             ##Starting awk program from here.
/^<pkg-info/ && match($0,/[[:space:]]+version="([0-9]+\.){2}[0-9]+"[[:space:]]+/){
                                  ##Checking condition if line starts from <pkg-info AND matches mentioned regex.
  val=substr($0,RSTART,RLENGTH)   ##Creating val which is sub string of matched regex.
  gsub(/^ +| +$/,"",val)          ##Substituting starting and ending spaces with NULL in val.
  print val                       ##Printing val value here.
}
' Input_file                      ##Mentioning Input_file name here.

A: assuming no newlines within tag
gawk/mawk/mawk2 'BEGIN { FS = "version=\"" } /^[<]pkg-info/ {

    print substr($2, 1, index($2, "\"") -1 ); exit; }'

version to handle random \n
gawk/mawk/mawk2 'BEGIN { FS="version=\"" } (NF > 1) {

    if (seen++) { print substr($2,1,index($2, "\"")-1); exit; } }'

This will skip the first time it sees version, at the initial xml tag. second time it prints the version number then exits. this code does not need to make assumptions regarding how version numbers are formatted, other than being double quoted.
version to account for pkg-info being all over the place :
gawk/mawk/mawk2 'BEGIN { RS = "^$"; FS = "([<]pkg-info|[\/]pkg-info[>])";

   } match($2, /version=[^ ]+/) {

       print substr($2, RSTART + 9, RLENGTH - 10); exit; }'

Just have it read in the whole XML file, not attempting to split things along NL.  Then when you enforce FS exactly being the opening and close tags of it, then $2 must be the first occurrence of such a tag.

A: What you have there is an XML Element with an attribute=value combination you wish to get.
While you could have a simple awk or sed that will retrieve 1.2.3 from the one-line example you have, you really should use an XML parser. It will likely not work in the future if you don't.
While you have given the attributes all-on-one-line example of:
<?xml version="1.0" encoding="utf-8"?>
<pkg-info overwrite-permissions="true" relocatable="false" identifier="com.application.something" version="1.2.3" format-version="2" generator-version="ABC" install-location="/Applications" auth="root">
</pkg-info>

The same data could just as easily be:
<?xml version="1.0" encoding="utf-8"?>
<pkg-info overwrite-permissions="true"
          relocatable="false" identifier="com.application.something"
          version="1.2.3" format-version="2"
          generator-version="ABC" install-location="/Applications" auth="root">
</pkg-info>

Or,
<?xml version="1.0" encoding="utf-8"?><pkg-info overwrite-permissions="true" relocatable="false" identifier="com.application.something" version="1.2.3" format-version="2" generator-version="ABC" install-location="/Applications"  auth="root"/>

and still be parsed as the same data. All three examples are valid XML but none of the awk or sed answers here handle any but the first example.
For XML, a '\n', ' ', '\t' and '\r' are all the same1  but to awk and sed those characters have very different meaning. To try and coerce a line oriented tool like awk or sed to deal with tag oriented data like XML is extremely fragile.
The best way to deal with this is to use an XPath query. The relevant query would be:
/pkg-info/@version

DEMO
Given file that has some valid form of XML as above, you can use one of these methods.
Here is a simple example in Ruby. Use nokogiri xml parser to parse with an xpath to the attribute of interest:
ruby -r nokogiri -e 'doc=Nokogiri::XML($<.read)
puts doc.xpath("/pkg-info").attribute("version").value' file
1.2.3

(You may need to install nokogiri with gem install nokogiri on your system...)
Or with XMLStarlet:
xml sel -t -v '/pkg-info/@version' file
1.2.3

If you have XML::XPath module installed with your Perl, (and most systems do) you also have a command line XPath query tool called xpath. You can do:
xpath -q -e '/pkg-info/@version' file
 version="1.2.3"

Then run that through sed to just get the value:
xpath -q -e '/pkg-info/@version' file | sed -E 's/[^"]*"([^"]*).*/\1/'
1.2.3

Note that an XML parser will work with the any legit version of your XML data. The other sed or awk solutions here will not.

And if your wreally wreally wreally want to use a regex, Perl is a better bet. This works with all three examples above:
perl -0777 -lnE 'say $1 if /(?:\s|>)<pkg-info[\s\S]*?\sversion="([^"]+)"/m' file

If you hafta hafta hafta have an awk you can set RS-"^$" which has the effect of reading the entire file in as one string then:

*

*Find the point with "<pkg-info ".

*Since these are attributes and not nested tags, there will be no > in the attribute section. But, no matter how the <pkg-info element is terminated, there must be a > to terminate it.

*Now sub everything on either side of the ' version=" value with ""

*Print and profit.

This awk works with all my examples; HOWEVER, you really should use an XML parser.
awk -v RS="^$" '{ x=index($0, "<pkg-info ")
                  s=substr($0,x)
                  sub(/[^>]*\sversion="/,"", s)
                  sub(/".*/,"", s)
                  print s
                }' file

1 So long as those characters are insignificant whitespace, which they are in this example...

A: Awk and XML are not the best of friends because awk is a regular expression driven line-based tool. XML is not a simple format that can be easily filtered with line based tools; so also, it is difficult to create a regular expression that can reliably match to all the ways XML can be presented.
To make sure we don't make a mistake, we leversge a state machine (a filter) that understands XML to transform it to something line-based that we can work with reliably. One such tool is xml2 which provides a parseable "flat" output from XML.  Here is an example of the filtered result of your sample....
$ xml2 < some.xml
/pkg-info/@overwrite-permissions=true
/pkg-info/@relocatable=false
/pkg-info/@identifier=com.application.something
/pkg-info/@version=1.2.3
/pkg-info/@format-version=2
/pkg-info/@generator-version=ABC
/pkg-info/@install-location=/Applications
/pkg-info/@auth=root

After filtering the XML, it is trivial to create a reliable awk or sed filter to grab our output...  Here are a couple ideas:
$ xml2 < some.xml | awk -F= '$1 == "/pkg-info/@version" { print $2 }'
1.2.3
$ xml2 < some.xml | sed -e 's,^/pkg-info/@version=,,; t; d'
1.2.3


text:
Q: Asp.net MVC - How to upload files without pressing send button? Automatically uploaded once selected the files
How can i make the upload file action automatically once the files selected. means that the action will go to index action without pressing any button? Thanks in advance..

View

<form action="@Url.Action("Index", "Home")" method="post" enctype="multipart/form-data">
    @Html.AntiForgeryToken()

                Name:
                <input type="text" name="faxnumber" />

                Select File:
                <input type="file" name="files" id="file" multiple="multiple" />

                <input type="submit" name="submit" value="Send" id="btnSubmit" />

        @ViewBag.Message

</form>

javascript

Controller

public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
{
  //some code here
}

UPDATE
After selected files, the files will auto uploaded and the details will be stored in object name Document then back to the view with fail or success message. Then when I hit Send button all details will pass to the Send action in controller. How can I manage this process? The upload part is done already..but now I'm stuck in how can I send all the details to the next action in controller.
 public class Document
  {
    public string Name { get; set; }
    public byte[] Binary { get; set; }
    public string Path { get; set; }
  }

SendController

public ActionResult Send(Document doc)
    {
      //some code here
    }

A: Your code will work fine if you change your submit button name value to anything other than "submit".
 <input type="submit" name="notsubmit" value="Send" id="btnSubmit" />

This is an interesting behavior ! I really do not know why it does not submit when the name attribute value is "submit". I will update the answer when i get any more info.


text:
Q: Caxis auto equivalent in OpenCV Python or Pillow? MATLAB has the function caxis auto which comes in handy for viewing images if they have a low contrast and are looking almost black.
In Matlab it works like this:
figure;imshow(I);caxis auto

I know  how to adjust the contrast in OpenCV Python, like:
 img = cv2.imread('someimage.jpg',0)
 equ = cv2.equalizeHist(img)

 #Showing image
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

However, this does is not the same implementation as caxis auto which changes the illuminuation adaptively.

A: OpenCV does not use colormaps for displaying single channel images. In Matlab, caxis sets the colormap limits. In other words, if your image has values between 0.5 and 1.0, you can set the displayed color limits so that 0.5 is rendered as if it were 0.0, and scale that way. OpenCV just displays the image values as they are.
What that means is that if you want a different scaling for the values, you can just change them in the array that gets displayed.
With OpenCV, you can easily accomplish this scaling with cv2.normalize() with the normType=cv2.NORM_MINMAX.
img = np.random.rand(500, 500, 3)*0.2
cv2.imshow('Low contrast image', img)
cv2.waitKey()

img_scaled = cv2.normalize(img, None, alpha=0.0, beta=1.0, norm_type=cv2.NORM_MINMAX)
cv2.imshow('Scaled colors for display', img_scaled)
cv2.waitKey()

Note that this works for both grayscale and color images.

However, if you just have a grayscale image, another option is to display them with Matplotlib. MPL will automatically scale single channel images to the min/max display values.
from matplotlib import pyplot as plt

img = np.random.rand(500, 500)*0.2
plt.imshow(img, cmap='gray')
plt.show()

Note here I included the cmap='gray' argument because the default colormap for a single channel image is Viridis, and not grayscale. You can read more about Matplotlib colormaps here. Generally, if you're looking for similar syntax to Matlab, Matplotlib has you covered---it was initially geared towards people coming to Python from Matlab, so it has similar functionality and syntax.

One last option is to just scale manually in numpy. If your image is an unsigned int type, you can do this simply by shifting the image to have it's lowest value as 0, and then multiply so that it's max value is the maximum of your datatype. Note that when you multiply your image will be converted to a float, so you'll need to recast it. For e.g., if you have a uint16 image, the values range from 0 to 65535, so you could do:
img_scaled = img.copy() - np.min(img)
img_scaled = np.uint16(img_scaled*(65535/np.max(img)))

Or, if you'd like to do this automatically, you can grab the datatype information from the image (including the min and max values possible in a datatype) with np.iinfo() to automatically scale and convert as necessary. Here's a function that will normalize any (signed or unsigned) integer or floating point image:
def normalize_minmax(img):
    """Scales an image into an interval [min, max] with the same datatype.

    If img.dtype is a float type, img is scaled into [0.0, 1.0].
    If img.dtype is an integer type, img is scaled into [dtype.min, dtype.max].
    If img.dtype is some other type, the original image is returned.
    """
    dtype = img.dtype
    if np.issubdtype(dtype, np.integer): # scale to [dtype.min, dtype.max]
        dtype_info = np.iinfo(img.dtype)
        img_scaled = img - np.min(img)
        scale = (dtype_info.max - dtype_info.min) / np.max(img_scaled)
        img_scaled = img_scaled * scale + dtype_info.min
        return np.round(img_scaled).astype(dtype)
    elif np.issubdtype(dtype, np.float):  # scale to [0, 1]
        img_scaled = img - np.min(img)
        img_scaled = img_scaled / np.max(img_scaled)
        return img_scaled.astype(dtype)
    return img

How it works is easy to describe. For the float image case, you simply shift it so that the lowest value is zero, and then divide by the max to get it between 0 and 1. Then just simply cast it back to the original type. For the integer datatypes, it takes a little more effort if you care to include signed integers. In this case the range extends to negative numbers as well. You start off the same by shifting the lowest value to zero. But then you need to scale so that the values span the entire range of the datatype (e.g. (datatype_max - datatype_min) / max(img)). So now your values will span from [0, datatype_max - datatype_min], so you need to add back the datatype_min to get to [datatype_min, datatype_max]. I also rounded the values instead of truncating before converting back to the original datatype.


text:
Q: Overthinking it: document class report vs book for a thesis I apologize in advance for the long wall of text; there is probably some way to condense this question to half the size without losing anything important, but I'm not sure which half to remove.
I recently finished writing my thesis, and this involved some last minute freaking out about the formatting of the front matter, since I kept putting off until "later".  (I've seen a few horror stories on this website where some universities take a ruler to your thesis to make sure that your margins are within spec or something.  The person at my school is fairly reasonable about such things.  I remember showing him my attempt at the signature page and he said "perfect" despite the fact that it looked noticably different than the page from the guidelines.  So it seems that I was freaking out for no good reason.  This did not stop me from doing so for several more weeks.  In some sense, the fact that I'm posting this question here shows that I haven't really stopped.)  I could have used a template that my advisor had lying around, but it had various misfeatures that would have driven me crazy; what they were is probably irrelevant here.  The point is, I know someone who did use, and was bitten by some of those misfeatures and needed my assistence to recover.  Which makes me think I'm not the only one who would like something better.  (In particular, simpler.)  So, I resolved to write my own template in the hopes that someone else would find it useful someday.
I want to base it one of the standard classes (as opposed to something fancy like memoir or something in the KOMA bundle), and the only ones that support chapters are report and book.  The question becomes: which one?  When I first began working on my draft, I was using the report class since it had a built in abstract environment (abstract is required), but eventually I switched to book since the built in abstract environment was not doing what I want and thus had to hand format it.  Now that I'm making a new template, I'm revisiting this decision.  The trouble is that these two classes are so similar that it's hard to choose between them on any basis at all.  Nevertheless, I compiled a list of differences between the two that seems relevant to this decision.  Note: I'm ignoring differences that are only apparent in compatibility mode: ie \documentstyle instead of \documentclass.  (For instance, book and report don't have the same text width in compatibility mode, but with LaTeX2e, they do.)
One argument in favor of book is that I've actually used it successfully myself, so I can say that it's proven to work.  This argument seems pretty weak, since the classes are very similar and in any case I intend to test this on my thesis to make sure everything is still fine.
I've also done a bit of online research, and most How To Thesis Guides seem to favor report instead of book, although not all.  But most of them give little to no justification for this choice.
In any case: the differences, with pros/cons:
The book class has support for the distinction between main matter and front matter, which the rules require.  On the other hand, this seems like the kind of thing that can be 90% faked by \pagenumbering.
The book class is two-sided by default, the report class is one-sided.  The rules require a single-sided thesis.  On one hand, defaults are easily changed, but maybe I should take a hint that the class with defaults closer to what I need is the right one to use?
At 12pt base size using one-sided layout (I haven't checked the other size too carefully) there are some (very) minor differences in layout: \headsep is a few points smaller with book than report.  (25pt vs 0.275in, or roughly 19.87pt.)  Similarly, \marginparsep is a bit smaller in book (7pt vs 10pt), and \marginparwidth is thus 3pt wider in book (47pt vs 44pt).  In practice, these are both much too small to make \marginpar useful, at least in my opinion (an inch or two is enough).  The two important parameters are \textwidth and \textheight, and these are identical.
The report class has a built-in abstract environment.  It's sufficiently different than what is neeeded that I have no temptation to reuse pieces of it.  I can't decide if this is a point for or against using report.  On the one hand, what's the sense of pulling in definitions I don't need.  On the other, this seems to suggest that reports are the kind of thing that contain abstracts, while books are not, so in some vague sense report is the more sementically correct choice.
Slightly different titlepage environment.  (book has an extra \cleardoublepage)  This environment does crazy things to page numbers and I intend to avoid it.  I have no idea who thought these page number games were a good idea.  (Leslie Lamport probably?)
Different defaults for the page style: report uses plain, while book uses headings.  Doesn't matter, both are not right.  It turns out that myheadings, with no customizations does the right thing here.  (Really, no setting marks or anything!)
Any thoughts?  I can't help feeling like these two classes should be (or should have been; too late now I guess) merged into one; they are too similar.


text:
Q: Visual Studio 2015 replace ; to , in properties This has been bugging me ever since! I just did a fresh install because I reformatted my laptop and just noticed this.
Can anyone help me change it back to ,?

A: Big thanks to Hans Passant for helping me...
Basically it chooses based on your main language in the control panel settings and to what your country is defaulted to. After changing, just restart visual studio and it should change!


text:
Q: Adding a counter for various div container first of all I know that this title is kinda confusing but I am going to explain what I want to do.
I created a simple .html and .js file which has different div tags. I looped the div tags with a for loop and the text of the div container should be added to a table that I created.

        one

        two

        three

        four

        five

        six

JavaScript file:
var divLists = document.getElementsByClassName('div');

window.onload = function() {
  for (i = 0; i < divLists.length; i++) {

    var divList = divLists[i];

    divList.onclick = function() {
      x(this.innerHTML);
    }
  }
};

function x(y) {
  var table = document.getElementById('table');
  var Row = table.insertRow();
  var Cell = Row.insertCell(0);
  var newText = document.createTextNode(y);
  Cell.appendChild(newText);
}

I also put the code in jsfiddle: https://jsfiddle.net/avj4zg21/11/
So by clicking on "one", "two", "three",... it will be added to the table but it want to add a counter. So for example if I click on one it should be added to the table and if I click a second or third time on it there should be a counter behind the one like: "one (3 times pressed)".
Thank you in advance

A: You can use a Map to keep track of the clicked items and increment the existing ones:

var divLists = document.getElementsByClassName('div');

window.onload = function() {
  for (i = 0; i < divLists.length; i++) {

    var divList = divLists[i];

    divList.onclick = function() {
      x(this.innerHTML);
    }
  }
};

let map = {};

function checkNumber(number){
     if(map[number])
          map[number] = map[number] + 1;
     else
          map[number] = 1;
     return map[number];
}

function x(y) {
  var table = document.getElementById('table');
  let rows = table.rows;
  let count = checkNumber(y);
  var Row = table.insertRow();
  var Cell = Row.insertCell(0);
  Cell.innerHTML = count;
  Cell = Row.insertCell(0);
  Cell.innerHTML = y;
}

        one

        two

        three

        four

        five

        six

A: Generates an incremented id (as a class) for each row.  Adds counter as data attribute using dataset.  If you need to have multiple divs with the same content increment the same counter, you will have to use a map, attach data, or scan contents.
Note: your current scheme takes the entire HTML contents of the divs which is actually "           one" rather than a simple word string.

var divLists = document.getElementsByClassName('div');

window.onload = function() {
  for (i = 0; i < divLists.length; i++) {

    var divList = divLists[i];

    let idx = i; // store current index, so it can be used below
    divList.onclick = function() {
      x(this.innerHTML, idx);
    }
  }
};

function x(y, idx) {
  var table = document.getElementById('table');
  var Row = table.getElementsByClassName(`id${idx}`)[0] || table.insertRow();
  Row.classList.add(`id${idx}`); // generate `id${idx}` as a class
  var Cell = Row.cells[0] || Row.insertCell(0);
  Cell.innerHTML = y + (Row.dataset.count ? `(${Row.dataset.count})`: '');
  Row.dataset.count = (+Row.dataset.count + 1)||2;
  // convert count to number increment, or if not defined yet start at 2
}

        one

        two

        three

        four

        five

        six


text:
Q: Jquery check if one array contains same value I have an simple javascript array that may contain duplicates or maynot contain duplicates.
var names = [
['aaa','pin/test1.html'],
['bbb','pin/test2.html'],
['ttt','test.html'],
['ggg','test.html'],
['yyy','un/777.html'],
['ggg','test3.html'],
['nnn','test3.html'],
['eee','n/777.html'],
['sss','pin/test1.html'],
['xxx','pin/test2.html'],
['ppp','pin/test1.html'],
];

I need to find the duplicate filepath and put their name into new array. If there is no duplicate then assign its name in first and then assign '' after two values. I could point all the codes that I have tried but it doesnt work. I accept jquery solution also. The expected outcome is this.
var outcome = [
[['aaa','sss','ppp'], 'pin/test1.html'],
[['bbb','eee','xxx'], 'pin/test2.html'],
[['ttt','ggg',''], 'test.html'],
[['yyy','',''], 'un/777.html'],
[['ggg','nnn',''], 'test3.html'],
];

What I have tried is this
for (var i = 0; i < arr.length; i++) {
    var uniqueNames = [];
    $.each(arr[i], function (i, el) {
        if ($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
    });
    console.log(uniqueNames);
}

A: You could take a hash table and an array of empty strings and find the next slot for the value.
The array is reduced by taking an object as accumulator and a destructure array as value (the first part of the array) and key (the second part, aka filepath).
Inside of Array#reduce, a property check with the key is made and if undefined, an array with the wanted structure (array with two items, the first is an array with three emty spaces and the key) is being assigned by using a logical nullish assignment ??=.
The next line assigns the value to the next free slot, an item with an empty string.
Finally the accumulator is returned.
To get only an array as result, a conversion of the values of the object takes place.

let names = [['aaa','pin/test1.html'], ['bbb','pin/test2.html'], ['ttt','test.html'], ['ggg','test.html'], ['yyy','un/777.html'], ['ggg','test3.html'], ['nnn','test3.html'], ['eee','n/777.html'], ['sss','pin/test1.html'], ['xxx','pin/test2.html'], ['ppp','pin/test1.html']],
    grouped = Object.values(names.reduce((r, [v, k]) => {
        r[k] ??= [Array(3).fill(''), k];
        r[k][0][r[k][0].indexOf('')] = v;
        return r;
    }, {}));

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

A:

   const aux = (names) => {
    const hash = {};
    let max = 0;
    names.forEach(ele => {
      if (!hash[ele[1]]) hash[ele[1]] = [];
      hash[ele[1]].push(ele[0]);
      max = Math.max(hash[ele[1]].length, max);
    });

    return Object.keys(hash).map(ele => [[...hash[ele], ...Array(max -hash[ele].length).fill("")], ele]);

   }

    var names = [
    ['aaa','pin/test1.html'],
    ['bbb','pin/test2.html'],
    ['ttt','test.html'],
    ['ggg','test.html'],
    ['yyy','un/777.html'],
    ['ggg','test3.html'],
    ['nnn','test3.html'],
    ['eee','n/777.html'],
    ['sss','pin/test1.html'],
    ['xxx','pin/test2.html'],
    ['ppp','pin/test1.html'],
     ];
    console.log(aux(names))

This might help

A: You do not need jQuery for dealing with regular JS structure, you can achieve what you want with a simple code like this:

var names = [['aaa','pin/test1.html'],['bbb','pin/test2.html'],['ttt','test.html'],['ggg','test.html'],['yyy','un/777.html'],['ggg','test3.html'],['nnn','test3.html'],['eee','n/777.html'],['sss','pin/test1.html'],['xxx','pin/test2.html'],['ppp','pin/test1.html'],];

let lengthToFill = 0;
// collecting all the duplicates into a map
const pathMap = {};
names.forEach(name => {
    // just in case if you're not familiar with array destructuring
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
    const [pathName, path] = name;

    // make sure we have an array to deal with
    // just in case you're not familiar with Nullish coalescing operator (??)
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
    pathMap[path] = pathMap[path] ?? [];
    pathMap[path].push(pathName);

    // tracking the max number of elements we're adding into a single entry
    lengthToFill = Math.max(lengthToFill, pathMap[path].length);
});

const result = Object.entries(pathMap).map(entry => {
    // constructing new array entry based on the data we've collected so far
    return [
        entry[1].concat(Array(lengthToFill - entry[1].length).fill('')),
        entry[0],
    ];
});

console.log(result);

This solution will work for any number of elements that you'd like to fill the array with ''. It makes sure that the length of final listing is the same for all entries.


text:
Q: A question about Chapter 12 (Vapnik-Chervonenkis Theory) of 'A Probabilistic Theory of Pattern Recognition' Hi,
Can anyone familiar with the book 'A Probabilistic Theory of Pattern
Recognition' or the theory described help me out?
See quote from chapter 12, 'Vapnik-Chervonenkis Theory', of 'A
Probabilistic Theory of Pattern Recognition' below. I'm not following
the geometric setup outlined there.
Some specific questions:
The hyperrectangle referred to is as in
http://en.wikipedia.org/wiki/Hyperrectangle, right?
Does $\phi \in C$ correspond to hyperrectangles of arbitrary dimension?
When the text says "assign the smallest hyperrectangle containing
these points", I assume it means both in the sense of smallest
dimension as well as size. I'm not sure whether this means the
$\phi_i$ are of fixed dimension. I think so.
However, my main source of perplexity is the sentence beginning
"Clearly, for each $\phi$..." and ending "on the boundary of the
hyperrectangle". I've no idea why this would be true.
There is a similar setup earlier in the book, Section 4.5, but this
talks about hyperplanes, and is easier to follow.
No doubt I'm misreading or something. Clarifications
appreciated.
                                                  Regards, Faheem.

(Some background to the extract that follows.)
In what follows, d is just a fixed integer. I guess it represents the dimension.
Suppose you have a classifier
$$ \phi: \mathbb{R}^d \longrightarrow \{0, 1\}$$
and $n$ ordered pairs $(X_i, Y_i)$, where $X_i \in \mathbb{R}^d$ are the data values,
and $Y_i\in \{0,1\}$ are the correct classifications of the $X_i$.
Then the empirical error (or risk) of $\phi$ is
$$   \hat{L}_n(\phi) = \frac{1}{n} \sum_{i=1}^n I_{\{\phi(X_i)\neq Y_i\}}    $$
that is, the number of errors made by the classifier is counted and normalized.
From pg 191 of 'A Probabilistic Theory of Pattern Recognition' by
Devroye et al, chapter 12, 'Vapnik-Chervonenkis Theory'.
Let $C$ be the class of classifiers assigning 1 to those $x$ contained
in a closed hyperrectangle and 0 to all other points, Then a
classifier minimizing the empirical error $\hat{L}_n(\phi)$ over all
$\phi \in C$ may be obtained by the following algorithm: to each
2d-tuple $(X_{i_1}, X_{i_{2d}})$ of points from $X_1,\dots, X_n$,
assign the smallest hyperrectangle containing these points. If we
assume that $X$ has a density, then the points $X_1,\dots, X_n$ are in
general position with probability one. This way we obtain at most ${n
  \choose 2d}$ sets. Let $\phi_i$ correspond to the $i$-th such
hyperrectangle, that is, the one assigning 1 to those $x$ contained in
the hyperrectangle, and 0 to other points. Clearly, for each $\phi \in
C$, there exists a $\phi_i$, i = 1, ${n \choose 2d}$, such that
$$\phi(X_j) = \phi_i(X_j)$$
for all $X_k$, except possibly for those on the boundary of the
hyperrectangle. Since the points are in general position, there are at
most $2d$ such points. Therefore, if we select a classifier
$\hat{\phi}$ among $\phi_1, \phi_{{n \choose 2d}}$ to minimize the
empirical error, then it approximately minimized the empirical error
over the whole class $C$ as well.

A: Yes, a hyperrectangle is a generalisation of rectangle to higher dimensions. Here the data is given by points in $\mathbb{R}^d$, so the hyperrectangles are all of that dimension. As with all such algorithms you need to find a way to get a handle on the set of classifiers, so rather than the infinite class of all hyperrectangles of dimension $d$, the choice will be from the $n \choose 2 d$ hyperrectangles of dimension $d$, each of which is the smallest for some choice of $2 d$ of the data points.
For example, if the data consisted of 1000 points in $\mathbb{R}^2$, rather then the infinite class of all rectangles, we confine ourselves to the $1000 \choose 4$ rectangles which minimally contain a subset of 4 of the data points.
One task then is to show that the best of this finite set is almost as good as the best of all the hyperrectangles -- good in the sense that were the data points each labelled $+$ or $-$, the $+$s would be best separated from the $-$s. The argument claims that for each hyperrectangle there will be one from the finite set agreeing with it except for a small number of points on the boundary equal to the number of faces of the hyperrectangles. In the example above, it says that for any rectangle, there is one in the set of $1000 \choose 4$ which encloses exactly the same points, except possibly for 4 on the boundary. Not completely obvious, I agree.
Edit: If hyperrectangles are restricted to have lines parallel to the axes, then it is obvious. Judging from problem 11.6 on page 183, this may well be the case.


text:
Q: Suggestions for faster deserialization using Protocol Buffers I am using Protocol Buffers in order to serialize/deserialize the data. I have defined the Protocol Buffers message file as follows:
syntax = "proto3";
package Tutorial;
import "google/protobuf/timestamp.proto";

message PointCloud {
  int32 width  = 1;
  int32 height = 2;

  message Point {
    float x     = 1;
    float y     = 2;
    float z     = 3;
    fixed32 rgb = 4;
  }
  repeated Point points = 3;
  google.protobuf.Timestamp timestamp = 4;
}

I am able to receive the serialized data. I am using ParseFromArray API as follows:
zmq::message_t msg;
int rc = zmq_socket.recv(&msg);
if (rc){
    std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
    Tutorial::PointCloud point_cloud;
    point_cloud.ParseFromArray(msg.data(), msg.size());
    std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
    std::cout << "Time (ms): " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()/1000.0 << std::endl
}

The above works but it takes enough time to deserialize the data. On an average it takes around 96 ms in Ubuntu 14.04 LTS 64 Bit OS. Just for information, I also printed msg.size() and found it 3773550 approximately.
I am looking for suggestions to deserialize the data much faster than this.

A: Short answer, there might be no way.
Protobuf is slow to deserialize since it need to construct objects on the fly from a series of key-value pairs. If performance is your concern, try flatbuffer or Capn'Proto. These are alternatives which does not need any object construction but (possibly) cost more on disk, and had other shortcomings.


text:
Q: how to resolve MySQL Left WHERE condition error? The following statement gives the results without any error,
select
title as 'unreviewed series',
rating from series
left join reviews
    on series.id= reviews.series_id
where rating is null;

However, the following gives an error:
select title as 'unreviewed series',
ifnull(avg(rating), null) as 'Average Rating'
from series
left join reviews
    on series.id= reviews.series_id
where avg(rating) = null;

The error given by mysql is to use right syntax near WHERE.

A: use having and group by - where will not work as you are trying to filter with aggregated function
select title as 'unreviewed series',
ifnull(avg(rating), null) as 'Average Rating'
from series
left join reviews
    on series.id= reviews.series_id
group by title
having avg(rating) is null

A: When you use aggregate function (like avg),you must use group by on other columns,
And when you use group by ,you must use having for set where clause on aggregated column
 Like this:
    select title as 'unreviewed series',
ifnull(avg(rating), null) as 'Average Rating'
from series
left join reviews on series.id= reviews.series_id
group by title
having avg(rating) is null