text:
Q: How to pass raw mp3 from recyclerview item to another activity In my Android app I have a recyclerview which contains a list of items. In recyclerview activity each item has one textview and another activity has two textview and one audio play button. But audio not playing. How can I set setOnClickListener and play audio mp3 usung MediaPlayer. Here is my code-
NameModel.java

public class NameModel {

    private String name,meaning;
    private int audio;

    public NameModel(String name, String meaning, int audio) {

        this.name= name;
        this.meaning= meaning;
        this.audio= audio;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name= name;
    }

    public String getMeaning() {
        return meaning;
    }

    public void setMeaning(String meaning) {
        this.meaning= meaning;
    }

    public int getAudio() {
        return audio;
    }

    public void setAudio(int audio) {
        this.audio = audio;
    }
}

NameAdapter.java

itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int position=getAdapterPosition();
                    NameModel nameModel=nameItemList.get(position);

                    Intent intent=new Intent(context, NameDetailsActivity.class);
                    intent.putExtra("NAME",nameModel.getName());
                    intent.putExtra("MEANING",nameModel.getMeaning());
                    intent.putExtra("AUDIO", nameModel.getAudio());
                    context.startActivity(intent);
                }
            });

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private LinearLayoutManager linearLayoutManager;
    private List<NameModel> nameModelList;
    private NameAdapter nameAdapter;

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

        RecyclerView recyclerView  = (RecyclerView) findViewById(R.id.recyclerViewId);
        nameModelList = new ArrayList<>();
        nameAdapter = new NameAdapter(this,nameModelList);

        linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setAdapter(nameAdapter);
        recyclerView.setLayoutManager(linearLayoutManager);

        RecyclerView.ItemDecoration itemDecoration=new DividerItemDecoration(getApplicationContext(),DividerItemDecoration.VERTICAL);
        recyclerView.addItemDecoration(itemDecoration);

        nameModelList.add(new NameModel("Mahmud", "The praised one", R.raw.mahmud));
        nameModelList.add(new NameModel("Maaz", "Brave Man", R.raw.maaz));
    }
}

NameDetailsActivity.java

public class NameDetailsActivity extends AppCompatActivity {

    Context context;
    NameModel nameModel;

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

        String name = getIntent().getStringExtra("NAME");
        String meaning = getIntent().getStringExtra("MEANING");
        int audio = getIntent().getIntExtra("AUDIO",0);

        TextView nameText = (TextView) findViewById(R.id.tvName);
        TextView meaningText = (TextView) findViewById(R.id.tvMeaning);
        Button playbutton = (Button) findViewById(R.id.playBtn);

        nameText.setText(name);
        meaningText.setText(meaning);

        playbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaPlayer mediaPlayer = MediaPlayer.create(context,audio);
                mediaPlayer.start();
            }

        });
    }
}

any help would be appreciated. Thanks!

A: First of all you're doing getIntent().getStringExtra("AUDIO"); which is not right in this case.
You set int value in your intent.putExtra("AUDIO", nameModel.getAudio()); so you have to get int value back using int audio = getIntent().getIntExtra("AUDIO");. Hope it will help you.
Also I've noticed 1 thing. In your NameDetailsActivity where do you initialize your context and your NameModel class? Actually I don't know why you need NameModel class in NameDetailsActivity, but anyway... If you will pass that context to mediaplayer without initialization, you will get nullPointerException. And you get exception like Caused by java.lang.NullPointerException Attempt to invoke virtual method 'int com.tahmid.name.models.NameModel.getAudioFile()'. That's because your NameModel class in NameDetailsActivity is null.
You have to do 2 things.
If you need NameModel class in NameDetailsActivity, you have to create an empty constructor in NameModel class. You can find it in my answer below. And you have to initialize context and nameModel in NameDetailsActivity.
So try this code.
First of all in your NameModel create an empty constructor.
public class NameModel {

private String name,meaning;
private int audio;

public NameModel() {}

public NameModel(String name, String meaning, int audio) {

    this.name= name;
    this.meaning= meaning;
    this.audio= audio;
}

// The same code...

And your NameDetailsActivity you can do this.
public class NameDetailsActivity extends AppCompatActivity {

Context context;
NameModel nameModel;

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

    context = getContext();
    nameModel = new NameModel();

    String name = getIntent().getStringExtra("NAME");
    String meaning = getIntent().getStringExtra("MEANING");
    int audio = getIntent().getIntExtra("AUDIO",0);

    TextView nameText = (TextView) findViewById(R.id.tvName);
    TextView meaningText = (TextView) findViewById(R.id.tvMeaning);
    Button playbutton = (Button) findViewById(R.id.playBtn);

    nameText.setText(name);
    meaningText.setText(meaning);

    playbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MediaPlayer mediaPlayer = MediaPlayer.create(context,audio);
            mediaPlayer.start();
        }

    });
}
}


text:
Q: Unable to parse JSON, Showing error message "JSONObject["other"] not found" Below is the code snippet for the utility which I've used to fetch data.
Below are sample JSON in which I have to fetch the value of Other/Vehicle/Properties, but I'm getting an error message.
Please suggest what things I need to add to the utility?
I need to get the value of Other/Vehicle/Properties.
Please suggest what things I need to change in the Utility so that nested property also fetched from JSON.
public class TestUtil {

    public static JSONObject responsejson;

    public static String getValueByJPath(JSONObject responsejson, String jpath){
        Object obj = responsejson;
        for(String s : jpath.split("/"))
            if(!s.isEmpty())
                if(!(s.contains("[") || s.contains("]")))
                    obj = ((JSONObject) obj).get(s);
                else if(s.contains("[") || s.contains("]"))
                    obj = ((JSONArray) ((JSONObject) obj).get(s.split("\\[")[0])).get(Integer.parseInt(s.split("\\[")[1].replace("]", "")));
        return obj.toString();
    }
}

JSON Format:
    {
                "coverageEndDate": "02/28/2019",
                "coverageStartDate": "03/01/2018",
                "coverageType": "Personal",
                "error": {
                    "code": 0,
                    "message": ""
                },
                "firstName": "Ronnie",
                "insuredItems": {
                    "other": [{
                        "coverageEndDate": "02/28/2019",
                        "coverageStartDate": "03/01/2018",
                        "description": "Hunter Marin Passage 450",
                        "id": 14
                    }],
                    "properties": [{
                        "address": "31 LAKEWOOD RD, WEST BEND, WI 53090",
                        "coverageEndDate": "02/28/2019",
                        "coverageStartDate": "03/01/2018",
                        "deductible": 5000,
                        "description": "31 LAKEWOOD RD, WEST BEND, WI 53090",
                        "id": "113",
                        "limit": 2000000
                    }],
                    "vehicles": [{
                        "coverageEndDate": "02/28/2019",
                        "coverageStartDate": "03/01/2018",
                        "deductible": "$500 Comprehensive\n$500 Collision",
                        "description": "2016 Ford Explorer",
                        "id": "126",
                        "limit": "$100,000",
                        "make": "FORD",
                        "model": "EXPLORER",
                        "transportationExpense": "$30 per day and $900 max",
                        "vin": "1G1FA1E38F2131121",
                        "year": 2016
                    }, {
                        "coverageEndDate": "02/28/2019",
                        "coverageStartDate": "06/18/2018",
                        "deductible": "$500 Comprehensive\n$500 Collision",
                        "description": "2017 Dodg Durango",
                        "id": "127",
                        "limit": "$100,000",
                        "make": "DODG",
                        "model": "DURANGO",
                        "transportationExpense": "$30 per day and $900 max",
                        "vin": "2G1XER366DE4DE3H5",
                        "year": 2007
                    }]
                },
                "lastName": "James Dio",enter code here
                "policyNumber": "5519930"
            }

A: Use normal parser from jackson lib by this example

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I synchronize the To do Ubuntu app and calendar with google In 18.04 the google to do list and calendar tasks where automatically synchronized with the to-do app and calendar, but this is not happening with 20.04.01 (my google accounts are already "registered" to Ubuntu)
Is there anything I can do?
Thanks


text:
Q: Uploading file to a REST api server using Android HTTP client I am using a dummy rest API server called json-server. I wrote an android app which is able to make POSt request to the server, server returns an expected 201 as well.
I am not very familiar with REST api. I want to send a File from my device
     public void run() {
                    Logger.d("reponse","inside thread");

                    HttpClient client = new DefaultHttpClient(TunnelView.this);
                    String url = "http://some_server:3000/comments";
                    HttpGet get = new HttpGet(url);
                    HttpPost post = new HttpPost(url);
                    HttpResponse response = null;
                    post.setEntity(new FileEntity(new File("/root/sdcard/Download/File.txt"),"application/octect-stream"));
                    try
                    {
                        response = client.execute(post);
                        String res = response.getEntity().getContent().toString();
                        Logger.d("response", res);

                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            }

Every time I do a post, a new Id is added under the Comments array on my json file located on the rest API server.
  "comments": [
{
  "id": 1,
  "body": "some comment",
  "postId": 1
},
{
  "id": 2
},]

I am not sure how to change my android code or the REST API Post URl so I can send the whole text file content and it gets posted on the json file on the server.

A: try this out
    public static JSONObject postFile(String url,String filePath,int id){
    String result="";
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    File file = new File(filePath);
    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "image/jpeg");
    StringBody stringBody= null;
    JSONObject responseObject=null;
    try {
        stringBody = new StringBody(id+"");
        mpEntity.addPart("file", cbFile);
        mpEntity.addPart("id",stringBody);
        httpPost.setEntity(mpEntity);
        System.out.println("executing request " + httpPost.getRequestLine());
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity resEntity = response.getEntity();
        result=resEntity.toString();
        responseObject=new JSONObject(result);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return responseObject;
}

this code works perfectly, use this and if you find any difficulty, do comment.
 Happy coding!!


text:
Q: Where my file goes with gcloud compute scp command? I am trying to move my local file to my newly created gcp vm instance named 'instance-1'. I tried this command:
gcloud compute scp D:\FPX\new_tst.txt instance-1:

It tells me:
new_tst.txt               | 0 kB |   0.2 kB/s | ETA: 00:00:00 | 100%

This means there is no error. But when I check on vm instance using cloud shell in the browser, I don't see any file.
I have checked root folder /, /home/$USER, /tmp but couldn't find any where.
Can someone guide me where it goes?

A: Finding file
If you just want to find out where your file goes after gcloud compute scp command, then you can try to find out the file by following @Fady's suggestion. I would suggest first changing to the root user by using sudo -s command once you have sshed into the VM from cloud shell, then run the below command which will search the whole / directory tree.

[root@instance-1]# find / -name new_tst.txt

Note: I believe you are using a Linux VM and your local machine is windows.
Moving a file from local to GCP VM
You can use the below command to do the SCP from local windows machine to the GCP VM. You need to specify the path of destination VM and make sure the user has the write access to it and also the directory already exists in the destination VM. This example command uses users home directory.

gcloud compute scp C:\test\file.txt user@instance-1:/home/user --zone zonename

However, before doing so you need to authenticate properly with gcloud auth login command and use the authorized service account or user to do the task. It is a good idea to check with gcloud auth list command to list credentialed accounts. Whichever account has an asterisk beside it, is the active account.
Hope this helps.


text:
Q: Updated Excel Cell value by Name Reference in C# I have a named cell in excel lets say its called "myCell"
In C# I wish to be able to access this cell and update its value.
I've tried
Globals.ThisAddIn.Application.Names.Item(@"myCell").Value = "myValue";

But this throws a COM exception with the message 'Exception from HRESULT: 0x800A03EC'

A: Your problem is that:
Globals.ThisAddIn.Application.Names.Item(@"myCell")

does not return a Range for which you can set the value, but an object of type Name. You can get the Range representing the cell you are looking for using the RefersToRange property and then set the value for this object. This all translates into something like this:
Globals.ThisAddIn.Application.Names.Item(@"myCell").RefersToRange.Value = "myValue";

A: Just use the Range object. A named cell is a named Range, so this should work:
myWorkBook.myWorkSheet.Range["myCell"].Value = "myValue";

P.D. I have no way to check this and I'm not sure if you can assign the value directly to a Rangeobject or you need to specify the offset of the cell inside the Range (as it can contain many cells).
You can also try: (I dont remember if named ranges work directly with cells)
myWorkBook.myWorkSheet.Cells["myCell"].Value = "myValue";

A: Use:
var cell = myWorksheet.Evaluate("defined_name");
if (cell != null) { cell.Value = "hello"; }

Or:
myWorksheet.Cells.SetValue("defined_name", "hello");

In the last case, trying to set a value for a non-existing name gives "Exception from HRESULT: 0x800A03EC"
If checking for null doesn't work, check this answer for a list of int values as errors.


text:
Q: Bundle install fails, Gem install succeeds When trying to bundle install on a Gemfile that contained only the GitHub Pages gem and nothing else, on Ubuntu 18.04, I got error messages telling me to try installing eventmachine using gem install.  That always succeeds, but bundle install still fails.  How can I get bundler to see that the gem is installed?

A: I fixed this after many hours of struggle, by noticing that on the GitHub Pages repo there's a note that says

Important: Make sure you have Bundler > v1.14 by running gem update bundler in your terminal before following the next steps.

I have no idea why this mattered but I removed my ruby packages from Ubuntu and reinstalled them, then installed bundler with rubygems, which gave me a newer version:

sudo apt-get remove ruby
sudo apt-get install ruby ruby-dev
sudo gem install bundler
bundler --version

If anyone knows why I needed that version of bundler, or how I should have diagnosed this faster, I'd be interested to hear it.  I'm not new to programming but I'm new to Ruby.

A: From my understanding it might be the gem you are trying to install requires a specific feature provided by bundler. If you check the change log of bundler there is some changes related to install github based gems on how to correctly read the user git settings. So I think that might be where the problem is from.


text:
Q: TCPDF cómo guardar un pdf generado en una ruta de red Estoy tratando de guardar en una ruta de mi red un documento pdf generado con la librería TCPDF, pero no lo he conseguido a pesar de que la carpeta tiene full permisos para Everyone y Anonymous Logon. (en una carpeta local del servidor si se almacena el pdf de manera correcta)
He intentado de esta manera:
$this->folder = '//servidor/carpeta/nombreArchivo.php';
$this->pdf = Output($this->folder, 'F');

Y obtengo este error:

Warning: fopen(file:////servidor/carpeta/nombreArchivo.php): failed to open stream: No such file or directory in ...\TCPDF\include\tcpdf_static.php on line 1821

TCPDF ERROR: Unable to create output file: //servidor/carpeta/nombreArchivo.php

Y de esta manera:
$this->folder = '\\\\servidor\\carpeta\\nombreArchivo.php';
$this->pdf = Output($this->folder, 'F');

Obteniendo el siguiente error:

Warning: fopen(): remote host file access not supported, file://\servidor\carpeta\nombreArchivo.php in ...\TCPDF\include\tcpdf_static.php on line 1821

Warning: fopen(file://\servidor\carpeta\nombreArchivo.php): failed to open stream: no suitable wrapper could be found in ...\TCPDF\include\tcpdf_static.php on line 1821

TCPDF ERROR: Unable to create output file: \servidor\carpeta\nombreArchivo.php

Alguna idea de lo que puede estar sucediendo que no me permite almacenar el archivo en esta ruta de red?
PD: Ya probé almacenar en una carpeta local el pdf y usar la función copy de PHP para copiar el archivo a la ruta de red, obteniendo un resultado similar:

Warning: copy(//servidor/carpeta/nombreArchivo.php): failed to open stream: Permissions denied in ...\proyecto\Controllers\generarPdf.php on line 37

A: Después de investigar, opté por resolverlo con una conexión FTP.
De esta manera genero el archivo en el servidor local con TCPDF y posteriormente lo traslado al servidor remoto a través de las funciones FTP de PHP.
Aquí encuentran las diferentes funciones disponibles, aunque con las básicas debería ser suficiente.
En la documentación oficial exponen un ejemplo de uso básico.
<?php
    // establecer una conexión básica
    $conexion_ftp = ftp_connect($servidor_ftp);

    // iniciar una sesión con nombre de usuario y contraseña
    $sesion_ftp = ftp_login($conexion_ftp, $usuario_ftp, $contrasena_ftp);

    // verificar la conexión
    if ((!$conexion_ftp) || (!$sesion_ftp)) {
        echo "¡La conexión FTP ha fallado!";
        echo "Se intentó conectar al $servidor_ftp por el usuario $usuario_ftp";
        exit;
    } else {
        echo "Conexión a $servidor_ftp realizada con éxito, por el usuario $usuario_ftp";
    }

    // subir el archivo
    $carga_ftp = ftp_put($conexion_ftp, $archivo_destino, $archivo_origen, FTP_BINARY);

    // comprobar el estado de la subida
    if (!$carga_ftp) {
        echo "¡La subida FTP ha fallado!";
    } else {
        echo "Subida de $archivo_origen a $servidor_ftp como $archivo_destino";
    }

    // cerrar la conexión ftp
    ftp_close($conexion_ftp);
?>

Espero que esta información le sirva de referencia a alguien que tenga un caso similar.


text:
Q: MACOS: Error using P2D argument in JAVA (ECLIPSE IDE) ERROR
2022-09-01 13:17:41.599 java[13634:814287] Apple AWT Internal Exception: NSWindow drag regions should only be invalidated on the Main Thread!
2022-09-01 13:17:41.599 java[13634:814287] trace: (
0   CoreFoundation                      0x00007ff817215e7b __exceptionPreprocess +242
1   libobjc.A.dylib                     0x00007ff816f77e48 objc_exception_throw + 48
2   CoreFoundation                      0x00007ff81723e8a6 -[NSException raise] + 9
3   AppKit                              0x00007ff819b372f4 -[NSWindow(NSWindow_Theme)_postWindowNeedsToResetDragMarginsUnlessPostingDisabled] + 321
4   AppKit                              0x00007ff819b232a4 -[NSWindow_initContent:styleMask:backing:defer:contentView:] + 1288
5   AppKit                              0x00007ff819b22d96 -[NSWindow initWithContentRect:styleMask:backing:defer:] + 42
6   libnativewindow_macosx.jnilib       0x000000015c066f9e Java_jogamp_nativewindow_macosx_OSXUtil_CreateNSWindow0 + 398
7   ???                                 0x000000010c1c6187 0x0 + 4498153863

)
2022-09-01 13:17:41.599 java[13634:814287] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'NSWindow drag regions should only be invalidated on the Main Thread!'
*** First throw call stack:
(
0   CoreFoundation                      0x00007ff817215e7b __exceptionPreprocess + 242
1   libobjc.A.dylib                     0x00007ff816f77e48 objc_exception_throw + 48
2   CoreFoundation                      0x00007ff81723e8a6 -[NSException raise] + 9
3   AppKit                              0x00007ff819b372f4 -[NSWindow(NSWindow_Theme) _postWindowNeedsToResetDragMarginsUnlessPostingDisabled] + 321
4   AppKit                              0x00007ff819b232a4 -[NSWindow _initContent:styleMask:backing:defer:contentView:] + 1288
5   AppKit                              0x00007ff819b22d96 -[NSWindow initWithContentRect:styleMask:backing:defer:] + 42
6   libnativewindow_macosx.jnilib       0x000000015c066f9e Java_jogamp_nativewindow_macosx_OSXUtil_CreateNSWindow0 + 398
7   ???                                 0x000000010c1c6187 0x0 + 4498153863

)
libc++abi: terminating with uncaught exception of type NSException
CODE
package module1;

import processing.core.PApplet;
import de.fhpotsdam.unfolding.UnfoldingMap;
import de.fhpotsdam.unfolding.geo.Location;
import de.fhpotsdam.unfolding.providers.AbstractMapProvider;
import de.fhpotsdam.unfolding.providers.Google;
import de.fhpotsdam.unfolding.providers.MBTilesMapProvider;
import de.fhpotsdam.unfolding.utils.MapUtils;

/** HelloWorld
  * An application with two maps side-by-side zoomed in on different locations.
  * Author: UC San Diego Coursera Intermediate Programming team
  * @author Your name here
  * Date: July 17, 2015
  * */
public class HelloWorld extends PApplet
{
    /** Your goal: add code to display second map, zoom in, and customize the background.
     * Feel free to copy and use this code, adding to it, modifying it, etc.
     * Don't forget the import lines above. */

    // You can ignore this.  It's to keep eclipse from reporting a warning
    private static final long serialVersionUID = 1L;

    /** This is where to find the local tiles, for working without an Internet connection */
    public static String mbTilesString = "blankLight-1-3.mbtiles";

    // IF YOU ARE WORKING OFFLINE: Change the value of this variable to true
    private static final boolean offline = true;

    /** The map we use to display our home town: La Jolla, CA */
    UnfoldingMap map1;

    /** The map you will use to display your home town */
    UnfoldingMap map2;

    public void setup() {
        size(800, 600, P2D);  // Set up the Applet window to be 800x600
                              // The OPENGL argument indicates to use the
                              // Processing library's 2D drawing
                              // You'll learn more about processing in Module 3

        // This sets the background color for the Applet.
        // Play around with these numbers and see what happens!
        this.background(200, 200, 200);

        // Select a map provider
        AbstractMapProvider provider = new Google.GoogleTerrainProvider();
        // Set a zoom level
        int zoomLevel = 10;

        if (offline) {
            // If you are working offline, you need to use this provider
            // to work with the maps that are local on your computer.
            provider = new MBTilesMapProvider(mbTilesString);
            // 3 is the maximum zoom level for working offline
            zoomLevel = 3;
        }

        // Create a new UnfoldingMap to be displayed in this window.
        // The 2nd-5th arguments give the map's x, y, width and height
        // When you create your map we want you to play around with these
        // arguments to get your second map in the right place.
        // The 6th argument specifies the map provider.
        // There are several providers built-in.
        // Note if you are working offline you must use the MBTilesMapProvider
        map1 = new UnfoldingMap(this, 50, 50, 25, 25, provider);

        // The next line zooms in and centers the map at
        // 32.9 (latitude) and -117.2 (longitude)
        map1.zoomAndPanTo(zoomLevel, new Location(32.9f, -117.2f));

        // This line makes the map interactive
        MapUtils.createDefaultEventDispatcher(this, map1);

        // TODO: Add code here that creates map2
        // Then you'll modify draw() below

        map2 = new UnfoldingMap(this, 350, 350, 25, 25, provider);

        // The next line zooms in and centers the map at
        // 32.9 (latitude) and -117.2 (longitude)
        map2.zoomAndPanTo(zoomLevel, new Location(72.9f, -217.2f));

        // This line makes the map interactive
        MapUtils.createDefaultEventDispatcher(this, map2);

    }

    /** Draw the Applet window.  */
    public void draw() {
        // So far we only draw map1...
        // TODO: Add code so that both maps are displayed
        map1.draw();

//      map2.draw();
    }

}

WHAT I HAVE TRIED
The application runs once i remove the P2D argument, not sure what the issue is. As suggested by some of the answers, I tried using the older versions of JRE- (https://github.com/AdoptOpenJDK/openjdk8-binaries/releases/tag/jdk8u242-b08) but I am getting the same error.


text:
Q: DapperPlus BulkMerge Infromation about insert/update I am trying to get some information after successful BulkMerge operation.
I want to know, how many rows are updated and how many are inserted.
I was trying with Transaction but had no luck with that.
My code :
using (var transactionScope = new TransactionScope())
        {
            Connection.BulkMerge(compUsers);
            transactionScope.Complete();
            var x = transactionScope;
        }

compUsers is list with data that will be inserted/updated. But I have no idea how to get some relevant information about this transaction.
Thanks in advance.

A: Unfortunately this isn't possible.
As explained by JonathanMagnan on this link.
https://github.com/zzzprojects/Dapper-Plus/issues/34


text:
Q: Parsing the end of a tcp connection There are a number of ways that a TCP connection can end.  This is my understanding:
rst: is immediate.  The connection is done, and immediately closes.  All further communication is a "new" connection.
fin: is a nice request from one side.  It must be acknowledged, and the other side then sends a fin to say they are done talking.  This too must be acknowledged.  These stages CAN happen simultaneously, but a fin and the ack that accompanies it must be passed.
Are there any others?  I'm looking at a tcp stream in Wireshark that just has a fin, psh, and ack bit sent.  This is acknowledged and the connection is over.  What other ways of closing a TCP connection are there?
If a fin is acked, can more data be sent?  If it is, does the original fin need to be resent (does the state of the side that sent the fin reset at some point)?

A:
Are there any others?

No.

I'm looking at a tcp stream in Wireshark that just has a fin, psh, and ack bit sent. This is acknowledged and the connection is over.

No. It is shut down in one direction only. It isn't over until both peers have sent a FIN.

What other ways of closing a TCP connection are there?

None.

If a fin is acked, can more data be sent?

It can't be sent even if the FIN wasn't ACKed, in the direction that the FIN was sent. It can be sent in the other direction.

If it is, does the original fin need to be resent (does the state of the side that sent the fin reset at some point)?

Can't happen.

A: There is indeed only 2 ways to close a TCP connection.

*

*The FIN 4 way handshake

*The RST

The FIN mechanism is the normal way of closing a TCP connection. You must understand that a TCP socket has a state machine underneeth. This statemachine is checked for each operation on the socket that happens. A close on a socket is called a halfclose. If you do this, it is like telling I have nothing more to send anymore. The state machine underneeth the socket is really going to check this, if you still were to try to send you will get error return codes.
The statemachine i am talking about is very well described over here with drawings ;-) http://www.tcpipguide.com/free/t_TCPOperationalOverviewandtheTCPFiniteStateMachineF-2.htm
The TCP/IP guide is an online book, also the RST scenario's that can happen are described in that book, as is the sliding window mechanism, byte acking, nagle and many other things. And not just for TCP, other protocols as well.


text:
Q: Sqlite circular dependency trigger The question is about Sqlite DBMS.
I have two tables:

*

*describes objects

*describes dependencies of objects from table 1 { id, id_parent }

How to write an INSERT and UPDATE triggers for table 2 to check for circular dependencies?
Example of objects dependencies:
A -> B -> C --- ok
A -> B -> C -> A --- raise condition
I understand how to check the immediate dependency A -> B, but have no idea how to check for any level.

A: You're pushing the proverbial uphill.
One fairly simple solution, which may or may not be feasible in your circumstances, is to have a constraint on the second table: id > id_parent. This will make it impossible to create cyclic graphs:
CREATE TABLE deps ( id NOT NULL, id_parent NOT NULL, CHECK ( id > id_parent ) )


text:
Q: Debugging in Visual Studio 2008/2010 - toggle off highlighting of rows In Debug-mode, the row currently executed is highlighted yellow and a yellow arrow is shown. Is it possible to turn the highlighting of the row off/on?

A: In VS2010: Menu Debug -> Options and Settings / General - Checkbox "Highlight entire source line for breakpoints and current statement.

A: Tools -> Options -> Fonts and Colors.
Find "Current statement" in the list and change the background to whatever your text editor background is. You might also want to change the other "Current ..." settings.


text:
Q: What currency to use in unit tests? I'm developing an application that relies heavily on Joda-Money, and have a number of unit tests that verify my business logic.  One (admittedly minor) sticking point for me has been what sort of Money/BigMoney objects to test with; specifically, what CurrencyUnit to use.
As I see it, I have a couple of options:

*

*Just use USD
This is clearly the easiest way to go, and most of my actual application will be working with US Dollars so it makes a fair bit of sense.  On the other hand, it feels rather US-centric, and I'm concerned it would risk letting currency-specific errors go unchecked.

*Use another real currency, like CAD
This would catch erroneous hard-codings of USD, but otherwise isn't much better than just using USD.

*Use a dedicated "fake" currency, i.e. XTS
This clearly makes sense, after all, XTS is "reserved for use in testing".  But Joda denotes psuedo-currencies as currencies with -1 decimal places.  In practice, the primary difference between currencies in Joda-Money is the number of decimal places, so this risks masking any errors involving decimal place precision, such as erroneously rounding to an integer value.

*Register my own custom currency with CurrencyUnit.registerCurrency()
This would obviously work, but seems a little odd seeing as there are alternatives.

*Use a CurrencyUnit instance created by a mocking library
Pretty much the same as registering a custom currency.
Again, this is obviously a minor issue, but I'm curious if there's a standard practice for cases like this, or if there's a clear reason to prefer one of these options in particular.

A: Use USD (or, generally, whatever currency is most commonly used in your application). I say this for two reasons:

*

*Good test data is unremarkable in every respect except that part of it which the test is actually about. When you're writing tests that don't have anything to do with differences between currencies, you don't want to have to think about differences between currencies. Just use whatever is most natural in the application.

*The idea that using an unusual currency everywhere will somehow result in better testing of unusual currencies is a red herring. Tests should be explicit and focused. If you need to test something about a specific currency, write a test whose point is to test that thing. And if a test is not about a specific currency, it shouldn't break when handling of some unusual aspect of that currency breaks -- it's not valuable to have half your tests break for the same reason; you only want one to break. So there is just no need to spread unusual currencies around the test suite and hope that that will catch something. Instead, optimize for readability; see point 1.

A: Since most of your application deals with U. S. dollars, it makes sense to use them for the vast majority of your tests. What currency-specific errors are you worried might happen? Missing halfpennies when compounding interest? Conversion to yen and back is off by a cent or two? Write tests for that.
If I were you, I'd fire up a local REPL (a Scala REPL works very well if you don't have JShell), run a few experiments. You'll probably find that you worried for nothing. Or you might discover that there is indeed a flaw, and your REPL session will inform how you write a test for that flaw.
You're using Joda Money because you don't want to reinvent this particular wheel. I didn't realize that until I read the question details. Presumably Joda Money has been tested rigorously by its developers and it does everything you expect it to do. You don't need to test it again.
But if you were making your own class to represent money amounts, I would suggest you use U. S. dollars, euros, Japanese yen and Lybian dinars (LYD). The reason for the first three is obvious. I suggest Lybian dinars because of the three decimal places. From what I can gather, there is no physical 1 dirham coin, so, for example, 513 darahim would get rounded down to 500 darahim and 997 darahim would get rounded up to a full dinar.
To test conversions, I would start with East Caribbean dollars (XCD), since they are fixed to exchange to US$2.70. Later on you can worry about currencies that fluctuate in relation to each other, and whether you're going to deal with them by mocking a rate server, or by connecting to an actual rate server but putting variances in your tests or by some other way.


text:
Q: Net::SMTPAuthenticationError (535-5.7.8 Username and Password not accepted. Learn more at ): with devise mailer i have got weird issue while working with my application.
In My app there will be lot mailer options which is write by own and it works perfectly. I have used Devise gem Authentication and those mails like (registration, forgot password, confirmation) mails are not working. End up with issue
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.perform_deliveries = true
  config.action_mailer.raise_delivery_errors = true
  # config.action_mailer.default :charset => "utf-8"

  config.action_mailer.smtp_settings = {
    :user_name => ENV['sendgrid_username'],
    :password => ENV['sendgrid_password'],
    :domain => '*****.com',
    :address => 'smtp.sendgrid.net',
    :port => 587,
    :authentication => :plain,
    :enable_starttls_auto => true
  }

I dont know why i am getting the devise mailer issue, other custom mailers are working fine.

Completed 500 Internal Server Error in 10789ms (ActiveRecord: 4434.0ms | Allocations: 260142)
Net::SMTPAuthenticationError (535-5.7.8 Username and Password not accepted. Learn more at):

I have inherited the mail in my custom mailer even though i have got same issue.
class UserMailer < ActionMailer::Base
  include Devise::Mailers::Helpers

  default from: "default@mydomain.com"

  def confirmation_instructions(record, token, opts={})
    @token = token
    devise_mail(record, :confirmation_instructions, opts)
  end

  def reset_password_instructions(record, token, opts={})
    @token = token
    devise_mail(record, :reset_password_instructions, opts)
  end

  def unlock_instructions(record, token, opts={})
    @token = token
    devise_mail(record, :unlock_instructions, opts)
  end

  def email_changed(record, opts={})
    devise_mail(record, :email_changed, opts)
  end

  def password_change(record, opts={})
    devise_mail(record, :password_change, opts)
  end

  # you can then put any of your own methods here
end


text:
Q: python function-converting texting language to english? I'm having trouble creating a function that uses a dictionary of texting abbreviations, and using the dictionary to write functions that translate to and from English. For example: "y r u l8?" translates to "Why are you late?"
So I have this so far: (I don't need every single texting phrase)
def text(string):
    textDict={'y':'why', "l8":'late','u':'you','gtg':'got to go', 'lol': 'laugh out loud', 'ur': 'your',}

any help is appreciated!

A: If you have a dictionary of replacements you can do this:
replacements = {
  'lol': 'laugh out loud',
  'y': 'why',
  'l8': 'late',
  'u': 'you',
  'r': 'are'
}

s1 = 'y r u l8'

s2 = ' '.join([replacements.get(w, w) for w in s1.split()])

A: *

*string needs to be split into words

*then loop through each word and replace it with the one in the dictionary if found

*Then, reconstruct a new string from the words and return it.

str.split() splits into an array, array.join() joins it back.
This won't work if there is punctuation in the sentence.  You would have to detect that and use the word without punctuation as the key

A: You could just split the text string and if its parts are in textDict and if they are replace them with the contents of the dictionary:
def translate(text_string, text_dict):
   for word in text_string.split():
       if word in text_dict:
           text_string = text_string.replace(word, text_dict[word]
  return text_string

A: For something a bit more elaborate try lookahead-lev. I made it for a similar situation. Just put your "thumblish" into a yaml file and call it. It's designed to be a web service, but you could probably modify it to suit your needs.


text:
Q: Are there negative effects for wasting time? In Skyrim, you can sleep or wait for up to a day at a time. Is there any negative consequences to wasting time like this? Do certain quests expire or certain conditions happen after several days (or even weeks) have passed that can be considered negative?
Obviously temporary buffs expire, but that happens after one day.

A: Nothing negative happens if you wait for a long time. Anything you have killed (dungeons, guards, etc.) will re-spawn and shop keepers will get new stock. Quest will not expire at any point so you are safe to wait for as long as you like.


text:
Q: SQL query cannot use NOT LIKE to get results I am starting out in SQL and am trying to do a query that will select all event names that are unique and do not have 'TODAY-XXXXXXXX' in the value for the event_name column. I have a query that works fine for getting the unique values from the table, but I cannot get the NOT LIKE to work well.
For example, I was to remove all items that have this as their name TODAY-20191021 the data at the end can change but all have the TODAY in front of the date
This is the query that is working fine
SELECT DISTINCT event_name, COUNT(*)
FROM events
GROUP BY event_name
Having COUNT(*) > 100.

But when I try to add the where clause it fails with this error

Error running query: column "TODAY-%" does not exist LINE 3: WHERE event_name NOT LIKE "TODAY-%" ^

This is what I have so far
SELECT DISTINCT event_name, COUNT(*)
FROM events
WHERE event_name NOT LIKE "TODAY%"
GROUP BY event_name
Having COUNT(*) > 100.

A: Here:
WHERE event_name NOT LIKE "TODAY%"

Because you use double quotes, the database considers this string as an identifier (here, a column name). Instead, you want to use single quotes, that stand for literal strings:
WHERE event_name NOT LIKE 'TODAY%'


text:
Q: jenkins how to execute perticular command based on the keyword in the git commit message? When I do a git commit, in commit message I will specify test class name and in junkins post-build step I am running a shell command(spoon) which needs the class name parameter which is in the git commit message.
I have 6 test classes depending upon the commit message perticular command should run.
example commit message :- git commit 'update [coreTest.java]'
command to run
java -jar spoon-runner-1.1.9-jar-with-dependencies.jar \
--apk example-app.apk \
--test-apk example-tests.apk
--class-name  coreTest.java

coreTest.java is the class name should be placed depending on the commit message.

A: One idea would be to have post-receive hook on the git server side, which would:

*

*analyze the commit message of the git commits pushed (as in this answer or this one)

*call a jenkins job (one of the 6 jobs depending of the commit message)

A: try Parametrized plugin
select and pass your class name as parameter


text:
Q: Laravel CKEditor Saves to DB but HTML does not render on page I have CKEditor enabled for details in my view for Projects.  All is working fine as in I can create a new project and it saves to the database.  When I look in the projects table in the details column I see my html
This is some details
.  When I try showing the $project->details in a view it does not render the HTML and just prints to
This is some details
 the screen.
As this answer suggests From my blade file I tried {{ html_entity_decode($project->details) }} and it does the same thing (doesnt render html from database).  I believe this is specific to Laravel and how it fetches/stores the data because I previously had this project in Codeigniter and was able to simply echo the value to the screen.
When I use {{ html_entity_decode($project->details) }}I Get this:

This will render the HTML but I don't think it is how I should be doing it and it prints a number (in this case 1) after the HTML.
{{ print($project->details) }}
This is what happens when I use (notice the random 1 at the bottom) {{ $project->details }}

Here is my DB table

How do I get the html to render on the page/is print the best way to do this in laravel or php?

A: There's no reason why that '1' should show up. Can you make sure you don't have any Mutators on your model.
Also if you are pretty sure about all the data coming from your DB and want to output the html as is you can try {!! $project->details !!}


text:
Q: Organizing and Documenting Multi-File JavaScript Projects I'm beginning a fairly large JavaScript project. The project will have everything exist within one or more namespaces, so only a sparse number of things will exist in the global scope (at the moment, there is only one thing).
In order to keep things organized, I would like to keep each class in its own file (much like you would other many other languages) instead of in "modules".
I built a little compilation script (with NodeJS) which will compile all of the files in to a single JavaScript file at the end of the day.
I thought I had a good method, but I'm trying to get JSDoc(3) to cooperate with me and not having a lot of luck, so I'm wondering if I'm maybe tackling this in the wrong way, or if there is some trick with JSDoc I'm missing.
In the source, each namespace is a folder and each class is a file of the same name.
Each class file looks something like this:
var BaseNS = BaseNS || {};
BaseNS.SubNS = BaseNS.SubNS || {};

BaseNS.SubNS.MyClass = (function() {
    function MyClass() {
    }

    Object.defineProperties(MyClass.prototype, {
       'someProp', {
            getter: function() { return this._someProp = this._someProp || 0; },
            setter: function(val) { this._someProp = val; }
       }
       // ... more
    });

    MyClass.prototype.someMethod = function() {};
    // ... more

    return MyClass;
}}());

When compiled together, my compilation script handles dependencies to get the classes in the correct order and also removed duplicate namespace declaration lines.
I think this method is relatively clean and straight-forward. The catch is, I can't figure out how to write the JSDoc documentation in a way which gives me things as I think they should be.
I would like to go with a "class-like" method for things. This is actually for an application which is largely removed from the DOM. Also, I'd like the entire project to be vanilla, modern JavaScript (i.e., no RequireJS, etc.)
Any ideas how to get this documented, or a better way to arrange things?
Thanks.

A: After playing around with various things for about four hours yesterday, I think I've figured out the optimal format, which combines nice efficent form while allowing for minimal comments to get things to parse properly.
"use strict";

/** @namespace */
var NS = NS || {};

/** @namespace */
NS.Sub = NS.Sub || {};

/**
 * @class
 */
NS.Sub.SomeClass = (function(NS) {
    /**
     * @constructor
     * @lends NS.Sub.SomeClass
     */
    var SomeClass = function() {
        /** @method */
        this.someFunc = function(cookie) {

        };

        Object.defineProperties(this, /** @lends NS.Sub.SomeClass */ {
            /**
             * @type {number}
             * @instance
             */
            somePublicProp: {
                getter: function() { return this._somePublicProp || 24; },
                setter: function(val) { this._somePublicProp = val; }
            }
        });
    };

    return SomeClass;
})(NS);

If anyone has any recommendations on how to make this better, I'd love to hear them. In particular, I can't figure out a way to get rid of the need for var SomeClass; ... return SomeClass. I'd like to just return it directly (preferably without any name), but then JSDoc loses track of my method, which means more comments, which isn't cool.


text:
Q: How to choose correct version of gatsby-plugin-sharp when using FreeBSD v11.3 server? I'm trying to install and build Gatsby app on the FreeBSD v11.3 server. My gatsby app use gatsby-plugin-sharp and gatsby-transformer-sharp and I think those plugins cause the error.
This was the first error I got during npm install:
ERR! sharp BSD/SunOS systems require manual installation of libvips >= 8.9.1

So I installed older versions of gatsby-plugin-sharp and gatsby-transformer-sharp to match the installed libvips on the system (sharp v0.22.1). After that error disappeared but the next error appeared during gatsby build:
Error: pngquant: unrecognized option `--strip'

What should I do to make it work? What versions do I need to use?


text:
Q: JavaScript: Post with Dictonary in body, never returns any values (curl pr PHP example works) I am trying to get a simple user by ID. In my case the field is called userID and the ID is 150. I know from the server, that this user exists. I also get returned all users, so the connection is fine.
This is what I tried:
 var dict = new Object();
    var dict = {
      "userID": "150"
    };

    fetch(url,
      {method:'POST',
       headers: { 'Authorization': 'Basic ' + btoa(username+ ":" + password), },
         body: JSON.stringify(dict),
      })
    .then(response => response.json())
    .then(json => console.log(json));

But no matter, I will always receive a payload of 0.
From the official docs of the server it says:
"You need to send a params dictionary in the POST body. This is a key, value pair array of your method's input parameters. If you're unsure of what these are, they can be seen when you run a method in Kumulos' control panel".
They even post an example:
curl -X POST
     -H "Content-Type: application/x-www-form-urlencoded"
     -H "Accept: application/json"
     -H "Authorization: Basic base64EncodedUsername:Password"
     -H "Cache-Control: no-cache"
     -d 'params[photos]=1
         &params[timeCreated]=1462060800'
    "https://api.kumulos.com/b2.2/yourAPIKey/getNewPhotographers.json"

Saying they gave as parameters "timeCreated".
Even in PHP, they claim this would work:
CURLOPT_POSTFIELDS => "params[photos]=1&params[timeCreated]=1462060800",

is my "translation" to javascript that wrong?
Only from what the docs say, would you agree that my code is correct, or is the issue with me?
I also havent been able to get the correct results from postman with these parameters.
Thank you !
EDIT:
I was however able to get the correct data doing it the old way:
var xhr = new XMLHttpRequest();
xhr.open("POST", url);

xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Authorization", 'Basic ' + btoa(username+ ":" + password));

xhr.onreadystatechange = function () {
   if (xhr.readyState === 4) {
      console.log(xhr.status);
      console.log(xhr.responseText);
   }};
   var data = `params[userID]=150`;

xhr.send(data);

A: The example shows that the API expects URL-encoded parameters, not JSON. And the parameter names need to be enclosed in params[...].
The equivalent JS is
let body = Object.entries(dict).map(([key, value]) =>
    encodeURIComponent(`params[${key}]`) + '=' + encodeURIComponent(value)).join('&');
fetch(url, {
    method: 'POST',
    headers: {
        Authorization: 'Basic ' + btoa(username+ ":" + password),
        "Content-Type": "application/x-www-form-urlencoded"
    },
    body: body
}).then(response => response.json())
    .then(json => console.log(json));


text:
Q: Child component list not rendering I am trying to render a list using a child component and it ends up not rendering anything.
Snippet in PropertyBar component:
updateSelectedCell() {
    if (graph.selectedCell != null) {
      this.setState({
        selectedCell: graph.selectedCell,
        cellProperties: Array.from(graph.selectedCell.value.attributes)
      });
    }
  }

  renderPropertyList() {
    this.state.cellProperties.map(key => {
      <PropertyBarItem name={key.nodeName} value={key.nodeValue} />
    })
  }

  render() {
    if (this.state.selectedCell != null) {
      return (

          <Button variant="contained" color="primary" fullWidth={true} onClick={() => this.updateSelectedCell()}> View properties </Button>
          <List>
            {this.renderPropertyList}
          </List>

      )
    }
    return (

        <Button variant="contained" color="primary" fullWidth={true} onClick={() => this.updateSelectedCell()}> View properties </Button>
        <List>

Click on a cell to view its properties.

        </List>

    )
  }

When a user clicks on the button, it updates the state with an array then should render a list of PropertyBarItem with the keys inside the array. It ends up not displaying anything, but doesn't crash. Testing using a simple p tag and it also does not render anything:
renderPropertyList() {
    this.state.cellProperties.map(key => {

 {key}

    })
  }

A: You are not invoking the renderPropertyList method. Add () to invoke it.

  <Button
    variant="contained"
    color="primary"
    fullWidth={true}
    onClick={() => this.updateSelectedCell()}
  >
    View properties
  </Button>
  <List>{this.renderPropertyList()}</List>

You must also return the result from renderPropertyList and return the JSX from the function given to map as well.
renderPropertyList() {
  return this.state.cellProperties.map(key => {
    return <PropertyBarItem name={key.nodeName} value={key.nodeValue} />
  })
}

A: You're missing the return statement:
renderPropertyList() {
  return this.state.cellProperties.map(key => {
    <PropertyBarItem name={key.nodeName} value={key.nodeValue} />
  })
}

Also, be sure to invoke the method:
 if (this.state.selectedCell != null) {
      return (

          <Button variant="contained" color="primary" fullWidth={true} onClick={() => this.updateSelectedCell()}> View properties </Button>
          <List>
            {this.renderPropertyList()}
          </List>

      )
    }


text:
Q: Using ODE to plot particle-motion with scipy.integrate.solve_ivp My Problem:

A positively charged particle  (mass = 2 * 10-27 kg) is moving along the x-axis. It is travelling in a homogenous magnetic field such that the field axis in z-direction. The energy of the particle is 2 MeV and B = 4 T. Use a ODE solver to plot the motion of the particle for 1 microseconds.

My attempt of solving the problem
Note that I have used question marks where I am unsure.
import numpy as np
from scipy.integrate import solve_ivp

initialZ = [?, ?, ?, ?, ?, ?] # = [positionX, positionY, positionZ, velocityX, velocityY, velocityZ]
t0 = 0
tf = 1*(10**-6) # 1 microsecond = 1*10^6 seconds
times = (t0, tf)

def ivf(t, Z):
  x, y, z = Z[0], Z[1], Z[2]
  u, v, w = Z[3], Z[4], Z[5]
  return np.array([u, v, w, ?, ?, ?])

s = solve_ivp(ivf, times, initialZ)

My question
what should the question marks (?) in the code be replaced with?
I have tried to solve the ODE as an initial value problem. I tried to determine inital velocity by equating the lorentz force and centripetal force. I am very new to differential equations and it is therefore difficult to know If I am doing things in the correct way. (note that the first three values of my initialZ vector represents positions x, y and z, and the last three values represent velocity in the x, y and z direction). I am grateful for any help or guidance.

A: Let us set up the ode and then the initial conditions. From the magnetic force equations and Newton's second law, a = (q B / m) v * z. I'm using * to represent the cross product and x, y, and z are unit vectors. In your question you didn't give a charge q for the particle, I'm assuming you are doing a proton and just rounded the mass of 1.67 to 2. You will see that we just need 4 equations and 4 initial conditions as this problem is 2D in nature.
We have that a = (q B / m) (v_y x - v_x y). Note there is no z term! We need to write these 2 second order odes as four first order odes so ode solver can work it out. We know that a = dv/dt.

*

*dv_x / dt = (q B / m) v_y

*dv_y / dt = -(q B / m) v_x

*dx/dt = v_x

*dy/dt = v_y

The initial condition is that the velocity is v_x0 = Sqrt(2 E / m) where E is 2 MeV, v_y0 = 0, and lets just have the particle start at the origin, so x0 = y0 = 0.
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt

# make sure everything is SI
q = 1.602176634E-19 # charge assuming it is a proton
B = 4 # magnetic field magnitude
m = 2E-27 # mass
E =  2 * 1.60218E-13 # kinetic energy in joules
C = q * B / m # constant for convenience
v0x = np.sqrt(2 * E / m)

initialZ = [0, 0, v0x, 0] # = [positionX, positionY, velocityX, velocityY]

def ivf(t, Z) :
# Z[2] is vx, Z[3] is vy
    dxdt = Z[2]
    dydt = Z[3]
    dvxdt = C * Z[3]
    dvydt = -C * Z[2]
    return [dxdt, dydt, dvxdt, dvydt]

sol = solve_ivp(ivf, [0, 1E-6], initialZ, method='Radau') # 1 microsecond = 1*10^6 seconds

plt.plot(sol.y[0], sol.y[1])
plt.xlabel('x')
plt.ylabel('y')
plt.title('Displacement on point particle')
plt.show()

What I am expecting is circular motion like in a cyclotron. Here is a rough graph I made,

I was able to get it a bit smooth by playing with the integration method. I'm sure you will be able to tinker and play around with different things until you get a satisfactory result.


text:
Q: Importing Data from .txt file to SQL Server 2005 Express I have a tab separated .txt (Very Small file with just 10 to 15 datasets) and this file is having some columns as PrdName, PrdSize, PrdWeight, PrdCode and so on.
Now I want to import the two columns which are PrdSize and PrdCode and import it in the columns of my Database table.
I have created the columns but how do I create import clause and transfer data from .txt file to SQL Server? Thanks

A: Since you have the express edition you'll need to either use BCP or write a program with something else.

A: Take a look at this post: Import/Export data with SQL Server 2005 Express, there are multiple options that you can use.

A: If you have a large amount of data, or need to automate the process, definitely look into BCP as mentioned already. However, I often use excel to load one-time data sources (a few hundred to a few thousand) rows of data from odd sources into SQL Server by doing the following:
Get the data into excel (that's usually easy), assuming you get column A with 'Prdsize' and column B with PrdCode, in column C put the formula:
="INSERT INTO MYTABLE(PRDSIZE, PRODCODE) VALUES (" & a1 & "," & B1 & ")"

(in other words create syntactically correct SQL using an Excel formula - you may need to add quotes around string values etc)
and then paste that formula all the way down the column C. Then copy/paste the resultant sql insert statements into SQL Management Studio, or any other tool that can execute SQL and execute it.
Defintely a 'manual' effort, but for one-time data loads it words great.
PS: You'll need to verify the XL formula and the resultant sql syntax - my example is close, but I didn't test it.


text:
Q: How to pass array with slashes or special characters? I'm using the jquery get() function to send data. The data was array with information that can have special characters like / , ? and " . When this happens i can't access to url because the characters spoil the link.
How can i solve that? I did this:
function exemple()
    {
      $('.add').click(function(e)
      {
        var kitFamilia = $('#select-family').val();
        var kitReference = $('#referenceinput').val();
        var kitDescription = $('#descriptioninput').val();
        var kitModel = $('#model-input').val();
        var supplier = $('#select-supplier').val();
        var details = [];

          //alert(data);
          details.push({stamp: stamp,family: kitFamilia, reference: kitReference, description: kitDescription, model: kitModel, supplier: supplier});
          details = JSON.stringify(details, null, 2);
          //alert(details);

          $.get("/management-kit/create-kit/"+details, function(data)
          {
            location.reload();
          });

        e.preventDefault();
      });
    }

A: You should encode the data with encodeURIComponent
$.get("/management-kit/create-kit/"+encodeURIComponent(details), ..

Keep in mind that you are sending the JSON encoded as part of the path and not as a parameter. (and you might also want to remove the 2 space formating of the JSON as it will make the url quite longer)


text:
Q: Save variable to stack (X86-64 assembly) I've written a small program in x86-64 assembly (AT&T) syntax, and it assembles just fine, but I don't get the result I expected.
I have a variable in register %rdi, which I need to modify in a subroutine, and I need to keep the original value for some other usage later. What I want to do is to push the original value onto the stack, and then retrieve it again when the subroutine finishes, for example, if the variable is located in %rdi.
    pushq %rdi
    call subroutine
    movq (%rsp), %rdi

Now, I'm not really sure if this is the correct way to do it? I've read somewhere that a subroutine pushes the return value onto of the stack, but does that mean that I have to include an offset when I try to retrieve the variable?
Also I know I have to keep the stack pointer aligned by 16 bytes, which I'm not quite sure if I do. In case I don't, will the assembler then give me an error, or could that be the reason why my program fails?
And by the way, this program is part of an assignment, so I cannot share the code with you, but I hope my description is good enough.

A: Instead of movq (%rsp),%rdi, use popq %rdi . The first doesn't update the RSP stack pointer, so you could be in a problem when returning to the function that called you.
This, of course, if subroutine doesn't adjust the stack for itself. It subroutine is using the standard (Pascal) calling convention, parameters will be removed by the function itself, and not the caller, and you will loose access to the saved %rdi value.

A: The code fragment is suspicious in that it fails to keep the stack pointer balanced across a call sequence, which is probably not the intended behaviour. Typically you would either match push and pop operations, push many times and then addq $k, %rsp (where k is the combined size of every previous push), or keep the frame size constant across the execution of the function and use explicit accesses.
Given that you need to keep keep the stack pointer 16-byte aligned, keeping a constant-sized frame is probably the most straightforward method. It might look like
# in the function prologue
subq $K, %rsp
...
mov %rdi, SLOT(%rsp)
call subroutine
mov SLOT(%rsp), %rdi
...
# in the epilogue
addq $K, %rsp

Where K is enough space for all the local stack state plus enough space for the largest set of outgoing arguments, rounded up to 16, and SLOT is a spot on the stack reserved for the value of %rdi.
The return value of an integer type usually placed in rax, not on the stack. Other types are returned differently (such as by a hidden pointer) - check the calling convention of the compiler you are interfacing with.


text:
Q: Sequel Pro and MySQL connection failed I just installed mysql on mac from Homebrew
brew install mysql

mysql -V

mysql  Ver 8.0.11 for osx10.13 on x86_64 (Homebrew)

from terminal it works and I can login to mysql but from Sequel Pro it says

Unable to connect to host 127.0.0.1, or the request timed out.
Be sure that the address is correct and that you have the necessary
  privileges, or try increasing the connection timeout (currently 10
  seconds).
MySQL said: Authentication plugin 'caching_sha2_password' cannot be
  loaded: dlopen(/usr/local/lib/plugin/caching_sha2_password.so, 2):
  image not found

can't figure out what I am missing

A: TL;DR: Sequel Pro is dead since 2016.  Don't downgrade your DB because of a tool. Move on to an alternative tool.
Update 2020: Sequel Pro is officially dead but unofficially alive!  You can find the "nightly" builds that don't have this issue (i.e. support Mysql 8 auth) in here: https://sequelpro.com/test-builds
Update 2021: Sequel Ace is a good similar alive alternative: https://github.com/Sequel-Ace/Sequel-Ace#installation (Credits to Maciej Kwas's answer)

All the other solutions here are recommending changing your DB settings (making it less secure, as advertised by MySQL) for the tool you are using.  That's not acceptable to me.
I have always been a huge fan of Sequel Pro, even donated to it.  But, with all my passion and love, I am sorry if the tool doesn't have any release since 2016.  YOLO, and I need to move on!
The alternative I found (from https://stackoverflow.com/a/55235533/2321594, thanks to @arcseldon) is DBeaver which supports MySQL 8's new authentication (non-legacy) method.
PS. The only trick in the tool side, not the DB side is when you are creating a MySQL 8 connection you might need to go to "Driver Properties" (later can be found in Edit Connection) and turn the value of allowPublicKeyRetrieval to true.
I needed this to connect to my MySQL container created using Docker.  To have the IP of MySQL be visible to the outside, for any other application in your ecosystem (not just this tool), you should either create a new user in MySQL, or pass -e MYSQL_ROOT_HOST=% in the run-time or as an ENV.

A: If you connect to MySQL via root@127.0.0.1, make sure that you reset its password too!
ALTER USER 'root'@'127.0.0.1' IDENTIFIED WITH mysql_native_password BY '[password]';

A: It's working for me. if you are getting this error :

Unable to connect to host 127.0.0.1, or the request timed out.
Be sure that the address is correct and that you have the necessary
privileges, or try increasing the connection timeout (currently 10
seconds).
MySQL said: Authentication plugin 'caching_sha2_password' cannot be
loaded: dlopen(/usr/local/lib/plugin/caching_sha2_password.so, 2):

Plz try this solution

A: This is because Sequel Pro is not ready yet for a new kind of user login, as the error states: there is no driver.
mysql + homebrew
Basically you will have to perform some actions manually, however- your database data won't be deleted like in solution below

*

*Go to my.cnf file and in section [mysqld] add line:
default-authentication-plugin=mysql_native_password

*Login to mysql server from terminal: run mysql -u root -p, then inside shell execute this command (replacing [password] with your actual password):
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '[password]';

*exit from mysql shell with exit and run brew services restart mysql.
Should work.
Quick fix (destructive method)
Quick fix for non-homebrew installs:
Apple Logo > System Preferences > MySQL > Initialize Database, then type your new password and select 'Use legacy password'
After restart you should be able to connect. Do it only on fresh installs, because you may lost your db tables otherwise.

my.cnf
The my.cnf file is located in /etc/my.cnf on Unix/Linux

Alternatives
For those who is still struggling with Sequel Pro problems: Sequel Pro was a great product, but with tons of unresolved issues and last release being dated to 2016 perhaps it's a good idea to look for some alternatives. There is a fork of SequelPro called SequelAce that seems to be pretty stable and up-to-date, it keeps similar functionality, similar look and feel, yet at the same time it is devoid of old Sequel Pro problems

A: *

*Assuming you don't have a mysql configuration, echo the following to ~/.my.conf
[mysqld]
default-authentication-plugin=mysql_native_password

*Sign into mysql with mysql -u root -p

*Set the root user password with ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '[PASSWORD]'; where [PASSWORD] is a password of your choosing.

*Restart mysql with e.g. brew services restart mysql

A: If anyone facing this issue and installed MySQL version > 8 through .dmg file; downloaded it from the official link. In that case please use this guideline. I am adding the same details below in case the link will not be available in the future.
This issue is because you're using the new Strong Password Encryption which is a new feature in MySQL 8, if you installed MySQL 8 using the .dmg file, you can go to System Preferences > MySQL and then click on Initialize Database type your password and select the second option Use Legacy Password Encryption.

A: Sequel Pro is officially dead and no longer supports newer MySql features. However, the good news is that it was replaced by Sequel Ace which is available on GitHub and App store. The app is free of charge and looks like official replacement for Sequel Pro as the post was made by one of the collaborators of Sequel Pro.
Ps. I decided to post this as an answer as others have not mentioned that there is now an up-to-date replacement for Sequel Pro


text: Q: Веб сервер на python Хочу сделать некий веб ресурс, который будет иметь простейшее API, с ответом в виде json. В ответе должны прилетать данные из базы данных. Собственно в чем моя проблема: данные в базе данных должны обновляться. То-есть...Сервер должен работать и отвечать на запросы клиентов, но при этом, постоянно должен мониторить другие ресурсы и парсить с них информацию, которую собственно и будет сохранять в БД. Я не совсем понимаю, что для создания такого ресурса нужно использовать, и может ли сервер выполнять какие-то фоновые задачи по парсингу и "общаться" с клиентами ОДНОВРЕМЕННО?


text:
Q: ffmpeg split makes long file when not starting from beginning Attempting to use ffmpeg to split a very long mp4.
ffmpeg -ss 00:00:00 -t 00:30:00 -i WorkingSession.mp4 -acodec copy -vcodec copy  WorkingSessionPart1.mp4

This provides about 89MB
Next I try this, notice the intentional time overlap
ffmpeg -ss 00:29:00 -t 00:30:00 -i WorkingSession.mp4 -acodec copy -vcodec copy  WorkingSessionPart2.mp4

This provides about 163MB even though it should just be the last minute of the previous half hour mp4
The clue I get is at the start, of the 2nd one I get:
[mp4 @ 0xf48fc0] Codec for stream 0 does not use global headers but container format requires global headers
[mp4 @ 0xf48fc0] Codec for stream 1 does not use global headers but container format requires global headers

How do I bypass this, so as to split my mp4.
I have tried both -flags global_header, and -shortest:
ffmpeg -flags global_header -ss 00:29:00 -t 00:30:00 -i WorkingSession.mp4 -acodec copy -vcodec copy -shortest WorkingSessionPart2.mp4

but I still get the same error, and the much too long mp4 output file
Any suggestions?


text:
Q: How to display comments from a JSON server using javascript and HTML? I am making this website project where people can leave comments and the webpage will dynamically display the comments without reloading the page. My comments are stored in an array in my server in the format  Allcomments=[ { username: 'username', info: 'title', commentinfo: 'commentinfo ' }]. I am currently receiving this error when I try and run my code Uncaught (in promise) ReferenceError: res is not defined at main.js:53 at async loadComments (main.js:50) and the comments are not displaying as a result. I am also confused on how to implement the function so that it updates with new comments without needing a page reload.
Any help or tips would be greatly appreciated! This is my code:
index.html

comments !

client.js
async function GetComments () {
  let info = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json'
    },
  };
  await fetch('http://127.0.0.1:8090/comments', info)
    .then((res) => { return res.json(); })
    .then(data => {
      document.getElementById('commentsSection').innerHTML;
    }).then(() => {
      const comments = JSON.stringify(res);
      for (let comment of comments) {
        const y = `

${comment.name}

${comment.info}

comment: ${comment.comment}

      `;
        document.getElementById('commentsSection').innerHTML =
          document.getElementById('commentsSection').innerHTML + y;
      }
    });
}

GetComments();

server.js

const app = express();
const port = 8090;
const express = require('express')
const bodyParser = require('body-parser');
const cors = require('cors');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

let Allcomments=[];

app.get('/comments', (req, res) => {
    res.json(Allcomments);
});

A: You are using res in a .then block, but you didn't pass it in from the earlier then block:
.then((res) => { return res.json(); }) // res is defined within this block only
.then(data => {
  document.getElementById('commentsSection').innerHTML;
.then(() => {
  const comments = JSON.stringify(res); // <- ReferenceError: res is not defined

This should fix it:
await fetch('http://127.0.0.1:8090/comment', info)

  // extract data from response body:
  .then((response) => { return response.json(); })

  // response body is comments array
  .then(comments => {
    for (let comment of comments) {
      const y = `

${comment.name}

${comment.title}

comment: ${comment.usercomment}

      `;
      document.getElementById('commentsSection').innerHTML += y;
    }
  })

  // also add a catch block
  .catch(err => {
    console.error('error:', err)
  });

A: In your main.js file, remove the return keyword in the first then statement. After that, loop the data array and append the data into the HTML element.
async function GetComments () {
  let options = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json'
    },
  };
  await fetch('http://127.0.0.1:3000/comment', options)
    .then(res => res.json())
    .then(data => {
      for (let comment of data) {
        const x = `

${comment.name}

${comment.title}

comment: ${comment.usercomment}

      `;
        document.getElementById('commentsSection').innerHTML =
          document.getElementById('commentsSection').innerHTML + x;
      }
    });
}

GetComments();


text:
Q: Find the number of elements in the centre of this group. Let $G = \{e, x, x^2, x^3, y, xy, x^2y, x^3y\}$ with $O(x)=4, O(y)=2$,  and $xy=yx^3$. Then what is the number of elements in the centre of $G$?

A: Sketch answer:
From the relation you can check that each $x^iy$ does not commute with $x$.
Next you can check if $x,x^3$ commute with $y$. You can check that what is left is the center of $G$.


text:
Q: Proving in combinations ... is it true ? prove that :
 $$\sum_{k=0}^n \left ( \begin{array}{c}n\\k\end{array}\right )^2 = {2n \choose n}$$
I tried to prove it by supposing i have a class has (M) girls and n boys , and we need to choose  a team (K of students) ---- So the ways are
$$\displaystyle {m+n \choose k}$$----------
So I have (0) boy  and (k) girl OR 1 of n and (k-1) of m OR 2 of n and (k-2) of m OR ... (k) of n and (0) of m
SO:
$(^{m}_{0})(^n_k)+(^m_1)(^{n}_{k-1})+(^{m}_{2})(^{n}_{k-2})+...(^{m}_{k})(^{n}_{0})$
THEN
$$ \
\sum_{i=0}^k{m \choose i}{n \choose k-i}\ $$
$$ \
\sum_{i=0}^k{m \choose i}{n \choose k-i} ={n+m \choose k}\ $$
suppose m=n=k (is it true to suppose this ? )
$$ \
\sum_{i=0}^n{n \choose i}{n \choose n-i} ={2n \choose n}\ $$
i+(n-i)=2n
the below = the top
what should i do ??
Can i prove it by Mathematical induction ?

A: Imagine we want to solve this question. "We have $2n$ objects that we want to chose $n$ of them. How many states exist?"
The first thing we can think of is this:  $\binom{2n}{n}$
But we can solve it in another way. We can divide these objects into two parts each consisted of $n$ objects. Now we pick $k$ objects from the first group and the rest $n - k$ from the second group. So we will have $\binom{n}{k} * \binom{n}{n-k}$ possibilities. This equation is the equivalent to:
$\binom{n}{k} * \binom{n}{n - k} = \binom{n}{k} * \binom{n}{k} = \binom{n}{k}^2$
But we have to calculate these possibilities for all $k$. It is obvious that $k$ is between $0$ and $n$. So the answer will be:
$\sum_{k=0}^{n}{\binom{n}{k}}^2$
So we have two solutions for the same problem. Since this question has only one answer, these solutions must be equal. So:
$\sum_{k=0}^{n}{\binom{n}{k}}^2 = \binom{2n}{n}$

A: Another approach :
The coefficient of $x^n$ in the product : $$(1+x)^n(x+1)^n$$
Is equal to the sum : $\displaystyle \left ( \begin{array}{c}n\\0\end{array}\right )\left ( \begin{array}{c}n\\0\end{array}\right )+\left ( \begin{array}{c}n\\1\end{array}\right )\left ( \begin{array}{c}n\\1\end{array}\right )+ \dots=\sum_{k=0}^n \left ( \begin{array}{c}n\\k\end{array}\right )^2 $
Since this product is equal to : $(1+x)^{2n}$, coefficient of $x^n$ must be same.
From here we get coefficient of $x^n$ as $\displaystyle{2n \choose n}$.
Hence : $$\sum_{k=0}^n \left ( \begin{array}{c}n\\k\end{array}\right )^2 = {2n \choose n}$$


text:
Q: Invalid color value ?android:colorControlNormal I have a drawable resource file like this:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
    <path
        android:fillColor="?android:colorControlNormal"
        android:pathData="M9,11L7,11v2h2v-2zM13,11h-2v2h2v-2zM17,11h-2v2h2v-2zM19,4h-1L18,2h-2v2L8,4L8,2L6,2v2L5,4c-1.11,0 -1.99,0.9 -1.99,2L3,20c0,1.1 0.89,2 2,2h14c1.1,0 2,-0.9 2,-2L21,6c0,-1.1 -0.9,-2 -2,-2zM19,20L5,20L5,9h14v11z"
        tools:targetApi="lollipop" />
</vector>

On Gradle Build, Error is as follows:
Invalid color value ?android:colorControlNormal
at com.android.ide.common.resources.MergedResourceWriter$FileGenerationWorkAction.run

What I tried:  I changed it to ?attr/colorControlNormal, but still same error
I am stuck at this. Can somebody help?

A: ?attr/colorControlNormal works for me. As I could see from your code you have tools:targetApi="lollipop" which means your minSdk is lower than API 21. Vector drawables are supported down to API 21. Before that Gradle generates PNGs for that vector drawables. By using theme attributes like ?attr/colorControlNormal means your drawable color could vary depending on the theme of its context. Therefore gradle could not generate PNGs for it as it doesn't know about the context.
The solution for this is either update the minSdk version to be atleast 21 or use a static color or static color reference. For example: android:fillColor="@color/someColor or android:fillColor="#FF00FF00"

A: If you have updated the Gradle Plugin to the latest version, restore it to 3.6.1 as It seems this is working till version '3.6.1'.


text:
Q: Pass array as value of annotation param in JavaPoet Using JavaPoet I'm trying to annotate a class with an annotation which has an array as a parameter value i.e.
@MyCustom(param = { Bar.class, Another.class })
class Foo {
}

I use AnnotationSpec.builder and its addMember() method:
List<TypeMirror> moduleTypes = new ArrayList<>(map.keySet());
AnnotationSpec annotationSpec = AnnotationSpec.builder(MyCustom.class)
   .addMember("param", "{ $T[] } ", moduleTypes.toArray() )
   .build();
builder.addAnnotation(annotationSpec);

A: CodeBlock has a joining collector, and you can use that to stream this, doing something like the following (if for instance this was an enum).  You can do it for any types, just the map would change.
AnnotationSpec.builder(MyCustom.class)
   .addMember(
      "param",
      "$L",
      moduleTypes.stream()
         .map(type -> CodeBlock.of("$T.$L", MyCustom.class, type))
         .collect(CodeBlock.joining(",", "{", "}")))
   .build()

A: Maybe not an optimal solution but passing an array to an annotation in JavaPoet can be done in the following way:
List<TypeMirror> moduleTypes = new ArrayList<>(map.keySet());
CodeBlock.Builder codeBuilder  = CodeBlock.builder();
boolean arrayStart = true;
codeBuilder.add("{ ");
for (TypeMirror modType: moduleTypes)
    if (!arrayStart)
        codeBuilder.add(" , ");
    arrayStart = false;
    codeBuilder.add("$T.class", modType);
codeBuilder.add(" }");

AnnotationSpec annotationSpec = AnnotationSpec.builder(MyCustom.class)
    .addMember("param", codeBuilder.build() )
    .build();
builder.addAnnotation(annotationSpec);


text: Q: Mail Merge from Http Request use a restful API In my project, I have a document in word and I need to use mail merge to fill the fields of the documents.  My problem is that my database is online on my domain and I can´t access these records from Word.  Can anyone help me?


text:
Q: How can I restart Firefox from the command-line? How can I restart Firefox from the command-line and restore the previous state completely (or as much as possible) after restart? Sure, I can do something like killall firefox; firefox, but that would not restore the session.

A: You can set Firefox to open with the previously open windows & tabs. It should  be under Preferences -> General -> "When Firefox starts". Set that to "Show my windows and tabs from last time":

You should now be able to restart firefox with killall firefox; firefox & and have the same session.

A: I think you need to do a setting in firefox before you restart it from command line. Go to:
   Prefrences->General->When Firefox starts

and select :
   Show my windows and tabs from last time

then from the command line , restart it the way you like ( may be killall firefox; firefox&) and you ll get the desired result.
For more advance tuning about session restore you can type about:config in address bar and search for session or restore to change it.
https://support.mozilla.org/en-US/questions/1089103#answer-794586

A: Unfortunately, there's no easy way to accomplish this.  The closest thing to it would actually be using the Firefox Console (Shift + F2) and typing in restart.

Aside from that, one could install an Addon or take @terdon's advice in his answer and change Firefox Preferences to "Show my windows and tabs from last time" When Firefox starts and "restarting" with
$ killall firefox; sleep 1; firefox &

UPDATE: The "gcli" was removed from firefox in 2018.  Therefore, the "Shift+F2" shortcut no longer works.

A: If you desire to restart Firefox with two or more profiles, this Bash script appears to work consistently:
#!/bin/bash
killall -s SIGTERM firefox; sleep 60
firefox -P "user" &
firefox -P "default settings" &

Replace the quoted profile names with your own (see about:profiles). Use the -foreground flag to control which windows appears on top, if desired.
As noted by the other answers, enable the 'open previous windows and tabs' setting in the preferences (about:preferences#general)
The value in sleep 60 (seconds) can potentially be lowered.

A: As of 2020, edit advanced settings via about:config, search for  resume and set the browser.sessionstore.resume_session_once flag to true, then exit.
Here's documentation on the flag:
https://kb.mozillazine.org/Browser.sessionstore.resume_session_once


text:
Q: Emails sent from exim4 to gmail appear as read Have an exim4 smtp server setup on debian jessie. When emails are sent to gmail domains, for some reason they do not appear as unread in gmail.
It puzzling as this will only happen for some accounts, specifically for a couple of daemons that are sending out emails on a regular basis.
I don't know if the problem lies within exim or gmail.

A: The read/unread status of a message is not carried by any SMTP header. And there is no concept of "message flags" in SMTP (I cant think of any...). Exim4 being an SMTP server only, I seriously doubt it had anything to do with the described behaviour. Gmail's rules are probably the motte obvious culprit.


text:
Q: C# BeginInvoke problem Why does i have this error and how to fix it. Thanks for help
Error   4   Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type
    void provider_GetAssignmentsComplete(object sender, QP_Truck_Model.Providers.GetAssignmentsEventArgs e) {
        lvMyAssignments.Dispatcher.BeginInvoke(() =>
        {
            lvMyAssignments.ItemsSource = e.HandOverDocs;
        });
    }

A: Cast it to a Delegate object, such as Action
lvMyAssignments.Dispatcher.BeginInvoke((Action)(() => lvMyAssignments.ItemsSource = e.HandOverDocs)));

A: Lambda expression are not implicitly convertible to delegates in certain cases. Specifically, if the method expects the type Delegate you have to first explicitly cast the lambda for the compiler to accept it.
What you can do is explicitly cast the lambda, which should allow you to use BeginInvoke:
lvMyAssignments.Dispatcher.BeginInvoke( (Action)(() =>
        {
            lvMyAssignments.ItemsSource = e.HandOverDocs;
        }));

Normally, if you have a method with a strongly-typed delegate signature, like:
public static void BeginInvoke( Action d ) { ... }

The compiler can convert a lambda expression to the appropriate delegate signature needed. But if the method is loosely typed:
public static void BeginInvoke( Delegate d ) { ... }

the compiler will not accept a lambda. You can, however, cast the lambda expression to a specific delegate signature (say Action), and then pass that to the method. The compiler cannot automatically do this for you, because there are many different delegate types that could be a valid match for the signature of the lambda ... and the compiler has no way of knowing which would be the right one.


text:
Q: Does HashMap keeps its order (not insertion order) Sorry if and answer to this is out there. I just could not find it.
I don't care about insertion order, I just want to ensure that HashMap keeps its order without any puts being used in between.
If I have the following code:
StringBuilder keyChecker = new StringBuilder("");
for(String field : hashmap().keySet()){
    keyChecker.append(field).append(",");
}

for(String field : hashmap().keySet()){
    setAny(checker,x++, hashmap().get(field) );
    x++;
}

Will the (1st,2nd,3rd,etc) field always match the same one next time I call HashMap keyset.
From my tests it seems like it always does, but I am not sure about any edge cases that I may come across.

A: Yes. It will keep its order if no new items are added. An idle map does not just decide to rearrange itself.  But that order is non deterministic and can change once items are added.

A: WJS is correct.  That said, it is very bad style to depend on this.  If you actually depend on the order of the entries, I would suggest using a TreeMap or one of the Apache Commons implementations of OrderedMap.
You might be able to get by with your assumption that the order will be stable right now ... but if another developer works on the code, that assumption might not be known and the code will break in unexpected ways that will be big headache for somebody to solve.
If you depend on entry order, use a data structure that guarantees that order.


text:
Q: How to Prove that $ cond(A)\ge \frac{||A||}{||C||} $ for any induced matrix norm. With $A$ invertible and $A+C$ singular matrix How could I prove that for any induced matrix norm
$$cond(A)\ge \frac{\|A\|}{\|C\|}$$
where $A$ is an invertible square matrix and $A+C$ is a singular matrix?

A: If $A$ is invertible and $A+C$ is singular then $\Vert A^{-1}C\Vert\ge1$.
Because if  $\Vert A^{-1}C\Vert<1$, then $I+ A^{-1}C$ would be invertible and
consequently $A+C=A(I+A^{-1}C)$ would also be invertible.
Now we have
$$\Vert A\Vert\leq \Vert A\Vert \Vert A^{-1}C\Vert\leq
\Vert A\Vert \Vert A^{-1}\Vert \Vert C\Vert=\text{cond}(A)\Vert C\Vert.$$
Done.$\qquad\square$


text:
Q: Find nearest div with class disableDiv and disable all of its contents In this code I am checking the chekbox with class disableDivCheckbox and the code is disabling all of the div content with class disableDiv. But if I apply this combination to another checkbox and another div, this is not working properly. So I want to find closest div with class disableDiv and disable only that div. I am using disabale * because I want to disbale div and its contents.
$(".disableDivCheckbox").click(function () {
            if ($(this).is(":checked")) {
               $('.disableDiv *').removeAttr("disabled");
            }
            else {
                $('.disableDiv *').val('').prop('checked', false).attr("disabled", "disabled");
            }
        });

fiddle : https://jsfiddle.net/8c0x1pho/

A: Try this,
$(".disableDivCheckbox").click(function () {
    if ($(this).is(":checked")) {
        $(this).closest('.disableDiv *').removeAttr("disabled");
    } else {
        $(this).closest('.disableDiv *').val('').prop('checked', false).attr("disabled", "disabled");
    }
});

This means that, you will disable all content of only that disableDiv class to which disableDivCheckbox belongs.
Give it a try, this will work.

A: You can try this approach:

*

*Get checked state and save it in a variable

*Navigate to all necessary elements using this. It will make your code more modular.

*Try not to use * selector. Use more specific selectors as this will specify element types you are manipulating and make your code more reusable.

*Instead of attr and removeAttr, you can just set value of disabled as true or false . You can just use !$(..).is(":checked")
Sample:

// Only call functions. DON'T declare any functions in ready.
$(document).ready(function() {
  // Have a common function.
  // If size grows, this can be exported to its own file
  registerEvents();

  // Initialise on load states.
  updateUIStates("#addBusinessObjectivesCheckbox")
});

function registerEvents() {
  $(".disableDivCheckbox").click(function() {
    updateUIStates(this)
  })
}

function updateUIStates(el) {
  var isNotChecked = !$(el).is(":checked");
  var inputs = $(el)
    .parents(".checkbox")
    .siblings(".disableDiv")
    .find('input');
  inputs.attr("disabled", isNotChecked)
  isNotChecked && inputs.val('').prop('checked', false)
}

<fieldset id="AddBusinessObjectivesFieldset" class="">
  <legend>
    Add business objectives
  </legend>

      <input type="checkbox" value="addBusinessObjectivesCheckbox" name="addBusinessObjectivesCheckbox" class="disableDivCheckbox" id="addBusinessObjectivesCheckbox"> Add business objectives

                <input type="radio" name="AddBusinessObjectives" id="" value="0" class=""> Fixed N

                <input type="radio" name="AddBusinessObjectives" id="" value="1" class=""> Random upto N

              <input type="text" placeholder="Enter N" id="indexTextboxAddBusinessObjectives" name="indexTextboxAddBusinessObjectives" style="width:70px" class="" />

</fieldset>

Pointers

*

*$(document).ready() is more like init function. Try to call functions instead of defining in it. This will make easier to understand as it will depict a flow.

*Use pure functions and call then. Like onChange, you can call few functions: updateUIStates(), postDataToServer(), processResponse(), otherTodos(). This may look like overkill but in long run this will help.

*Create a tree structure in your markup.

...

...

This will ease navigation part. No matter what structure you use, keep it standardised. This will keep your JS clean.


text:
Q: Redirecting (301) multiple urls with the same query string using .htaccess I wonder if anyone can help. I've researched this issue but not found a post that QUITE matches it so I'm a bit lost as to how to proceed.
I have a whole bunch of URLs from an old site that each use the same query string, which is used to redirect users to the mobile version of the pages. I would like to redirect these URLs to pages on the new site so that the new URLs don't display the query string.
So:
www.old-site.com/first-page/?type=88 should redirect to www.new-site.com/first-page;
www.old-site.com/second-page/?type=88 should redirect to www.new-site.com/second-page; and
www.old-site.com/third-page/?type=88 should redirect to www.new-site.com/third-page, etc.
I've tracked down code that will redirect one URL with a query string to another URL without a query string:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^type=88
RewriteRule (.*)$ http://www.new-site.com? [R=301,L,NC]

but, I am not sure how to deal with all these different pages that use the same query string, but each need to end up at different destinations.
Any help that anyone can provide would be most helpful.
With kind regards,
Mark

A: Try :
RewriteEngine On
RewriteCond %{QUERY_STRING} ^type=88
RewriteRule (.*)$ http://www.new-site.com%{REQUEST_URI}? [R=301,L,NC]


text:
Q: Regex to check if the user submitted price is really a valid price I'm trying to create a regex code to match a price with or without a dollar sign $, and with or without a comma or decimal point.
The following prices should be valid.
$1
$5.00
$.10
$.07
$03 //this should be interpreted as $0.03 in case if you are confused
$10,000
$10,000.00

1
5.00
.10
.07
03 //this should be interpreted as $0.03 in case if you are confused
10,000
10,000.00

Here is my code so far:
preg_match('/^([1-9][0-9]*|0)(\.[0-9]{2})?$/', $price)

A: How do you like this?
preg_match(
    '/^' .
    '\$?' . // optional dollar sign
    '[\d]*' . // any digits (0 or not does not make a difference, 03 is valid as well as .03 or 0.03)
    '(,\d{3})*?' . // a comma has to be followed by 3 digits to be valid
    '(.\d\d)?' . // the point has to be followed by 2 digits to be valid
    '$/', // the end
    $price
);

You have to adapt this, if you wanna force a comma after every three digits. However there are good regex if you google "regex float" (like http://www.regular-expressions.info/floatingpoint.html)
I am not sure why the "03" or "$03" is important. If you want to verify the string, okay. If you just want to convert it to a float, I would keep it simple, stupid:
$price = str_replace(['$', ','], '', $str);
    if ('0' === $price[0]) {
        $price = '.' . $price;
    }
    $price = (float) $price;

A: You can use this regex -
^\$?(?:(?:\d+(?:,\d+)?(?:\.\d+)?)|(?:\.\d+))$

Here's a demo, which also explains it.
Note that I've added 03 and .03 as separate entries. This regex will just match them.

A: I quickly spun up a function for checking if a string or int is a valid price and if not, converting it. The final output is always going to be a string with two digits after the decimal, like 1000.00.
It removes minus/negative signs, commas, spaces, and dollar signs. The only except is when if the string contains any characters like letters that would set is_numeric() to false.
Here is the function:
function convertToValidPrice($price) {
    $price = str_replace(['-', ',', '$', ' '], '', $price);
    if(!is_numeric($price)) {
        $price = null;
    } else {
        if(strpos($price, '.') !== false) {
            $dollarExplode = explode('.', $price);
            $dollar = $dollarExplode[0];
            $cents = $dollarExplode[1];
            if(strlen($cents) === 0) {
                $cents = '00';
            } elseif(strlen($cents) === 1) {
                $cents = $cents.'0';
            } elseif(strlen($cents) > 2) {
                $cents = substr($cents, 0, 2);
            }
            $price = $dollar.'.'.$cents;
        } else {
            $cents = '00';
            $price = $price.'.'.$cents;
        }
    }

    return $price;
}

And here is to test it:
var_dump(convertToValidPrice('100'));          // 100.00
var_dump(convertToValidPrice('-100'));         // 100.00
var_dump(convertToValidPrice(100));            // 100.00
var_dump(convertToValidPrice('$100'));         // 100.00
var_dump(convertToValidPrice('100.98'));       // 100.98
var_dump(convertToValidPrice('100.9'));        // 100.90
var_dump(convertToValidPrice('100.'));         // 100.00
var_dump(convertToValidPrice('1,00.98'));      // 100.98
var_dump(convertToValidPrice('1,000.98'));     // 1000.98
var_dump(convertToValidPrice('100.98829382')); // 100.98
var_dump(convertToValidPrice('abc'));          // null


text:
Q: Get current line in boost spirit grammar I am trying to get the current line of the file I am parsing using boost spirit. I created a grammar class and my structures to parse my commands into. I would also like to keep track of which line the command was found on and parse that into my structures as well. I have wrapped my istream file iterator in a multi_pass iterator and then wrapped that in a boost::spirit::classic::position_iterator2. In my rules of my grammar how would I get the current position of the iterator or is this not possible?
Update: It is similar to that problem but I just need to be able to keep a count of all the lines processed. I don't need to do all of the extra buffering that was done in the solution.

A:
Update: It is similar to that problem but I just need to be able to keep a count of all the lines processed. I don't need to do all of the extra buffering that was done in the solution.

Keeping a count of all lines processed is not nearly the same as "getting the current line".
Simple Take
If this is what you need, just check it after the parse:
Live On Wandbox
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/support_line_pos_iterator.hpp>
#include <fstream>
#include <set>
namespace qi = boost::spirit::qi;

int main() {
    using It = boost::spirit::istream_iterator;

    std::ifstream ifs("main.cpp");
    boost::spirit::line_pos_iterator<It> f(It(ifs >> std::noskipws)), l;

    std::set<std::string> words;
    if (qi::phrase_parse(f, l, *qi::lexeme[+qi::graph], qi::space, words)) {
        std::cout << "Parsed " << words.size() << " words";
        if (!words.empty())
            std::cout << " (from '" << *words.begin() << "' to '" << *words.rbegin() << "')";
        std::cout << "\nLast line processed: " << boost::spirit::get_line(f) << "\n";
    }
}

Prints
Parsed 50 words (from '"' to '}')
Last line processed: 22

Slightly More Complex Take
If you say "no, wait, I really did want to get the current line /while parsing/". The real full monty is here:

*

*boost::spirit access position iterator from semantic actions
Here's the completely trimmed down version using iter_pos:
Live On Wandbox
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/support_line_pos_iterator.hpp>
#include <boost/spirit/repository/include/qi_iter_pos.hpp>
#include <boost/fusion/adapted/std_pair.hpp>
#include <fstream>
#include <map>

namespace qi = boost::spirit::qi;
namespace qr = boost::spirit::repository::qi;

using LineNum = size_t;

struct line_number_f {
    template <typename It> LineNum operator()(It it) const { return get_line(it); }
};

static boost::phoenix::function<line_number_f> line_number_;

int main() {
    using Underlying = boost::spirit::istream_iterator;
    using It = boost::spirit::line_pos_iterator<Underlying>;
    qi::rule<It, LineNum()> line_no = qr::iter_pos [ qi::_val = line_number_(qi::_1) ];

    std::ifstream ifs("main.cpp");
    It f(Underlying{ifs >> std::noskipws}), l;

    std::multimap<LineNum, std::string> words;

    if (qi::phrase_parse(f, l, +(line_no >> qi::lexeme[+qi::graph]), qi::space, words)) {
        std::cout << "Parsed " << words.size() << " words.\n";

        if (!words.empty()) {
            auto& first = *words.begin();
            std::cout << "First word: '" << first.second << "' (in line " << first.first << ")\n";
            auto& last = *words.rbegin();
            std::cout << "Last word: '" << last.second << "' (in line " << last.first << ")\n";
        }

        std::cout << "Line 20 contains:\n";
        auto p = words.equal_range(20);
        for (auto it = p.first; it != p.second; ++it)
            std::cout << " - '" << it->second << "'\n";

    }
}

Printing:
Parsed 166 words.
First word: '#include' (in line 1)
Last word: '}' (in line 46)
Line 20 contains:
 - 'int'
 - 'main()'
 - '{'