text:
Q: Can I read a striped volume (2 HDDs) encrypted with VeraCrypt from another OS or after "PC reset"? So I created a striped volume from 2 hard drives of the same size & type from within a VeraCrypt encrypted system (Windows 10) and encrypted it with VeraCrypt therafter. Now this VeraCrypt encrypted system drive doesn't boot anymore even after perma-decrypting it and I'm not sure if I get it working again.
-> can I read/mount the encrypted striped volume from another OS than the one I created it in?
And also I'd like to try "Reset this PC" from the Windows 10 repair options. Will I still be able to read the striped volume afterwards?

A: Its difficult to comment for certain without more knowledge of your specific setup, but in general -
* It would be a bad idea to "Reset this PC" if you want to recover data from the drives in the computer.

*

*If you have a striped volume, you will need both disks to get the data off it.  Depending on how the striping was done, you may be able to use another OS, but this is not likely (using a newer or older version of the OS stands a much better chance then trying to use Linux for example.

You should look at the disk as a number of layers.   You have 2 physical disks each with partitions.  You then have combined the partitions into a single block device (volume) which you then encrypted.    If you can use your original OS to see the volume, you could then bit copy that volume onto a partition - even if its encrypted - and mount/open it in another OS which can recognise that partition with Veracrypt.

A: So when I connected the disks to another PC where they show up as "Dynamic Foreign" in disk management with the option to "Import Foreign Disks".
However it worked after I reset my PC with which I set up the striped volume. For this I first perma-decrypted my system volume encrypted with VeraCrypt using the rescue USB stick.
I could still not reset my PC at first but I executed a few statements (such as chkdsk; Google it) in the repair console after which it worked.
It also still worked after I formatted my system drive and reinstalled Windows 10 64Bit to it.


text:
Q: insert if not exist , using auto incremental primary keys. mvc3 i have a problem with auto incremental primary keys..
when im adding a student to my database, i can add the same student over and over again because the primary key of student is auto incremental so it is, of course, never repeated, i need to verify that the  SSN of the student does not already exist in the database before inserting.
how can i do that on mvc3?? (im totally new in .net and mvc3)
my code for create in the student controller is:
[HttpPost]
    public ActionResult Create(Alumno alumno)
    {
        try
        {
            using (var db = new administracionEntities())
            {
                db.Alumno.Add(alumno);
                db.SaveChanges();
            }
            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

A: before you insert check if input alumno.ssn doesnot exist like
db.Alumno.where(a=> a.ssn == alumno.ssn).Any()

if this returns true, then there exists a ssn in database.
There are different ways in which you can achieve this in MVC.In one of which, You can have this call in a separate call to controller than in Create Action. May be you can check if duplicate SSN exists through JQuery.Ajax call on SSN textbox blur event on client side.
$.ajax({
   type: "Get",
   url: "StudentController/DoesSSNExist",
   data: "ssn=#",
   success: function(msg){
       if(msg)
        alert('ssn already exists');
   }

This is controller action
public bool DoesSSNExist(string ssn)
{
    return db.Alumno.where(a=> a.ssn == ssn).Any()
}

A: In my model Class
public class Student {
    public int StudentID { get; set; }
    [Remote("UsernameChecker", "Student")]
    public string Username { get; set; }
}

In my Controller
public virtual JsonResult UsernameChecker(string Username){
    bool checkuser = db.Student.Any(i => i.Username == Username);
    return checkuser
        ? Json("Username already exists", JsonRequestBehavior.AllowGet)
        : Json(true, JsonRequestBehavior.AllowGet);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exponential of a matrix does order matter? If I have two matrices $A$ and $B$ then I know that $AB$ is not necessarily equal to $BA$. However if I have $exp(tA)exp(tB)$ can I switch them round then? Is $exp(tA)exp(tB) = exp(tB)exp(tA)$? The Taylor expansion suggests not, but I can't find the answer explicitly on google. Thanks for any help.

A: Well no, in general. You can observe this, as you said, with a Taylor series.
You know that the matrix exponential can be expressed in the Taylor series definition for the exponential, but only when you can compute all the even and odd orders of the matrix you have. Otherwise you cannot. But suppose we can, then we would have
$$e^{t\mathbb{A}} = \mathbb{1} + t\mathbb{A} + \frac{t}{2}\mathbb{A}^2 + \ldots$$
$$e^{t\mathbb{B}} = \mathbb{1} + t\mathbb{B} + \frac{t}{2}\mathbb{B}^2 + \ldots$$
Hence
$$e^{t\mathbb{A}}e^{t\mathbb{B}} = \left( \mathbb{1} + t\mathbb{A} + \frac{t}{2}\mathbb{A}^2\right)\cdot \left(\mathbb{1} + t\mathbb{B} + \frac{t}{2}\mathbb{B}^2\right) = \mathbb{1} + t(\mathbb{B} + \mathbb{A}) + \frac{t}{2}(\mathbb{B}^2 + \mathbb{A}^2) + \frac{t^2}{4}(4\mathbb{A}\mathbb{B} + 2\mathbb{A}\mathbb{B}^2 + 2\mathbb{A}^2\mathbb{B} + \mathbb{A}^2\mathbb{B}^2)$$
You can easily see that the reversed operation $e^{t\mathbb{B}}e^{t\mathbb{A}}$ would change the order of the matrix products, and you know that in general
$$\mathbb{A}\mathbb{B} \neq \mathbb{B}\mathbb{A}$$
hence yes, order does matter.


text:
Q: Typescript falls back to the default value of generic type for no reason Sorry if the title is not very obvious. I don't know what is the problem so I couldn't come up with a good question. This is a simplified version of the problem that I'm struggling with:
type Key = unknown[];

type Option<TKey extends Key> = {
  key: TKey;
  updateKey: (v: TKey) => TKey;
};

type Getter = <Value>(v: Value) => Value

function createConfigWithOption<TKey extends Key>(
  getOptions: ((g: Getter) => Option<TKey>)
) {
}

createConfigWithOption receives a function whose first parameter is a getter function (doesn't matter what it does) and returns an option object. The option object has a key key and an updateKey function. The input and output of updateKey should be inferred from the key.
It works correctly if I don't use the getter:
createConfigWithOption(() => ({
  key: ["1"],
  updateKey: (currentKey) => {
    const a = currentKey[0];
    //    ^? const a: string

    return [];
  },
}));

But it falls back to the default value of Key when I use the getter:
createConfigWithOption((get) => ({
  key: ["1"],
  updateKey: (currentKey) => {
    const a = currentKey[0];
    //    ^? const a: unknown

    return [];
  },
}));

Here is a Typescript playground if you want to try it out yourself.
I've been scratching my head for several hours to understand what's going on but didn't find an answer.

A: See microsoft/TypeScript#47599 for an authoritative description of this issue.
TypeScript's type inference algorithm isn't perfect by any means; it's effectively a collection of heuristic rules that works well over a wide range of use cases, but there are unfortunately situations where it fails to infer something that a human developer would see as obvious.  One place where things can go awry is if the compiler needs to infer generic type arguments at the same time it needs to contextually infer callback parameter types.
The difference between
createConfigWithOption(() => ({
  key: ["1"],
  updateKey: (currentKey) => {
    const a = currentKey[0];
    //    ^? const a: string

    return [];
  },
}));

and
createConfigWithOption((get) => ({
  key: ["1"],
  updateKey: (currentKey) => {
    const a = currentKey[0];
    //    ^? const a: unknown

    return [];
  },
}));

is that in the latter, the callback passed to createConfigWithOption has a callback parameter get whose type the compiler wants to infer for you.  That makes the whole callback function context sensitive.  Generally speaking, if the compiler doesn't know the parameter type of a function, it can't know the types of what's going on inside the function either.  The current algorithm tends to delay context sensitive inferences until after generic type arguments are inferred.  But this is a problem, since leaving the callback as a black box means that the compiler has no idea what to infer for the E generic type parameter, so it falls back to the constraint, after which get is inferred properly... but it's too late, since E is wider than you want.
Note that in this particular instance, it turns out that get is not used anywhere inside the function body, so in fact nothing actually depends on its type.  But the compiler doesn't do much of an inspection into the function body to check for that sort of thing.  So using (get)=> like that messes up inference for you.

So that's what's going on.  There have been recent improvements in this sort of circular contextual-and-generic inference, as described in microsoft/TypeScript#48538, but they can't address every possible situation, and your code is one of those places that still doesn't work as you want.
The workarounds here are either to leave it out entirely like ()=> as in your first example, or to explicitly annotate it with its type so the compiler doesn't have to infer it:
createConfigWithOption((get: Getter) => ({
  key: ["1"],
  updateKey: (currentKey) => {
    const a = currentKey[0];
    //    ^? const a: string

    return [];
  },
}));

Playground link to code


text:
Q: Copy file only after all directories are copied I have a folder A. It contains another folders data and opt, which contains many folders and files. And a complete.txt file, which denotes all files in data and opt are correct.
I need to copy folder A completely. But the complete.txt file should copy only after all other files and folders are copied.
Is there any linux command to do this.

A: Using rsync you can easily achieve it. But It takes two steps
$rsync -av --progress sourcefolder destinationfolder --exclude filetoexclude
$rsync -av --progress sourcefolder destinationfolder

When you use rsync with exclude option, it will exclude the particular file
and when you use it next time without exclude it will only copy the excluded file.


text:
Q: Convert image to png byte array in Matlab I would like to take a 512x512 image and convert it into a png byte array in Matlab so that I can stream it via a socket.
At the moment I take the array, write it to a png file using imwrite(I,'file.png'), then read it as a binary file and send it through the socket. This is obviously horribly inefficient because I first write to disk and then read from disk. I want to skip the and write to disk.
Is there anyway to do this in Matlab?

A: Probably not directly using the base MATLAB toolbox since the PNG file itself is created by the PNGWRITEC MEX-function. However, there may be some Java classes that can help, such as those in the javax.imageio package.


text:
Q: Create user in ubuntu docker instead using root I am creating a custom docker image based on ubuntu (testing:latest). I want to run some unit tests for a meteor application.
FROM ubuntu:16.04
RUN apt-get update -y && \
    apt-get install -yqq --no-install-recommends apt-transport-https ca-certificates curl nodejs-legacy && \
    apt-get clean && apt-get autoclean && apt-get autoremove && \
    curl https://install.meteor.com/ | sh && \
    meteor npm install eslint eslint-plugin-react && \
    apt-get remove -y apt-transport-https ca-certificates curl && \
    rm -rf /var/lib/apt/lists/*

I am using gitlab CI using a docker runner. So my yml file looks like
stages:
  - test

lint:
  image: testing:latest
  stage: test
  script:
    - /node_modules/.bin/eslint --ext .js --ext .jsx .
  except:
    - master

unit:
  image: testing:latest
  stage: test
  script:
    - whoami
    - meteor test --driver-package=practicalmeteor:mocha-console-runner
  except:
    - master

Running whoami shows me that the current user is root. Therefore meteor test is not running, as it shouldn't be used with root
You are attempting to run Meteor as the 'root' superuser. If you are
developing, this is almost certainly *not* what you want to do and will likely
result in incorrect file permissions. However, if you are running this command
in a build process (CI, etc.), or you are absolutely sure you know what you are
doing, set the METEOR_ALLOW_SUPERUSER environment variable or pass
--allow-superuser to proceed.

Even with METEOR_ALLOW_SUPERUSER or --allow-superuser, permissions in your app
directory will be incorrect if you ever attempt to perform any Meteor tasks as
a normal user. If you need to fix your permissions, run the following command
from the root of your project:

  sudo chown -Rh <username> .meteor/local

How can I use another user? Do I have to do that in the dockerfile? Or do I have to add some commands in the yml file?

A: You can do it the normal Ubuntu way RUN useradd <username> then USER <username> and run the task.
From the Docker.Io Docs

The USER instruction sets the user name or UID to use when running the image and for any RUN, CMD and ENTRYPOINT instructions that follow it in the Dockerfile.

You can also look at this SO Answer: Switching users inside Docker image to a non-root user


text:
Q: How to work with Inequalities in an Induction Proof Prove the following by induction:
(n+1)! > $2^{n+3}$ for all $n\geq5$
My proof:
For all $n\geq5$ in the natural numbers,
A(n) = (n+1)! > $2^{n+3}$ for all $n\geq5$
Step 1: Initialization
A(5) = (5+1)! > $2^{5+3}$
A(5) = 6! > $2^8$. -- true
Step 2: Assume A(n) is true.
A(n) = (n+1)! > $2^{n+3}$
Step 3: The induction step: A(n) $\Rightarrow$ A(n+1)
A(n+1) = (n+2)! > $2^{n+4}$
n $\cdot$ (n+1) $\cdot$ (n+2) > $2^{n+4}$
here's where I get lost in the sauce
(n+1)! - $2^{n+3}$$\cdot$ (n+2) > $2^{n+4}$ ????
Please help me get to the end of this proof! Much appreciated! I also appreciate any links or resources that would help me understand whats happenes to inequalities in this case.


text:
Q: Magento2.3.4 - No such entity with customerId I imported all my Customers from my Old Magento store.
But now, when a Customer try to log in in my new store with a wrong password, they can see this error:

Can someone tell me how I can fix it please?
Many thanks


text:
Q: value stored during initialization is never read I am trying parse the google api so that I can retrieve the address and its data.
 I get two errors that are on the commented lines. Why am I getting these errors.
 I allocated the dit so I should have to release it correct.
Here is my code to retrieve the data
  NSURL *url=[NSURL URLWithString:str];
    NSData *data=[[NSData alloc]initWithContentsOfURL:url];
    NSString *str1=[[[NSString alloc]initWithData:data  encoding:NSUTF8StringEncoding]autorelease];
    NSDictionary *dit=[[[NSDictionary alloc]init]autorelease];//value stored to dit during initialization is never read
    dit=[str1 JSONValue];
    NSArray *dit1=(NSArray *) [dit objectForKey:@"results"];
    NSDictionary *dit3=[[dit1 objectAtIndex:0]objectForKey:@"geometry"];
    NSDictionary *dit4=[dit3 objectForKey:@"bounds"];
    NSDictionary *northeast=[dit4 objectForKey:@"northeast"];
    NSDictionary *lt=[northeast objectForKey:@"lat"];
    NSDictionary *southwest=[dit4 objectForKey:@"southwest"];
    NSDictionary *lng=[southwest objectForKey:@"lng"];

A: Probably the issue is this:
NSDictionary *dit=[[[NSDictionary alloc]init]autorelease];
dit=[str1 JSONValue];

You create an empty dictionary, then never use it but instead overwrite the value with the one returned from JSONValue. This code should be:
NSDictionary *dit=[str1 JSONValue];


text:
Q: How can I add a static 'Main' method suitable for an entry point? I am getting an error on my code that says "Error   CS5001
Program does not contain a static 'Main' method suitable for an entry point"
I am coding in C# using Microsoft Visual Studio and .NET. This is my code.
    using System.IO;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using System;

class projectsummer
{
    [CommandMethod("OpenDrawing", CommandFlags.Session)]

    public static void OpenDrawing()

    {
        string strFileName = "C:\\DRAFT.dwg";
        DocumentCollection acDocMgr = Application.DocumentManager;

        if (File.Exists(strFileName))
        {
            acDocMgr.Open(strFileName, false);
        }
        else
        {
            acDocMgr.MdiActiveDocument.Editor.WriteMessage("File " + strFileName +
                                                            " does not exist.");
        }
    }
}

I am not sure how to go about this error. Thank you!

A: Looking at this post and your previous question, let's try and break down what's going on.

*

*You created a new Console application in Visual Studio. You did not tick "Do not use top level statements". This gave you a Program.cs file that was essentially empty (there was no "Main" method visible).

*You erased the Hello World code given to you, and went to make a static method - the code from your previous question.

*Damien_The_Unbeliever commented that based on the error, you put your method inside a "top level statement" file, and to put your method inside a class.

*You wrap your method (which is still inside Program.cs) in a class, and now suddenly you get a Can't Find Entry Point error.

User Ryan Pattillo posted a great explanation of the original issue - where your method was "by itself" in the Program.cs file. You should follow their advice, but you should also ensure that this class is in its own file.
You should end up with this:
Program.cs
// this is the entire contents of the file
using ConsoleApp1;

ProjectSummer.OpenDrawing();

ProjectSummer.cs
using System.IO;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using System;

namespace ConsoleApp1
{
    public class ProjectSummer
    {
        [CommandMethod("OpenDrawing", CommandFlags.Session)]
        public static void OpenDrawing()
        {
            // ...
        }
    }
}

Change ConsoleApp1 to the name of your project.
The entry point of your application, which right now is the only file that has "top level statements", remains Program.cs, thus you fix the Can't Find Entry Point error.

Another adjustment you can make, which seeing you're new to C# might be useful, is to not use top level statements at all. Modify your Program.cs to this:
namespace ConsoleApp1
{
    internal static class Program
    {
        // this is your program's entry point
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
            ProjectSummer.OpenDrawing();
        }
    }
}

Change ConsoleApp1 to the name of your project.

A: You cannot use the AutoCAD .NET API out of process. To be able to use the AutoCAD .NET libraries, you have to build a "class library" project (DLL) and NETLOAD this DLL from a running AutoCAD process. See this topic about in-process vs out-of-process and you can start from this other one to see how to create an AutoCAD .NET project.


text:
Q: custom script to log in as a regular user on local machine but remotely ssh as root Good day all, i am not sure if this is the right question to ask. I am a newbie . Pls do anyone have an idea of a possible custom bash script that can be use to login over ssh into a remote server but will automatically sudo to root on the remote server without having to input a password. i am task to find a way to run same operation over multiple servers but i can not log in as root by default
command will be of the form below where script.sh will be some sort of ssh wrapper script. i have looked at possible ssh documentation but no luck.
user1@localmachine~:script.sh server_name
root@remotemachine~#:
Addition: to be more specific, how can i bypass the two password prompt by running command ssh -t $SERVER "sudo su"
i can observe i got prompted the first time to authenticate to $SERVER and the second password prompt to authenticate the "sudo su"
i will like to play around any suggestion provided in my personal lab to weigh in on the potential risk


text:
Q: Why does a magnetic field raise the ground state energy of an electrical particle? I heard a statement that the ground state energy of a electrical particle in a magnetic field is larger than its ground state energy without the magnetic field.
I just heard this statement. This statement shows an energy shift by a magnetic field. This energy shift is different from Zeeman splitting.
Maybe I have some mistakes when I quote this statement. And I don't know why the ground state energy is different. I guess it has a quantum origin.
If you have heard a similar conclusion, could you tell me the more details? Mathematics and proofs are much better.

A:
I heard a statement that the ground state energy of a electrical particle in a magnetic field is larger than its ground state energy without the magnetic field.

This can be understood in terms of classical theory of particle in a magnetic field. Consider particle circling in a magnetic field. Any slow increase of the magnetic field will be accompanied by eddy-like electrical field, which will act on the charged particle in such a way so that the adiabatic invariant $E/\omega$ will be conserved; here $E$ is kinetic energy and $\omega$ is angular frequency of the circular motion of the particle. Since $\omega$ is proportional to $B$, increasing $B$ increases $\omega$ and since the ratio $E/\omega$ remains constant, kinetic energy $E$ increases too. The energy increase is the work of the eddy-like electric field accompanying the changing magnetic field.

A: There are different factors that modify the ground state energy. The principals are fine and hyperfine structure (http://en.wikipedia.org/wiki/Fine_structure)
(http://en.wikipedia.org/wiki/Hyperfine_structure).


text:
Q: How do you use search to create a table with list.js? I am trying to create a form that, when submitted, lists all available flights within the users' specifications by using Listjs. I don't know what is going wrong, but when I try to manually add something to the list, nothing happens.
HTML:

            Flight
            Departing
            Arriving
            Dur.
            Aircraft
            CAT
            Operating
            Carrier

I'm not 100% sure if it is relevant, but I also get this script error from the list.min.js file Uncaught TypeError: Cannot read property 'cloneNode' of null.
Javascript:

A: You cannot use a "tr" as the template according to the docs

◦item String, default: undefined  ID to item template element or a
  string of HTML (notice: does not work with
)

Here is the link to the docs with this verbiage - http://listjs.com/docs/options
This should work though. Update your tbody to this and leave out the template in your options


text:
Q: How to update UNICODE version in TOMCAT8 I'm using Emojis in a web application, for test I'm using jetty 8.1.8 and work it very well, however I put my webapp in tomcat 8 and not work it, I read about this and find it is because my version of UNICODE is not update, my question is How can I update it?
Thanks.

A: You can add URI Encoding property to your connector.
In your Tomcat distribution's conf/server.xml file, find the connector definition for your HTTP protocol and add at the end of the connector URIEncoding="UTF-8" like so.
<Connector port="8080" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="UTF-8"/>

Alternatively you can set encoding via system property -Dfile.encoding=utf-8

A: The Unicode version does not depend on the Tomcat version, but on the Java version. Do you use the same Java version for both Jetty and Tomcat?
And where in the code and how do you access the Unicode information? Maybe it helps to implement that part using IBM's icu4j, which can be updated independently of the Java version.

A: The problem is the  pageEncoding UTF-8. I had to use other encoding in my jsp only when I use the emoji, the encoding that work for me is ISO-8859-8.


text:
Q: GLM with scores/principal dimensions from MCA I hope someone can help me understand how to run this analysis!
I have a dataset with many categorical variables (i.e. color, pattern, texture) associated to each animal in each interaction between pairs of animals (a set of categorical variables for each interaction of each animal in each pair).
I want to test the effect of each variable on animal contest outcome (binomial).
My sample size is really small compared to the number of variables/predictors (n = 10 pairs composed by 5 animals in total).
So, I would like to perform a "Multiple Correspondence analysis" (MCA) to reduce the dimensionality and select only the most relevant predictor variables to input in a Generalised Linear Mixed Effect Model (GLMM). This would also allow me to avoid including in the same GLMM model predictors with high collinearity, is that correct?
I read that you can input the scores from a PCA into a GLM with Factoextra.
Can you do the same with the scores from a MCA? Could I simply input the scores from the dimensions in the MCA into a GLMM model with lma4:glmer R function?
This would be the model with the original variables:
glmer(outcome ~ body color + texture + pattern +
                (1|individual_ID) + (1|pair_ID),
                family=binomial(link="logit"), dataset)

How would the model with the MCA scores look like?
If I input the MCA scores in the GLMM model, can I still know which original variable (i.e. color) is the strongest predictor of contest outcome?
I haven't found much information on how to run a GLMM with MCA scores, so any help including tutorial links or examples that you could recommend would be highly appreciated!

A: Using the factors obtained in the MCA as predictors in GLM/GLMM is valid, especially considering your specific case (need for dimension reduction and multicolinearity reduction).
The interpretation of the coefficients will be the difficult part. I would try two approaches:

*

*Having a good understanding and labelling of each factor, and interpreting the coefficients only in relative terms: "The augmentation of this factor is associated with a decrease (or increase) in my output".

*Using model predictions and marginal effects. The idea is to have an observation used as a scenario, using the function predict.MCA from factoMineR to get is coordinates on the new factors and then predicting your outcome with the predict function and your GLM/GLMM. You can then do the same thing but with a new observation for which you change only one characteristic (scenario 2). You can then interpret the change between the two predictions. But keep in mind that it is not exactly "everything hold equal" because changing that characteristic will affect the other factors.

A last suggestion would be to think about your process (input data --> MCA --> GLMM --> result) as a global model. With a little bit of effort, you could use the functions from DALEX and analyze your whole model with tools used in machine learning.


text:
Q: Semantic UI dropdowns: prevent onchange event from firing when selected option is changed programmatically When you change selected value of a dropdown with a change event handler programmatically in standard HTML, that event is not fired.  For example, if I do:
document.getElementById("my_select").value = "foo";

the onchange event handler of the dropdown is not executed (it only responds to user-initiated events).
I am converting all dropdowns in my code to Semantic UI (which is a great library, BTW).  However, the problem is that now the onchange event fires regardless of whether the change was initiated by user interaction or by some JS function.
So, when I do this:
$('#my_select').dropdown('set selected', 'foo');

the onchange event is fired.
Here is the fiddle that shows both behaviors:
FIDDLE
So, my questions are:

*

*Is there another way (other than "set selected") to select one of the options in a dropdown that will not fire onchange event?

*If not, is there a way to prevent the event from firing?

Thanks!

A: To get the behaviour you desire you need to trick the system into thinking you've already selected the option you wish you select.

$(document).ready(function() {
 $('.ui.dropdown').dropdown();

 $('#change_button').click( function() {
    //set the value to the value you want
  $('#semantic_select')[0].value='3';
    //now use the semantic ui function
  $('#semantic_select').dropdown('set selected', '3');

 });
});
<link href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css" rel="stylesheet"/>

<select id="semantic_select" class="ui dropdown" onchange="alert('Semantic Changed')">
 <option value=""></option>
 <option value="1">One</option>
 <option value="2">Two</option>
 <option value="3">Three</option>
</select>
<input id="change_button" type="button" value="Change" />

By setting the value, then calling the dropdown function the system thinks you've already selected the value you're setting, so the change event doesn't fire.

A: To avoid the problem I would split it in two parts :
A part for the setValue behaviour :
$('#semantic_select').dropdown('set value', 3)

And a part for the setText behaviour :
$('#semantic_select').dropdown('set text', 'three')

So that this will both update text and value.

A: This change for fomantic-ui resolves the problem:
https://github.com/fomantic/Fomantic-UI/pull/1683.
Just set 'preventChangeTrigger' parameter to true for the 'set selected' behavior.


text:
Q: Fetching external api with cypress I would like to fetch an email from an email provider and i know that  i could use axios or any other http client however since i added cypress can i just use cy.request to get data and store it or it should not be used for such purposes.
I can use axios as it shows here but why if i have cy.request
context('Verify email', () => {
    let inbox;
    before((done) => {
      // Configure timeout
      this.timeout(1000*60*5); // five minutes
      // Query the inbox
      axios.get(`${ENDPOINT}&tag=${TAG}&timestamp_from=${startTimestamp}&livequery=true`).then((response) => {
        inbox = response.data;
        done();
      }).catch((err) => {
        done(err);
      });
    });

A: You could store the response in a Cypress environment variable.
context('Verify email', () => {
  before(() => {
    cy.request(`${ENDPOINT}}&tag=${TAG}&timestamp_from=${startTimestamp}&livequery=true`)
      .then((response) => {
        Cypress.env('inbox', response.body);
    });
  });

  it('test', () => {
    // reference the variable by Cypress.env('inbox')
  });
});


text:
Q: Encounter TypeError: cannot pickle 'generator' object when doing model fitting for my siamese network I'm trying to do the model fitting for a siamese network. Here is my generator:
def gen(list_tuples, person_to_images_map, batch_size=16):
  ppl = list(person_to_images_map.keys())
  while True:
    batch_tuples = sample(list_tuples, batch_size // 2)
    labels = [1] * len(batch_tuples)
    while len(batch_tuples) < batch_size:
        p1 = choice(ppl)
        p2 = choice(ppl)

        if p1 != p2 and (p1, p2) not in list_tuples and (p2, p1) not in list_tuples:
            batch_tuples.append((p1, p2))
            labels.append(0)

    for x in batch_tuples:
        if not len(person_to_images_map[x[0]]):
            print(x[0])

    X1 = [choice(person_to_images_map[x[0]]) for x in batch_tuples]
    X1 = np.array([read_img(x) for x in X1])

    X2 = [choice(person_to_images_map[x[1]]) for x in batch_tuples]
    X2 = np.array([read_img(x) for x in X2])

    yield [X1, X2], np.array(labels)

I fit the model using:
model.fit(gen(train, train_person_to_images_map, batch_size=16), use_multiprocessing=True,
                validation_data=gen(val, val_person_to_images_map, batch_size=16), epochs=100, verbose=1,
                workers=4, callbacks=callbacks_list, steps_per_epoch=200, validation_steps=100)

It gives my type error after two minutes but the jupyter notebook cell shows it's still running. I feed a size-10 data to it and it stuck in Epoch1/100 for two hours.

Epoch 1/100
Exception in thread Thread-14:
Traceback (most recent call last):
.
.
.
TypeError: cannot pickle 'generator' object
Should I keep waiting or is there any mistakes in my code?

A: use_multiprocessing=True won't work with generator input if your generator takes unpickable arguments (e.g. other generators) as arguments.
You could either just set use_multiprocessing=False (at expense of some performance probably) or make sure that you don't have unpickable arguments (from the code you've provided it's hard to say what list_tuples and person_to_images_map are).
Reference: https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit


text:
Q: Finding series solution of xy'' + y = 0 I do not know how to format equations on here, so here is a picture of my attempt:
Why is it that when trying to find the coefficients about the indicial root r=0 leads to undefined coefficients? The textbook claims both roots r = 1 and 0 have the same series solution? Unfortunately the textbook does not show the derivation.

A: So you get the first equations
$$
0=r(r-1)c_0\\
-c_0=(r+1)rc_1\\
-c_1=(r+2)(r+1)c_2
$$
etc. In the case $r=0$ the second equation tells you that $c_0=0$ and $c_1$ is arbitrary and determines the other coefficients,
$$
y_0(x)=c_1(x-\frac12x^2\pm\dots).
$$
 In the case $r=1$ you get a solution based on $c_0$, but now with additional factor $x=x^r$ so that
$$
y_1(x)=c_0x(1-\frac12x+\frac1{12}x^2\mp\dots)
$$
which in the end is the same solution. You get the second basis solution by order reduction, set $y_2(x)=u(x)y_0(x)$ where $c_1=1$ with the equation
$$
0=x(u''y_0+2u'y_0')\implies u'(x)=y_0(x)^{-2}=x^{-2}\left(1 + x + \frac{7}{12}x^2 + \frac{19}{72}x^3 + \frac{149}{1440}x^4 + \dots\right)
\\
\implies u(x)=-\frac1x+\ln(x)+\frac{7}{12}x + \frac{19}{144}x^2 + \frac{149}{4320}x^3 + \dots
$$
which gives the solution that is singular in $x=0$.


text:
Q: How do I permanently delete a .sys driver file (and stop it from coming back) on Windows 11 I'm having an issue with something (also linked to this question) involving drivers on Windows 11. Basically, to cut a long story short, a .sys driver file is causing a BSOD on boot but every time I delete the .sys file in the C:/Windows/System32/drivers folder, it'll then reinstall itself when reboot and then BSOD.
The only way I can bypass this is by going in Safe Mode, which then it works fine.
The driver name is igdkmd64.sys.
How do I permanently delete the .sys file and stop it from reinstalling? I have tried deleting the thing using the driver in Device Manager but it keeps coming back. Also, I have tried disabling driver auto-install (Settings > System > About > Advanced device settings) but that didn't help.


text:
Q: Getting Data from API (ok 200 Response Undefined Method 'id') I got the below to work and call up membership data based on current_user.id (See 200 Ok response) this shows up in my logs.
GET https://api-e1.authrocket.com/v1/memberships?user_id=usr_0vKhXTr0K1bz6kUipKNnjD
-> 200 (103.4 ms)
NoMethodError (undefined method `id' for #<NCore::Collection:0x007f50c82a7e50>):app/controllers/directory/categories_controller.rb:13:in `index'

I was using current_user.id which worked.
@directory_category.user_id = current_user.id

Trying to change it so it grabs the user's membership.id
@directory_category.user_id = membership_info.id

The full create statement I'm working with.
# Create
def create
    @directory_category = Directory::Category.new(directory_category_params)
    @directory_category.user_id = membership_info.id
    if @directory_category.save
        redirect_to directory_categories_path, notice: 'Category was successfully created.'
        else
            render :new
    end
end

    # Directory Category Index
    def index
        @directory_categories = Directory::Category.where(user_id: membership_info.id)
    end

My attempt, which does say 200 ok getting current_user id and putting it at the end AuthRocket::Membership.all statement like below:
def current_user
    @_current_user ||= AuthRocket::Session.from_token(session[:ar_token]).try(:user)
end

def membership_info
    AuthRocket::Membership.all user_id: current_user.id
end

https://authrocket.com/docs/api/memberships

A: It looks like your
def membership_info
    AuthRocket::Membership.all user_id: current_user.id
end

method is actually returning a collection and not a single item.  if you change it to
def membership_info
    AuthRocket::Membership.all(user_id: current_user.id).first
end

or whichever record you actually want, you should stop this error from raising.


text:
Q: Display heart rate via ClockKit complication? I'm developing a watchOS app for tracking the heart rate, and it's working well.
Is it possible to display the computed heart rate value on a complication using ClockKit?

A: Is it possible?  Yes.
Is it feasible?  Not really.
Apple chose to provide a Heart Rate Glance instead of a complication, since complications aren't meant to be updated that frequently, and certainly not often enough to display an accurate heart rate throughout the day.
Apple restricts scheduled complication updates to once every 10 minutes, so your displayed heart rate data would often be stale.  While you could manually update your complication more frequently than that, you'll likely run into two issues:

*

*Exhausting your complication daily time budget
If you update your complication too often, and exhaust your daily budget, no further updates will occur for the remainder of the day. From the CLKComplicationDataSource Protocol Reference:

Do not ask the system to update your complication within minutes. Instead, provide data to last for many hours or for an entire day. If your budget is exhausted, the next scheduled update does not occur until after your budget is replenished.

*Draining your watch battery
Frequent complication updates can drain the watch battery before the day is over.


text:
Q: Need help installing LAPACK/BLAS for CVXOPT (or a recommendation for another QP solver that's easier to install) I've been trying to install CVXOPT, which requires LAPACK/BLAS and to be honest it's killing me!
Context:
I am experimenting with an SVM and so need a QP solver. CVXOPT seems to be the best. The problem is the LAPACK/BLAS (or ATLAS) dependency.
I've tried installing ATLAS, which I thought worked, but when trying the CVXOPT install I still got "cannot find -lblas" and "cannot find -llapack".
So for the last 2 days I've been trying to follow the various methods on http://icl.cs.utk.edu/lapack-for-windows/lapack/#libraries_mingw to install LAPACK, but it's turning out to be the most ball crunchingly difficult installation I've ever had to preform, and I haven't even started trying to install BLAS yet.
The question:
Could someone either:
A) Point me to an English translation of the LAPACK/BLAS install guides. Or some sort of simple method of instillation if such a thing exists.
OR
B) Point me to a QP solver which doesn't require LAPACK/BLAS? So far I've not been able to find one that's any easier to install.
Thanks!

A: Ok so I finally got the damn thing working. Here is what I did, for any poor soul who has to install CVXOPT in the future:
For the most part follow the instructions at http://abel.ee.ucla.edu/cvxopt/install/index.html#building-cvxopt-for-windows but you also must:
1) Download gnuwin32 from http://gnuwin32.sourceforge.net/ in order to use 'sed' command.
2) Download and use use cygwin NOT cmd for running all commands. This is because 'sed' and 'make' commands don't work in cmd. Also when you are doing the cygwin install make sure you include the make command package which is under dev tools I think.
3) The following commands are slightly wrong:
sed 's/-mno-cygwin//g' -i'.bak' c:\Python27\Lib\distutils\cygwinccompiler.py
should be
sed 's/-mno-cygwin//g' -i'.bak' "c:\Python27\Lib\distutils\cygwinccompiler.py"
and
mv c:\Python27\Lib\distutils\cygwinccompiler.py.bak c:\Python27\Lib\distutils\cygwinccompiler.py
should be
mv "c:\Python27\Lib\distutils\cygwinccompiler.py.bak" "c:\Python27\Lib\distutils\cygwinccompiler.py"

A: To install on windows download the MLK numpy binary and cvxopt binary.
First install MLK numpy then install cvxopt binary.
See this page for a link to both of those binaries:
Problems on installing cvxopt
9 times out of 10 this should work. Otherwise yes you're stuck manually building. Congrats on figuring it out.

A: I followed the exactly Windows Tutorial of CVXOPT  but I was having the "cannot find -lblas" and "cannot find -llapack" issues too.
What solved for me was instead of writing
 BLAS_LIB_DIR = '.'

I wrote:
 BLAS_LIB_DIR = 'src'

And it worked. :)


text:
Q: Import files exists to project eclipse C++ Linux I am using eclipse to dev my application for linux. I have my library source  in workspace/mylib/ and the project in workspace/project.
In a source of my project i include the relative path of source library file,
example: #include "../mylib/foo.h"
The problem start when i try build it, in all parts that use library source eclipse shows this error: undefined reference to 'function()'
I think that it is by library files  don't have in src folder or not link.
Any Idea?
Thanks!

A: error: undefined reference to 'function()'

Indicates that the linker cannot find the definition of the function(). Either you have not defined it in your source code Or If you are using a library which defines it, the library is not getting linked.
This or this posts explain what you should do to add external libraries to eclipse.


text:
Q: Add() method adding duplicate rows for linked models in Code-First Entity Framework Following is the action that is adding a Loan request to the database:
[HttpPost]
public ActionResult Add(Models.ViewModels.Loans.LoanEditorViewModel loanEditorViewModel)
{
    if (!ModelState.IsValid)
        return View(loanEditorViewModel);

    var loanViewModel = loanEditorViewModel.LoanViewModel;

    loanViewModel.LoanProduct = LoanProductService.GetLoanProductById(loanViewModel.LoanProductId); // <-- don't want to add to this table in database
    loanViewModel.Borrower = BorrowerService.GetBorrowerById(loanViewModel.BorrowerId); //<-- don't want to add to this table in database

    Models.Loans.Loan loan = AutoMapper.Mapper.Map<Models.Loans.Loan>(loanEditorViewModel.LoanViewModel);
    loanService.AddNewLoan(loan);
    return RedirectToAction("Index");
}

Following is the AddNewLoan() method:
public int AddNewLoan(Models.Loans.Loan loan)
{
    loan.LoanStatus = Models.Loans.LoanStatus.PENDING;
    _LoanService.Insert(loan);

    return 0;
}

And here is the code for Insert()
public virtual void Insert(TEntity entity)
{
    if (entity == null)
        throw new ArgumentNullException(nameof(entity));

    try
    {
        entity.DateCreated = entity.DateUpdated = DateTime.Now;
        entity.CreatedBy = entity.UpdatedBy = GetCurrentUser();

        Entities.Add(entity);
        context.SaveChanges();
    }
    catch (DbUpdateException exception)
    {
        throw new Exception(GetFullErrorTextAndRollbackEntityChanges(exception), exception);
    }
}

It is adding one row successfully in Loans table but it is also adding rows to LoanProduct and Borrower table as I showed in first code comments.
I checked the possibility of multiple calls to this action and Insert method but they are called once.
UPDATE
I am facing similar problem but opposite in functioning problem here: Entity not updating using Code-First approach
I think these two have same reason of Change Tracking. But one is adding other is not updating.

A: The following code seems a bit odd:
var loanViewModel = loanEditorViewModel.LoanViewModel;

loanViewModel.LoanProduct = LoanProductService.GetLoanProductById(loanViewModel.LoanProductId); // <-- don't want to add to this table in database
loanViewModel.Borrower = BorrowerService.GetBorrowerById(loanViewModel.BorrowerId); //<-- don't want to add to this table in database

Models.Loans.Loan loan = AutoMapper.Mapper.Map<Models.Loans.Loan>(loanEditorViewModel.LoanViewModel);

You are setting entity references on the view model, then calling automapper.  ViewModels should not hold entity references, and automapper should effectively be ignoring any referenced entities and only map the entity structure being created. Automapper will be creating new instances based on the data being passed in.
Instead, something like this should work as expected:
// Assuming these will throw if not found? Otherwise assert that these were returned.
var loanProduct = LoanProductService.GetLoanProductById(loanViewModel.LoanProductId);
var borrower = BorrowerService.GetBorrowerById(loanViewModel.BorrowerId);

Models.Loans.Loan loan = AutoMapper.Mapper.Map<Models.Loans.Loan>(loanEditorViewModel.LoanViewModel);
loan.LoanProduct = loanProduct;
loan.Borrower = borrower;

Edit:
The next thing to check is that your Services are using the exact same DbContext reference. Are you using Dependency Injection with an IoC container such as Autofac or Unity? If so, make sure that the DbContext is set registered as Instance Per Request or similar lifetime scope.  If the Services effectively new up a new DbContext then the LoanService DbContext will not know about the instances of the Product and Borrower that were fetched by another service's DbContext.
If you are not using a DI library, then you should consider adding one. Otherwise you will need to update your services to accept a single DbContext with each call or leverage a Unit of Work pattern such as Mehdime's DbContextScope to facilitate the services resolving their DbContext from the Unit of Work.
For example to ensure the same DbContext:
using (var context = new MyDbContext())
{
    var loanProduct = LoanProductService.GetLoanProductById(context, loanViewModel.LoanProductId);
    var borrower = BorrowerService.GetBorrowerById(context, loanViewModel.BorrowerId);

    Models.Loans.Loan loan = AutoMapper.Mapper.Map<Models.Loans.Loan>(loanEditorViewModel.LoanViewModel);
    loan.LoanProduct = loanProduct;
    loan.Borrower = borrower;

    LoanService.AddNewLoan(context, loan);
}

If you are sure that the services are all provided the same DbContext instance, then there may be something odd happening in your Entities.Add() method.  Honestly your solution looks to have far too much abstraction around something as simple as a CRUD create and association operation. This looks like a case of premature code optimization for DRY without starting with the simplest solution. The code can more simply just scope a DbContext, fetch the applicable entities, create the new instance, associate, add to the DbSet, and SaveChanges. There's no benefit to abstracting out calls for rudimentary operations such as fetching a reference by ID.
public ActionResult Add(Models.ViewModels.Loans.LoanEditorViewModel loanEditorViewModel)
{
    if (!ModelState.IsValid)
        return View(loanEditorViewModel);

    var loanViewModel = loanEditorViewModel.LoanViewModel;
    using (var context = new AppContext())
    {
       var loanProduct = context.LoanProducts.Single(x => x.LoanProductId ==
loanViewModel.LoanProductId);
       var borrower = context.Borrowers.Single(x => x.BorrowerId == loanViewModel.BorrowerId);
       var loan = AutoMapper.Mapper.Map<Loan>(loanEditorViewModel.LoanViewModel);
       loan.LoanProduct = loanProduct;
       loan.Borrower = borrower;
       context.SaveChanges();
    }
    return RedirectToAction("Index");
}

Sprinkle with some exception handling and it's done and dusted. No layered service abstractions. From there you can aim to make the action test-able by using an IoC container like Autofac to manage the Context and/or introducing a repository/service layer /w UoW pattern. The above would serve as a minimum viable solution for the action. Any abstraction etc. should be applied afterwards. Sketch out with pencil before cracking out the oils. :)
Using Mehdime's DbContextScope it would look like:
public ActionResult Add(Models.ViewModels.Loans.LoanEditorViewModel loanEditorViewModel)
{
    if (!ModelState.IsValid)
        return View(loanEditorViewModel);

    var loanViewModel = loanEditorViewModel.LoanViewModel;
    using (var contextScope = ContextScopeFactory.Create())
    {
       var loanProduct = LoanRepository.GetLoanProductById( loanViewModel.LoanProductId).Single();
       var borrower = LoanRepository.GetBorrowerById(loanViewModel.BorrowerId);
       var loan = LoanRepository.CreateLoan(loanViewModel, loanProduct, borrower).Single();
       contextScope.SaveChanges();
    }
    return RedirectToAction("Index");
}

In my case I leverage a repository pattern that uses the DbContextScopeLocator to resolve it's ContextScope to get a DbContext. The Repo manages fetching data and ensuring that the creation of entities are given all required data necessary to create a complete and valid entity. I opt for a repository-per-controller rather than something like a generic pattern or repository/service per entity because IMO this better manages the Single Responsibility Principle given the code only has one reason to change (It serves the controller, not shared between many controllers with potentially different concerns). Unit tests can mock out the repository to serve expected data state. Repo get methods return IQueryable so that the consumer logic can determine how it wants to consume the data.

A: Finally with the help of the link shared by @GertArnold Duplicate DataType is being created on every Product Creation
Since all my models inherit a BaseModel class, I modified my Insert method like this:
public virtual void Insert(TEntity entity, params BaseModel[] unchangedModels)
{
    if (entity == null)
        throw new ArgumentNullException(nameof(entity));

    try
    {
        entity.DateCreated = entity.DateUpdated = DateTime.Now;
        entity.CreatedBy = entity.UpdatedBy = GetCurrentUser();

        Entities.Add(entity);

        if (unchangedModels != null)
        {
            foreach (var model in unchangedModels)
            {
                _context.Entry(model).State = EntityState.Unchanged;
            }
        }

        _context.SaveChanges();
    }
    catch (DbUpdateException exception)
    {
        throw new Exception(GetFullErrorTextAndRollbackEntityChanges(exception), exception);
    }
}

And called it like this:
_LoanService.Insert(loan, loan.LoanProduct, loan.Borrower);

A: By far the simplest way to tackle this is to add the two primitive foreign key properties to the Loan class, i.e. LoanProductId and BorrowerId. For example like this (I obviously have to guess the types of LoanProduct and Borrower):
public int LoanProductId { get; set; }
[ForeignKey("LoanProductId")]
public Product LoanProduct { get; set; }

public int BorrowerId { get; set; }
[ForeignKey("BorrowerId")]
public User Borrower { get; set; }

Without the primitive FK properties you have so-called independent associations that can only be set by assigning objects of which the state must be managed carefully. Adding the FK properties turns it into foreign key associations that are must easier to set. AutoMapper will simply set these properties when the names match and you're done.

A: Check Models.Loans.Loan?Is it a joined model of Loans table , LoanProduct and Borrower table.
You have to add
Loans  lentity = new Loans()
lentity.property=value;
Entities.Add(lentity );

var lentity = new Loans  { FirstName = "William", LastName = "Shakespeare" };
context.Add<Loans  >(lentity );
context.SaveChanges();


text:
Q: How to both constrain an Array and signal protocol implementation You indicate that an extension implements a protocol using the syntax:
extension Array : MyProtocol

You can constrain an Array extension using the syntax:
extension Array where Element:MyProtocol

I have a situation where I want to indicate that MyProtocol is implemented for Arrays only where Element implements MyProtocol, so I tried:
extension Array where Element:MyProtocol : MyProtocol {
}

which gives a horribly obscure error message
Statement cannot begin with a closure expression

and:
extension Array : MyProtocol where Element:MyProtocol {
}

here the error message is somewhat clearer:
Extension of type 'Array' with constraints cannot have an inheritance clause

How can I implement a protocol on an array only if the elements also implement the protocol?  The last error message seems to indicate that I'm SOL.  Thoughts or suggestions?


text:
Q: Cryptography friends: How to prove that a hash function can produces a length-fixed output? Consider the following hash function based on RSA. $M_i < n$. The hash value of a message consisting of two blocks is calculated by
$H(M) = H(M_1,M_2) = ((M_1^e\ mod\ n)\ XOR\ M_2)^e mod\ n$
Q1.Does this hash function can produce fixed output size?
My answer: Because any output is limited to the modulus(n), the hash function can produce fixed output size?(I think of it for a long time, but I still wonder about it)
Q2.Is the hash function easy to calculate?
My answer: Because the hash function just contain encryption and XOR operations, it is easy to calculate.(Is it right or completed?)

A: It's a weird chaining mode of RSA, and the output can be seen as a string of the length equal to that of $n$, as we output a number modulo $n$. So yes to Q1, provided you output a fully padded string.
It's not easy to calculate, but that's a bit subjective. The cost is two RSA operations essentially (xor is very cheap on computers) and those are relatively expensive compared to real hash functions (like SHA256 or SHA3 and many others). It's easily doable, but relatively expensive.
It's very insecure though.


text:
Q: Ansible datetime timezone conversion Is there a way to convert ansible date into a different timezone in a "debug" statement in my playbook ? I dont want a global timezone setting at the playbook level. I have this :
  debug:
   msg: "{{ '%Y-%m-%d %H:%M:%S' | strftime(ansible_date_time.epoch) }}"

This works fine but displays time in UTC. I need the time to be displayed in EDT without setting timezone at the global playbook level. How do I accomplish this  ?

A: If you use a command task to run date rather than relying on the ansible_date_time variable, you can set the timezone via an environment variable. E.g. the following playbook:
- hosts: localhost
  vars:
    ansible_python_interpreter: /usr/bin/python
  tasks:
    - command: "date '+%Y-%m-%d %H:%M:%S'"
      register: date_utc
      environment:
        TZ: UTC

    - command: "date '+%Y-%m-%d %H:%M:%S'"
      register: date_us_eastern
      environment:
        TZ: US/Eastern

    - debug:
        msg:
          - "{{ date_utc.stdout }}"
          - "{{ date_us_eastern.stdout }}"

Results in this output:

PLAY [localhost] *****************************************************************************

TASK [Gathering Facts] ***********************************************************************
ok: [localhost]

TASK [command] *******************************************************************************
changed: [localhost]

TASK [command] *******************************************************************************
changed: [localhost]

TASK [debug] *********************************************************************************
ok: [localhost] => {
    "msg": [
        "2020-05-12 15:21:05",
        "2020-05-12 11:21:06"
    ]
}

PLAY RECAP ***********************************************************************************
localhost                  : ok=4    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0


text:
Q: MPMediaPickerController missing search functionality on the iPad When setting up an MPMediaPickerController with the same code the search functionality works on the iPhone but not on the iPad. There's a search box in the picker on iPhone, but not on iPad.
Is there a way to enable this functionality on the iPad?

A: I filed a bug report about this (ID: 12157125) back in August nothing has come from it yet, so no there is no way to enable this functionality. However, you could remake the picker from the ground up using a combination of a UITableView and some MPMediaQueries, leaving you free to add your own search functionality.


text: Q: Is it true that the PDE $x^2u_{t}+uu_{x}=0$ is non-linear and homogeneous? I just want to check if this is  true, my rationale being that, by calling the LHS $F$, the $uu_{x}$ term ensures that $\lambda F(t,x,u,u_t,u_x)\neq F(t,x,\lambda u,\lambda u_t,\lambda u_x)$ (so non-linear), and since the zero function solves the PDE then is homogeneous?


text:
Q: get mean of certain elements in a vector I have a vector X which is a 20x1 double. I would like to calculate the mean for the 4 elements X(7,1), X(8,1), X(10,1), and X(12,1). One way to do this is:
M=mean([X(7,1), X(8,1), X(10,1),X(12,1)])

However, typing out all the elements is very inefficient, especially if I want to find the mean for even more elements. Is there a quicker way to write this? This seems to be a very easy operation but I have not been able to find the answer. I would appreciate a solution a direction to a post elsewhere. Thank you.

A: mean(X([7,8,10,12],1))
You can request a subset of indices by indexing with a vector instead of a single number.


text:
Q: How to get the td element without using row number in protractor I have the existing method like below,
getSpecificCell: function(tableObject, rowNumber, columnCss) {
  var ele = element(by.repeater(tableObject).row(rowNumber)).element(by.css('[' + columnCss + ']'));
  return ele;
}

Is that possible to do the same using the row text instead of rowNumber?
Form the below html I need to get the column value without using the row number
HTML sample:

      Name

        <input name="item-checkbox" ng-click="toggleSelectAll(a)" type="checkbox">

ROW2

      <input name="item-checkbox" ng-click="checkFunction()" type="checkbox">

        test.name

      <input name="item-checkbox" ng-click="checkFunction()" type="checkbox">

        test.data

        <input name="item-checkbox" ng-click="toggleSelectAll(a)" type="checkbox">

ROW1

      <input name="item-checkbox" ng-click="checkFunction()" type="checkbox">

        test.name

      <input name="item-checkbox" ng-click="checkFunction()" type="checkbox">

          test.data

A: You can use filter() method to filter the array of WebElement. have a look at below example,
getSpecificCell: function(tableObject, expectedRowValue, columnCss) {
   var ele =element.all(by.repeater(tableObject).filter(function(rowElement){
      return rowElement.element(by.css("td h4")).getText().then(function(rowValue){
        return rowValue == expectedRowValue;
      })
   }).first().element(by.css('[' + columnCss + ']'));

 return ele;
}


text:
Q: Replace first occurrence of ":" but not second in R In order to be able to process I'd like to replace the first occurrence of a : in a string (which is my marker, that a speech begins).
text <- c("Mr. Mark Francois (Rayleigh) (Con): If the scheme was so poorly targeted, why were the Government about to roll it out to employees in the Department of Trade and Industry and the Department for Work and Pensions on the very day the Treasury scrapped it? The CBI and the TUC have endorsed the scheme, which has helped 500,000 people and their families to improve their computer skills. When the Chancellor announced the original concession, he told the  Daily Record:", "Even at this eleventh hour, will the Government recognise that this is a poor decision, taken by an analogue Chancellor who is stuck in the past and reversing?", "Dawn Primarolo: The hon. Gentleman answers his own question, as the US does not have similar schemes. He is right to address the question of how we give people in the greatest need access to computer technology, but the Low Pay Commission\u0092s 2005 report showed that that was not happening under the scheme. Why should the Government spend £200 million on a poorly targeted scheme? It was being abused and was not delivering, so the Government have refocused to ensure that the objective is achieved.")

I am able to find the position of the first : using
lapply(gregexpr("\\:", text), head, 1)

[[1]]
[1] 35

[[2]]
[1] -1

[[3]]
[1] 15

However, I am unable to replace it in text (say, for example, with a |).

A: You can also use str_replace from stringr package.
text1 <- c("ABC:DEF:", "SDF", "::ASW")
library(stringr)
str_replace(text1, ":", "|")
# [1] "ABC|DEF:" "SDF"      "|:ASW"

This replaces the first occurence of : with |.

A: We can use sub as it matches only the first occurrence of pattern : and then we replace that with |.
sub(':', '|', text)


text:
Q: Elasticsearch query for unique data count I'd like to query the elasticsearch to get the unique ip count by devices from a bucket?
The bucket data are in the following format
{
    "request_time": 1651545553544,
    "cp_code": "1179526",
    "client_ip": "190.122.XXX.189",
    "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
    "device": "Chrome",
    "stream_key": "ymty1j6r",
    "bytes": 1242,
    "country": "DO"
}

{
    "request_time": 1651545553653,
    "cp_code": "1179526",
    "client_ip": "190.122.XXX.189",
    "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
    "device": "Chrome",
    "stream_key": "ymty1j6r",
    "bytes": 2824933,
    "country": "DO"
}

{
    "request_time": 1651545545132,
    "cp_code": "1179526",
    "client_ip": "190.122.XXX.189",
    "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
    "device": "Chrome",
    "stream_key": "ymty1j6r",
    "bytes": 2821788,
    "country": "DO"
}
{
    "request_time": 1651545465646,
    "cp_code": "1179526",
    "client_ip": "89.187.XXX.161",
    "user_agent": "Xtream-Codes IPTV Panel Pro",
    "device": "Other",
    "stream_key": "ymty1j6r",
    "bytes": 2807496,
    "country": "US"
}

{
    "request_time": 1651545482284,
    "cp_code": "1179526",
    "client_ip": "89.187.XXX.161",
    "user_agent": "Xtream-Codes IPTV Panel Pro",
    "device": "Other",
    "stream_key": "ymty1j6r",
    "bytes": 2813754,
    "country": "US"
}

Which aggregation method should I use to get the result in the following format directly from elasticsearch?
device|unique_ip_count
chrome|50
firefox|10

Thank you very much

A: A simple terms bucket aggregation on the device field and a cardinality metric aggregation on the client_ip field:
{
  "size": 0,
  "aggs": {
    "devices": {
      "terms": {
        "field": "device",
        "size": 10
      },
      "aggs": {
        "unique_ips": {
          "cardinality": {
            "field": "client_ip"
          }
        }
      }
    }
  }
}


text:
Q: Large Bluetooth Mouse I'm currently using a Logitech MX Revolution. Unfortunately, it operates on the 2.4 GHz band which results in some horrible interferance with my wireless network.
I'm looking for recommendations wireless mice that work well in close proximity to a wireless network. As I also spend many hours with a mouse in hand, I'd much prefer a larger mouse, and the small to regular sized ones really start to cramp up my hand. Do any large Bluetooth mice exist?

A: I've come across the Wireless Laser Mouse 8000.


text:
Q: RavenDB modelling/indexing: address verification with reference data I'm using RavenDB 4.2.3 stable on Windows x64, trying to load an artificial document by id from another index.
I'm working on an ETL system, where a significant part of the work is address verification. I have reference data for valid addresses, comprised of country, state, zipcode, city/community, street and house number range (where applicable) plus additional info like LAT/LON, type of community and so on.
The typical input to be verified would be comprised of tens or hundreds of thousand address records (usually zipcode, community, street, house number), where about 30% would not match a record in reference data (after normalization, of course), because of misspellings, transpositions, etc.
Those I assume I would have to query for one by one using fuzzy queries, then either automatically correcting using predefined Levenshtein-Damerau distance or filtering out for manual correction (while supplying best matches along with them).
But what about the other 70% or so that do have a direct match in reference data? Those I don't want to query for, because network latency and so on even if exact queries are faster than fuzzy ones. I need an index for that.
Since I cannot query in an index definition, my idea is to build a collection from this reference data, using hashed values of (normalized) address parts to lookup (minus house number) and using said hash as part of the entity Id (or even using the address parts directly), storing normalized and canonical addresses; so I can then use LoadDocument() on this reference collection in an index on the addresses to be verified to test for a 100% verifiable address (LoadDocument() returns non null entity and house number is in range in returned reference address) and to filter out those I have to make slower queries for.
Does that sound to be a good solution given the requirements, or am I missing something here and there is a better, more RavenDB-ish way?
One thing I don't think is possible, is to build said reference collection as an output from a map/reduce index, since I can't control the Id generation; the Id is defined as a hash on the group by fields, but I don't have access to this hashing function in the index definition for the addresses to be verified in order to use its result as document Id parameter for LoadDocument().
I found an issue for a feature controlling artificial document Id generation, but it is not done yet:
https://issues.hibernatingrhinos.com/issue/RavenDB-12932

A: The easiest way to handle that is to do something like:
var code = sha256( (u.Zip + u.Community + u.Street + u.HouseNumber).ToLower() );
You get a bunch of records and send their codes to the database, then see what you already have.It is better to do that in batches (calling: Load(IEnumerable ) to avoid call per item.
Because you have 70% / 30% new / existing rate, you can also use a bloom filter on the hashes, and likely save a lot of database queries because you'll know that the value isn't there (although if you find it, you'll need to check if this is the right one)
I'm not sure what the index / LoadDocument is related here. I would only go that route if you need to do more complex searches.Unfortunately, you probably do need to do things like: "First Av" vs "1st Avenue", etc, no?


text:
Q: como puedo llamar a esta funcion? Hola necesitaria ayuda con esto, la verdad es que soy bastante novato en programacion y no se muy bien como usar las funcionas asi que agradeceria una ayuda!

var Discord = require('discord.js');
var client = new Discord.Client();

client.on("ready", () => {
 console.log("Online");
});

client.on("message", async message => {

let prefix = "!"
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();

if(command === "start") {
     var embed = new Discord.RichEmbed()
       .setColor('#48f442')
       .setDescription(`txt`)
     message.reply(`txt`,embed).then(embedMessage => {
     var favor =  embedMessage.react("");
     var against = embedMessage.react("");
     startgame(against, favor)
    });

let startgame = function(against, favor) {
        setTimeout(function () {
          if(favor > against) {
       client.guilds.get(message.guild.id).channels.get("536028903458996225").send("txt")
     }
          if(favor < against) {
      client.guilds.get(message.guild.id).channels.get("536337360808312872").send("txt")
      client.guilds.get(message.guild.id).channels.get("536028903458996225").send("txt")
     }
        }, 5000);
    }

   }
})


text:
Q: What does the function CvPoint2D32f in OpenCV CvPoint2D32f

I want to know what this function does, for example:
CvPoint2D32f center = cvPoint2D32f(src->width/2,src->height/2);

A: OpenCV has a few different data structures for points (that is, x:y or x:y:z coordinates) and their name tells you what type of point it is.
This particular point is a 2D Point - so it has just X and Y coordinates, and they are 32-bit floating point values.  That's what the 32f at the end means.  A 3D point that uses 32-bit floating point values would have 3D32f at the end of the data type name.
See this page in the OpenCV reference documentation for more info.

A: The code you posted sets the coordinates of a 2D point type as the center coordinates of some src data structure (eg cv::Mat or CvMat).


text:
Q: Sitecore: Get child items of parent item when the items are in publish restricted period I am trying to get the children items of a Item.,of which some of the child items  applied publish restrictions and there end date had expired.
I want to collect all the child items, whether it's end expired or not.
when i debugged my code i got only those items which have end date in time.
I have used following code
var childItems=item.GetChildren();

the child items collection is collecting only those child items which have there end date in time.
is there any method to collect all the items??
I have asked in sitecore forum, they asked to get child items from master database, but that approach also not working. i have tried following code also.
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Item parentNode= master.GetItem("ItemNAme");
var childItems=parentNode.GetChildren();

The childitems is only collecting those child items whose end date is not expired
Please suggest me some solution for this
Thanks in advance
-Vaibhav

A: What you said about going to the master database is correct, as the master contains all versions of all pieces of content, not just publicly published content. I would wrap your code in a SecurityDisabler() in case that is somehow interfering with getting the right items.
using(new SecurityDisabler()) {
    Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
    Item parentNode= master.GetItem("ItemNAme");
    var childItems=parentNode.GetChildren();
}

A: The reason you find this problem is not related to security.
When IsPreview is true (cookie based) and Filtering on the site config is allowed you will not get Items with publishing restrictions. This functionality is from the implementation of the PageEditor Preview where you need to browse the master database as if published items where not visible.
See the answers on Sitecore Publishable flag makes it impossible to GetItem() from Master database


text:
Q: cannot finds symbol action listener i am doing a browse file class by using JFileChooser. i meet a problem when compile. it keep told me than cannot find symbol actionlistener. below is my code:
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.text.*;
import javax.swing.filechooser.*;

public class BrowseForFile
{
private JTextField txtFileName;
private JFrame layout;

public BrowseForFile()
{
    super();
    initialize();
}

    public void initialize()
    {
        //empty layout
        layout = new JFrame();
        layout.setTitle("Task Synchronization ");
        layout.setBounds(100, 100, 800, 600);
        layout.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        layout.getContentPane().setLayout(null);

        //set the copyright
        JLabel lblNewLabel_5 = new JLabel("(c) 2012 All Rights Reserved");
        lblNewLabel_5.setForeground(Color.GRAY);
        lblNewLabel_5.setFont(new Font("Tahoma", Font.PLAIN, 10));
        lblNewLabel_5.setHorizontalAlignment(SwingConstants.RIGHT);
        lblNewLabel_5.setBounds(527, 548, 255, 14);
        layout.getContentPane().add(lblNewLabel_5);

        //set the label
        JLabel lblSendAFile = new JLabel("Select a file to be sent to all nodes");
        lblSendAFile.setBounds(404, 400, 378, 14);
        layout.getContentPane().add(lblSendAFile);

        //set the textfield
        txtFileName = new JTextField();
        txtFileName.setBounds(404, 425, 277, 20);
        layout.getContentPane().add(txtFileName);
        txtFileName.setColumns(10);

        //set the browse button and let it to choose file after click.
        JButton btnBrowse = new JButton("Browse");
        btnBrowse.setBounds(691, 424, 91, 23);
        layout.getContentPane().add(btnBrowse);

        btnBrowse.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                JFileChooser chooser = new JFileChooser();
                chooser.setCurrentDirectory(new File(dirName));
                chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

                FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt only", "txt");
                chooser.setFileFilter(filter);

                try {
                int code = chooser.showOpenDialog(null);
                if (code == JFileChooser.APPROVE_OPTION) {
                File selectedFile = chooser.getSelectedFile();
                Scanner input = new Scanner(selectedFile);
                String f=selectedFile.getName();
                txtFileName.setText("File Name is: "+f);

                }

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

    public static void main(String[] args)
    {
        try
        {
            BrowseForFile window = new BrowseForFile();
            window.layout.setVisible(true);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

}

this is the error :
BrowseForFile.java:52: error: cannot find symbol
                    btnBrowse.addActionListener(new ActionListener()
                                                    ^
symbol:   class ActionListener
location: class BrowseForFile
1 error

can anyone tell me what is the error ? thanks in advance.

A: You have to import following classess.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

A: Since your question has already been answered, I would like to offer a suggestion.
Use an IDE like Eclipse or Netbeans. They take care of imports, formatting, checked exceptions, etc making your life much easier.

A: import java.awt.event.ActionListener; // seems to be missing.

A: import java.awt.* means import all the classes from this package but not from the sub packages. For every sub package, you have to put separate import statement. e.g. import java.awt.event, import java.awt.datatransfer.* etc.


text:
Q: Google API: Using requestAccessToken() without a popup? (Ionic/Capacitor) I am using the following code to get a client token from Google in order to access the user's calendar. This works absolutely fine on Desktop.
However, on my Capacitor mobile app, a popup can not be opened out of the box.
So my question is: Is there possibility to authenticate my client without a popup?
    const client = google.accounts.oauth2.initTokenClient({
        client_id: '{id}',
        scope: 'https://www.googleapis.com/auth/calendar.readonly',
        redirect_uri: 'http://localhost:3000/calendar',
        callback: (tokenResponse) => {
            googleGetEvents(tokenResponse.access_token);
            return tokenResponse.access_token;
        }
    });

    client.requestAccessToken({ prompt: '' }); // prompt '' is required to avoid the consent screen


text:
Q: Hiding element in body, which has specific classes I got some code here:

        <title>Select View</title>

        Many divs here
        ...
        ...
        ...

PHP code here

And I want to hide the div with the test id. My site is based on wordpress, so in css I have to refer to a specific body.
I tried:
body.class-1, .class-2, .class-3, .class-4, .class-5, div#test{
    color: red;
}

and the color is working, "PHP code here" is on red color, but when i do this:
body.class-1, .class-2, .class-3, .class-4, .class-5, div#test{
        display: none; //or visibility: hidden;
    }

all site dissapears.
Any ideas how to hide only this div?

A: Just use what you have already
div#test{
   display: none;
}

When you called body.class-1, .class-2, .class-3, .class-4, .class-5, and set display: none, it is the expected behaviour, because you are hiding all elements rather than just the test div!

A: Since you don't repeat the id in other elements you can just use,
#test {
    display: none;
}

Just in-case if you have another element (ex: span) with the same id you have to specifically mention that you need to hide the div element with id=test
div#test {
    display: none;
}

It is always a good thing to uniquely mark your elements if possible. Since you are dealing with classes if you just mention one class it will select the matching element.
In the below case you used your  selection is the whole body,
body.class-1, .class-2, .class-3, .class-4, .class-5, div#test{
    display: none; //or visibility: hidden;
}

This might be the same case if you just use the below code,
.class-1 {
    display: none; //class-1 supposed to pick the whole body here;
}


text:
Q: Mingw-w64 C11 threads.h not found? I'm trying to use the C11 standard threading in my program, and I'm using the Mingw-w64 toolchain x86_64-8.1.0-posix-seh-rt_v6-rev0 specifically.
When I #include <threads.h> as the C11 standard defines, I get the No such file or directory error from gcc. I have found that I can #include <pthread.h> without error. I am passing the -std=c11 argument to gcc, btw.
I've searched high and low on the internet for any information about the standard C threading support. All I can find information on is for C++. Can somebody please explain to me why I can't use the C11 standard threads.h library?
EDIT:
I've also checked if the STDC_NO_THREADS macro is defined. It seems to be undefined.
#ifdef __STDC_NO_THREADS__
printf("We got no threads capp'n!\n");
#endif

I get no message about not having threads.

A: I also meet this problem on Windows 11. There is no threads.h under Mingw-w64 and vs 2022. But if you want to use it you can install Msys2 and gcc on it. After installation you find the head file there! I add thread.h into the source file and test it. Of course gcc in Msys2 compiles it with no error and warning. And I finally add __STDC_NO_THREADS__ and __STDC_NO_ATOMICS__ into the source and the compiler passes the error that the macros are undeclared. So the compiler support the C11 standard Concurrency support library.


text:
Q: AddThis FaceBook sharing without webpage scraping I have a web application that is built on Backbone JS framework, that is most URLs have a hashtag section in them. For example: www.abcd.com/xyz.shtml#/route1
the 'route1' is the name of a defined execution route which causes contents including the meta-tags of the page to be populated dynamically on-load by making a number of AJAX calls to the server. I'm not able to integrate AddThis Facebook-share because when FB scrapes the URL it doesn't execute the JS section defined by the 'route1' and thus none of the meta-tags are populated!
Can anyone suggest me a way to bypass this scraping process of FB and/or lets me supply the relevant parameters to FB and FB posts it directly without messing with the URL?
Many Thanks.


text:
Q: Restore mysql db from AWS AMI? We have one EC2 instance running our mysql database server.
due to a security incident we had to delete the current EC2 instance as database was completely messed up with some sort of encryption.
So we had to recover it from Snapshot/AMI that are being taken every 6 hours. we have past 1 months snapshots and AMI's available for this EC2 instance.
This EC2 instance has only one SSD (Persistent Block Storage) EBS volume, which is part of the Snapshots/AMI's.
We also have phpmyadmin installed but its not able to connect to DB for obvious reasons!
Below are the details of OS and the mysql Service status.
# cat /etc/release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=20.04
DISTRIB_CODENAME=focal
DISTRIB_DESCRIPTION="Ubuntu 20.04.1 LTS"
NAME="Ubuntu"
VERSION="20.04.1 LTS (Focal Fossa)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 20.04.1 LTS"
VERSION_ID="20.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=focal
UBUNTU_CODENAME=focal

# mysqld --version
/usr/sbin/mysqld  Ver 8.0.22-0ubuntu0.20.04.2 for Linux on x86_64 ((Ubuntu))

# systemctl status mysql.service
● mysql.service - MySQL Community Server
     Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
     Active: activating (start) since Mon 2021-03-01 13:19:50 UTC; 241ms ago
    Process: 79728 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exited, status=0/SUCCESS)
   Main PID: 79736 (mysqld)
     Status: "Server startup in progress"
      Tasks: 1 (limit: 1164)
     Memory: 91.3M
     CGroup: /system.slice/mysql.service
             └─79736 /usr/sbin/mysqld

Mar 01 13:19:50 ip-172-31-93-250 systemd[1]: Starting MySQL Community Server...
Mar 01 13:19:52 ip-172-31-93-250 systemd[1]: mysql.service: Main process exited, code=exited, status=1/FAILURE
Mar 01 13:19:52 ip-172-31-93-250 systemd[1]: mysql.service: Failed with result 'exit-code'.
Mar 01 13:19:52 ip-172-31-93-250 systemd[1]: Failed to start MySQL Community Server.
Mar 01 13:19:53 ip-172-31-93-250 systemd[1]: mysql.service: Scheduled restart job, restart counter is at 328.
Mar 01 13:19:53 ip-172-31-93-250 systemd[1]: Stopped MySQL Community Server.
Mar 01 13:19:53 ip-172-31-93-250 systemd[1]: Starting MySQL Community Server...

# journalctl -xe
Mar 01 13:14:20 ip-XXX-XXX-XXX-XXX systemd[1]: mysql.service: Main process exited, code=exited, status=1/FAILURE
-- Subject: Unit process exited
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- An ExecStart= process belonging to unit mysql.service has exited.
--
-- The process' exit code is 'exited' and its exit status is 1.
Mar 01 13:14:20 ip-XXX-XXX-XXX-XXX systemd[1]: mysql.service: Failed with result 'exit-code'.
-- Subject: Unit failed
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- The unit mysql.service has entered the 'failed' state with result 'exit-code'.
Mar 01 13:14:20 ip-XXX-XXX-XXX-XXX systemd[1]: Failed to start MySQL Community Server.
-- Subject: A start job for unit mysql.service has failed
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- A start job for unit mysql.service has finished with a failure.
--
-- The job identifier is 105083 and the job result is failed.
Mar 01 13:14:21 ip-XXX-XXX-XXX-XXX systemd[1]: mysql.service: Scheduled restart job, restart counter is at 206.
-- Subject: Automatic restarting of a unit has been scheduled
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- Automatic restarting of the unit mysql.service has been scheduled, as the result for
-- the configured Restart= setting for the unit.
Mar 01 13:14:21 ip-XXX-XXX-XXX-XXX systemd[1]: Stopped MySQL Community Server.
-- Subject: A stop job for unit mysql.service has finished
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- A stop job for unit mysql.service has finished.
--
-- The job identifier is 105149 and the job result is done.
Mar 01 13:14:21 ip-XXX-XXX-XXX-XXX systemd[1]: Starting MySQL Community Server...
-- Subject: A start job for unit mysql.service has begun execution
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- A start job for unit mysql.service has begun execution.
--
-- The job identifier is 105149.

For additional Log output of "# tail -500 /var/log/mysql/error.log"
Can any of you please help me restore the mysql service with the data/databases?
We are not sure what is the right procedure to follow in this scenario to restore the databases.
Thanks in advance!

A: To resolve this issue the only thing you have to do is below:
just edit /etc/mysql/mysql.conf.d/mysqld.cnf file using whichever editor you like and update the bind address using whichever editor you like. below is the line you need to update with the correct/updated IP address. because when you launch a new EC2 instance using an backup AMI image or Snapshot it gets a new private IP Address (Unless you have made it static in your OS configuration earlier.)
bind-address           = 192.168.XXX.XXX
Then restart the mysql service using below command and everything will start working as earlier including the PHP My Admin console.
systemctl restart mysql.service


text:
Q: how to append a new div between each img tag using jquery? This is my code:

i want to append like this but class should be created and append dynamically using jquery:I tried but my logic is wrong so anyone help

    $('img').each(function(){
var that = $(this);
var v = document.createElement('div');
v.setAttribute('class','new');
$(v).append(that);
$('sample').append(v);
});

A: $('.sample img').wrap('

');

A: You can use wrap method:
$('.sample img').wrap('

');

Your code also works if you add . for the class selector:
$('sample').append(v);
// ^---

http://jsfiddle.net/6hYFc/

A: $('img').wrap('
content
')

should be all you need


text:
Q: Force Camel case in Swagger Gen for parameters Problem:
I have Rest Endpoint with route params that look something like this
    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteDocument([FromRoute] DeleteDocumentRequest request)

Where the "DeleteDocumentRequest" has a gettor / settor
    public Guid Id {get; set;}

However, when swagger gen serializes this into OpenApi 3.0, it generates an error because the case of the property "Id" in the class does not match the property "id" in the route.
Question:
How can I override the serializer for it to change all of my properties to camelCase to ensure conformity?
Using Newtonsoft Json in .NET 6, I have tried to use CamelCasePropertyNamesContractResolver as well as overrides for ResolvePropertyName and CreateProperties, but the parameters in the controller endpoint are not "properties" that get hit.

A: I was able to solve it by adding the following to the Swagger Gen setup.  Thanks to @jspcal for the link to a related question.
services.AddSwaggerGen(c =>
            {
                c.DescribeAllParametersInCamelCase();
            });


text:
Q: Hibernate Running native SQL Select I am trying to run a simple SQL(native) query within a hibernate application.
SELECT COUNT(*) from users

The answer to the select may be saved into a integer.
How can i do this without having to create a model class in Hibernate?

A: int count=0;
Resultset rs=Statement.ExecuteQuery("SELECT COUNT(*) as count from users");
    if(rs.next()){
     count=rs.getInt("count");
    }

System.out.println(count);

A: Hibernate 5.0.9.Final will give that result as a BigInteger type object. Assuming you have an EntityManager, then use:
BigInteger r = (BigInteger) em.createNativeQuery("select count(*) from user").getSingleResult();
System.out.println(r);

This is a simple question and you should be able to find the answer easily on stackoverflow:
hibernate native query, count [duplicate].
How do we count rows using Hibernate?

A: Resultset rs=Statement.ExecuteQuery("SELECT COUNT(*) as number from users");
while(rs.next()){
 Long count =rs.getLong("number");
    }


text:
Q: When to optimize a Solr Index I am using the Collective Solr 4.1.0 Search on our Plone 4.2.6 system. We have not deployed the Solr search to our live system yet, so I'm free to test and develop. I recently gathered some knowledge about the Optimize option for the Solr Index.
During my investivations, I found quite a few warnings not to optimize in the course of development since that could easily cause bad readability.
My question now is: Does that only concern raw index data, which probably would not affect my work with that index, or would it yield more problems to address during the development process?
Thanks in advance!


text:
Q: How to save and close appointment without discard event in OWA using office-js appointment  can be saved in OWA as following . but it does not close automatically as send or save button click event in OWA appointment .
 Office.context.mailbox.item.saveAsync(function(result) {

    });

A: In the saveAsync callback function, you can call close API to close the window.
Below example will save and upon successful save, close the compose window.
Office.context.mailbox.item.saveAsync(function(result) {
    if (result.status === Office.AsyncResultStatus.Succeeded)
        Office.context.mailbox.item.close();
});

Edit:
I do see that in Outlook Web application (OWA), a dialog to Discard event is being shown even after successful save operation, but the same works on Outlook Win32/Mac. This could possibly be an issue in OWA.


text:
Q: Align equation, matrix, and table I need to align this equation as:

I recreated it by using the equation, matrix, and tabular environment.
\begin{equation} \hat{J}_x \leftrightarrow \frac{\hbar}{2}
\begin{pmatrix}
  \begin{tabular}{ c | c | c | c | c }
    0 & 0 & 0 & 0 &   \\ \hline
    \multirow{2}{*}{0} & 0\ 1 & \multirow{2}{*}{0} & \multirow{2}{*}{0} \\ & 1\ 0 &  &  \\ \hline
    \multirow{3}{*}{0} & \multirow{3}{*}{0} & 0\ \ $\sqrt{2}$\ \ 0 & \multirow{3}{*}{0} \\ &  & $\sqrt{2}$\ \ 0\ $\sqrt{2}$ & \\ & & 0\ \ $\sqrt{2}$\ \ 0 &  \\ \hline
    \multirow{4}{*}{0} & \multirow{4}{*}{0} & \multirow{4}{*}{0} & 0\ $\sqrt{3}$\ 0\ 0 &  \\
    & & & $\sqrt{3}$\ 0\ 2\ 0 & \\
    & & & 0\ 2\ 0\ $\sqrt{3}$ & \\
    & & & 0\ 0\ $\sqrt{3}$\ 0&  \\ \hline
    & & & & $\ddots$ \\
  \end{tabular}
  \end{pmatrix}
\end{equation}

I am getting this:

But I need the first part of the equation to be aligned on the top left. Also the alignment in the table is a bit off. Any ideas?

A: You can use delarray for top aligning the matrix and gathered for centering the equation number.
\documentclass{article}
\usepackage{amsmath}
\usepackage{delarray}

\begin{document}

\begin{equation}
\begin{gathered}
\hat{J}_x \leftrightarrow \frac{\hbar}{2}
\begin{array}[t]({ c | c | c | c | c })
0 & 0 & 0 & 0 & \vphantom{\Big|} \\
\hline
0 & \begin{matrix} 1 & 0 \\ 0 & 1\end{matrix} & 0 &  &  \\
\hline
0 & 0 & \begin{matrix}
        0 & \sqrt{2} & 0 \\
        \sqrt{2} & 0 & \sqrt{2} \\
        0 & \sqrt{2} & 0
        \end{matrix} & 0 & \\
\hline
0 & 0 & 0 & \begin{matrix}
            0 & \sqrt{3} & 0 & 0 \\
            \sqrt{3} & 0 & 2 & 0 \\
            0 & 2 & 0 & \sqrt{3} \\
            0 & 0 & \sqrt{3} & 0
            \end{matrix} & \\
\hline
    & & & & \ddots
\end{array}
\end{gathered}
\end{equation}

\end{document}

Nesting matrices is much easier than abusing \multirow.

Removing gathered yields

On the other hand, I don't think this is really clear.
In case you change your mind:
\documentclass{article}
\usepackage{amsmath}

\begin{document}

\begin{equation}
\hat{J}_x \leftrightarrow \frac{\hbar}{2}
\left(\begin{array}{ @{} c | c | c | c | c @{} }
0 & 0 & 0 & 0 & \vphantom{\Big|} \\
\hline
0 & \begin{matrix} 1 & 0 \\ 0 & 1\end{matrix} & 0 &  &  \\
\hline
0 & 0 & \begin{matrix}
        0 & \sqrt{2} & 0 \\
        \sqrt{2} & 0 & \sqrt{2} \\
        0 & \sqrt{2} & 0
        \end{matrix} & 0 & \\
\hline
0 & 0 & 0 & \begin{matrix}
            0 & \sqrt{3} & 0 & 0 \\
            \sqrt{3} & 0 & 2 & 0 \\
            0 & 2 & 0 & \sqrt{3} \\
            0 & 0 & \sqrt{3} & 0
            \end{matrix} & \\
\hline
    & & & & \ddots
\end{array}\right)
\end{equation}

\end{document}

You can obtain a more open look by setting \extrarowheight. I'll only show it added to the last code, the method applies the same for the other two examples.
\documentclass{article}
\usepackage{amsmath}
\usepackage{array}

\begin{document}

\begin{equation}
\setlength{\extrarowheight}{2pt}
\hat{J}_x \leftrightarrow \frac{\hbar}{2}
\left(\begin{array}{ @{} c | c | c | c | c @{} }
0 & 0 & 0 & 0 & \vphantom{\Big|} \\
\hline
0 & \begin{matrix} 1 & 0 \\ 0 & 1\end{matrix} & 0 &  &  \\
\hline
0 & 0 & \begin{matrix}
        0 & \sqrt{2} & 0 \\
        \sqrt{2} & 0 & \sqrt{2} \\
        0 & \sqrt{2} & 0
        \end{matrix} & 0 & \\
\hline
0 & 0 & 0 & \begin{matrix}
            0 & \sqrt{3} & 0 & 0 \\
            \sqrt{3} & 0 & 2 & 0 \\
            0 & 2 & 0 & \sqrt{3} \\
            0 & 0 & \sqrt{3} & 0
            \end{matrix} & \\
\hline
    & & & & \ddots
\end{array}\right)
\end{equation}

\end{document}

A: If you want the eq number aligned with the top, then just place the pmatrix in a \belowbaseline[-\ht\strutbox]{...}.
\documentclass{article}
\usepackage{amsmath,multirow,stackengine}
\begin{document}
\begin{equation} \hat{J}_x \leftrightarrow \frac{\hbar}{2}
\belowbaseline[-\ht\strutbox]{$\begin{pmatrix}
  \begin{tabular}{ c | c | c | c | c }
    0 & 0 & 0 & 0 &   \\ \hline
    \multirow{2}{*}{0} & 0\ 1 & \multirow{2}{*}{0} & \multirow{2}{*}{0} \\ & 1\ 0 &  &  \\ \hline
    \multirow{3}{*}{0} & \multirow{3}{*}{0} & 0\ \ $\sqrt{2}$\ \ 0 & \multirow{3}{*}{0} \\ &  & $\sqrt{2}$\ \ 0\ $\sqrt{2}$ & \\ & & 0\ \ $\sqrt{2}$\ \ 0 &  \\ \hline
    \multirow{4}{*}{0} & \multirow{4}{*}{0} & \multirow{4}{*}{0} & 0\ $\sqrt{3}$\ 0\ 0 &  \\
    & & & $\sqrt{3}$\ 0\ 2\ 0 & \\
    & & & 0\ 2\ 0\ $\sqrt{3}$ & \\
    & & & 0\ 0\ $\sqrt{3}$\ 0&  \\ \hline
    & & & & $\ddots$ \\
  \end{tabular}
  \end{pmatrix}$}
\end{equation}
\end{document}

If you want the number centered, then just wrap the whole thing in a \vcenter{\hbox{$\displaystyle...$}}
\documentclass{article}
\usepackage{amsmath,multirow,stackengine}
\begin{document}
\begin{equation} \vcenter{\hbox{$\displaystyle\hat{J}_x \leftrightarrow \frac{\hbar}{2}
\belowbaseline[-\ht\strutbox]{$\begin{pmatrix}
  \begin{tabular}{ c | c | c | c | c }
    0 & 0 & 0 & 0 &   \\ \hline
    \multirow{2}{*}{0} & 0\ 1 & \multirow{2}{*}{0} & \multirow{2}{*}{0} \\ & 1\ 0 &  &  \\ \hline
    \multirow{3}{*}{0} & \multirow{3}{*}{0} & 0\ \ $\sqrt{2}$\ \ 0 & \multirow{3}{*}{0} \\ &  & $\sqrt{2}$\ \ 0\ $\sqrt{2}$ & \\ & & 0\ \ $\sqrt{2}$\ \ 0 &  \\ \hline
    \multirow{4}{*}{0} & \multirow{4}{*}{0} & \multirow{4}{*}{0} & 0\ $\sqrt{3}$\ 0\ 0 &  \\
    & & & $\sqrt{3}$\ 0\ 2\ 0 & \\
    & & & 0\ 2\ 0\ $\sqrt{3}$ & \\
    & & & 0\ 0\ $\sqrt{3}$\ 0&  \\ \hline
    & & & & $\ddots$ \\
  \end{tabular}
  \end{pmatrix}$}$}}
\end{equation}
\end{document}

A: You can use \raisebox{-\height} to lower the box to move it below the baseline and \raisebox{\dimexpr-\height+\baselineskip\relax} to get it on the correct height:
\documentclass[]{article}

\usepackage[]{amsmath}
\usepackage{multirow}

\begin{document}
\begin{equation} \hat{J}_x \leftrightarrow \frac{\hbar}{2}
  \raisebox{\dimexpr-\height+\baselineskip\relax}
    {%
      $\begin{pmatrix}
      \begin{array}{ c | c | c | c | c }
        0 & 0 & 0 & 0 &   \\ \hline
        \multirow{2}{*}{0} & 0\ 1 & \multirow{2}{*}{0} & \multirow{2}{*}{0} \\ & 1\ 0 &  &  \\ \hline
        \multirow{3}{*}{0} & \multirow{3}{*}{0} & 0\ \ \sqrt{2}\ \ 0 & \multirow{3}{*}{0} \\ &  & \sqrt{2}\ \ 0\ \sqrt{2} & \\ & & 0\ \ \sqrt{2}\ \ 0 &  \\ \hline
        \multirow{4}{*}{0} & \multirow{4}{*}{0} & \multirow{4}{*}{0} & 0\ \sqrt{3}\ 0\ 0 &  \\
        & & & \sqrt{3}\ 0\ 2\ 0 & \\
        & & & 0\ 2\ 0\ \sqrt{3} & \\
        & & & 0\ 0\ \sqrt{3}\ 0&  \\ \hline
        & & & & \ddots \\
      \end{array}
      \end{pmatrix}$%
    }
\end{equation}
\end{document}


text:
Q: heap and class destructor I have a problem with my code. I get an error of BLOCK_TYPE_IS_VALID... I know there is problem with new and delete, but I cannot find it.
I have a myString class with these functions:
    //constructors and destructors
myString::myString() {
    this->string_ = NULL;
    this->length = 0;

    cout << "created " << "NULL" << endl;
}

myString::myString(char a[]) {
    int i;
    for (i=0; a[i]!=NULL; i++);
    this->length = i;

    int j=0;
    while(pow(2,j)<i)
        j++;

    this->string_ = new char [(int)pow(2,j)];
    for (int i=0; i<this->length; i++)
        this->string_[i] = a[i];

    cout << "created " << this->string_ << endl;
}

myString::~myString() {
    cout << "deleteing " << this->string_ << endl;
    if (this->string_ != NULL)
        delete [] this->string_;
}

and when I run this
myString a("aaa");
myString b("bbbb");
myString c;
c = a + b;
cout << c.get_lenght() << endl;
cout << c.get_string() << endl;

I get the error in line "c = a+b" and then program stops.

A: You need to define a copy constructor and assignment operator for your class.
myString::myString( const myString& );
myString& operator=( const myString& );

Otherwise, you are violating the rule of three.
This code...
c = a + b;

may produce a temporary myString holding the value a + b.
The default generated copy and assignment implementations will give c the same string_ pointer that the temporary has.
And when the destructor for either of those strings is run, the other string will have a dangling pointer.
Coincidentally, this code:
if (this->string_ != NULL)
    delete [] this->string_;

Will never act differently than simply:
delete [] this->string_;

A: You haven't shown the class definition, but I'm guessing that you haven't followed the Rule of Three.
Without a correctly implemented copy constructor and copy-assignment operator, it is not possible to copy objects safely. The default implementation will simply copy the pointer (and other member variables), leaving both copies to delete the same block of memory in their destructors.
The simplest solution is to use a class designed to manage memory for you. std::string or std::vector<char> would be ideal here.
Assuming you have a good reason for managing the memory yourself, you will need something like:
// Copy constructor
myString(myString const & other) :
    string_(new char[other.length]),
    length(other.length)
{
    std::copy(other.string_, other.string_+length, string_);
}

// Simple assignment operator
// For bonus points (and a strong exception guarantee), use the copy-and-swap idiom instead
myString & operator=(myString const & other) {
    if (this != &other) {
        delete [] string_; // No need to check for NULL (here or in the destructor)
        string_ = new char[other.length];
        length = other.length;
        std::copy(other.string_, other.string_+length, string_);
    }
    return *this;
}

In C++11, for even more bonus points, consider also providing a move constructor and assignment operator. These just need to modify the pointers, so will be much more efficient than copying.