text:
Q: Run torque job while editing the source file I have a project using git as the source control tool, with a default branch named dev. And I can run that as a job on a torque server. My question is, while the job using the code from branch dev is running, is it safe to create a new branch, then edit some piece of code and run that new branch?
I guess this is related to how program is loaded into memory and maybe also the internal logic of torque. Any ideas?

A: You problem is actually not really specific to either GIT or TORQUE.
What you (I guess) want to do is change a scripts source while it is running.
As you already guessed, this is heavily dependent on your program.
E.g.

*

*if you program is a shell script, this will not work, at least not by default. See https://unix.stackexchange.com/questions/110663/bash-is-automatically-reloading-injecting-updates-into-a-running-script-upon-s

*if your application is a Python script, changing the script's source should work fine: What will happen if I modify a Python script while it's running?
You will have to check the implications for your technology stack.
However, if this is a more complex application, there could be a lot of pitfalls.
I would recommend finding another solution. If your GIT repository is small, a straightforward approach would be to just check out multiple repository instances i.e. to different folders.


text:
Q: Oracle SQL: Creating unique teamid from existing table I have table dept(deptname, color). I would like to create a unique teamid by selecting the first 3 chars of the deptname and the first 2 chars of the color and a corresponding number. I got the SQL part down but don't know what the next step is
select deptname, upper(substr(1,3), color upper(substr(1,2)
from dept;

Here is my dept table
DEPTNAME............COLOR
SALES...............Orange
ACCOUNTING..........Blue

And my output should be
SALOR1
ACCBL2

A: Depending on what you're using this for, you could just use rownum:
select upper(substr(deptname,1,3)) || upper(substr(color,1,2))
|| rownum from dept;

There is no guarantee that running this sql will always produce the same teamid each time it is run though.  For that, you'd have to add another column with a number in.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Clean Architecture diagram Below is the classical Clean Architecture diagram from Uncle Bobs original blog post.

I am rather confused as to why the Gateways are more outwards than the Use Cases. This is something present in all such diagrams I have seen so far that include Gateways or some other form of Data Access mechanism.
I understand that Use Cases should not bind to the specifics of the Data Access mechanism, as these should be hidden behind an architectural boundary. At the same time the only users of the services that form this boundary should be the Use Cases. That clashes hard with the diagram, as following the visual rules, Use Cases cannot use the Gateways (while they need to) and frameworky-stuff can use them (while it should not).
Am I missing something? And if not, is there a more correct way to represent the rules of The Clean Architecture visually?
I'm asking because I am creating a diagram that shows The Clean Architecture + DDD Bounded Contexts.

I'm not happy with how the DB and services bits are outside of the UseCase circle as like that it is not clear the UseCases are the public interface of the Bounded Context and that the persistence is not directly accessible from the outside.
Something like this solves these two issues but introduces a new one: no indication of the data access layer boundary. In fact, following the visual rules, the diagram suggests that everything in the Bounded Context can directly access the persistence.

I believe I am running into the same problem that causes the Gateways to be "misplaced" in the original diagram and am looking for a way around that.

A: The diagram shows where the implementations reside, not the interfaces. The gateway interfaces reside with the use cases.

A: The diagram is a more elaborate version of Alistair Cockburn's Hexagonal Architecture, which is a lot more precise about the use of adapters, especially in respect to CDI.
Essentially, the idea is to turn dependencies inward: Use Cases may depend upon Entities (i.e., import domain related packages and use domain data types; Cockburn does not describe these as separate circles, but rather as "the application"). Adapters on the left may call Use Cases (i.e., execute or abort them, e.g. using the Command pattern), while Use Cases in turn may call interfaces (such as service or repository facades, which are implemented by Adapters on the right), using the principle of Dependency Inversion to preserve the inbound direction.
If you're confused about "left" and "right": In Cockburn's picture, the hexagon has adapters on the left (input/interaction mechanisms) and on the right (persistence, external systems, services). You may think of it as a 3-layer-architecture diagram turned 90 degrees, where the domain layer does not depend on the persistence layer, but the other way around.
Again, Cockburn's explanation, while perhaps a bit harder to grasp due to the unusual hexagonal image, is the more precise one, because it doesn't try to include everything and concentrates on the dependency fundamentals.

A: In your BC drawing your are missing a surrounding circle outside UC. That circle is infraestructure, where you should place the Repository implementation of the Repository interface of the Domain Model. The implementation access the DB using a technology (SQL for example).
So the circles are from inside to outside:

*

*Domain Model (entities, value objects, repositories(interfaces), etc)

*Application Layer (use cases).

*Infraestructure (UI,repositories(implementation),etc)

Dependencies points inwards and not just the next circle inside (infraestructure depends both on application layer and domain model).
I use hexagonal architecture though.

A: The gateway interfaces must reside in the use cases layer and implemented in the interface adapters layer to ensure the dependency rule.
  Interface Adapters Layer    || Use Cases Layer
                              ||
  +-----------------+         || <implements>    +-------------+   <uses>  +---------+
  |JDBCEntityGateway| --------++-------------->  +EntityGateway|  <------  | UseCase |
  +-----------------+         ||                 +-------------+           +---------+
                              ||

This pattern can be applied to every architectural boundary. The higher level layer defines an interface to tell what it needs and not how it is done. The lower level layer implements that interface and thus defines how it is done. Maybe that's why the layer is named interface adapters. As a result of this you can change the way of how something is done by providing another implementation. You might recognize now that this is the open-close principle.
But keep in mind that the interface should be a stable abstraction of what the use case needs. Don't put implementation specific things in that interface, e.g. if you specify a find method like this List<Eintity> find(String where). Becauese the where string is a detail, perhaps a SQL or JPQL string part. You should rather introduce a EntityCriteria that describes the selection criteria in an implementation independent way.


text:
Q: Pandas rolling values How do I obtain the rolling values of some length n of a pandas series of value ?
For example, if I have the following:
df = pd.DataFrame({'temperature': [0, 1, 2, np.nan, 4, 2, 0.8, 4, 8.8, 7.12]})

how do I obtain the moving values of length n, i.e. something like, if n=3:
[NaN, NaN, 0], [NaN, 0, 1],..., [4, 8.8, 7.12]
EDIT:
If I use pandas rolling, as:
roll = pd.Series.rolling(df, 3).mean()

then roll is the moving averages of the series.
Here, I do not want the averages of every moving set of 3 values, but these sets of 3 values.

A: I think you need first add NaNs and then this solution:
N = 3
x = np.concatenate([[np.nan] * (N-1), df['temperature'].values])

def rolling_window(a, window):
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
    strides = a.strides + (a.strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
print (rolling_window(x, N))
[[  nan   nan  0.  ]
 [  nan  0.    1.  ]
 [ 0.    1.    2.  ]
 [ 1.    2.     nan]
 [ 2.     nan  4.  ]
 [  nan  4.    2.  ]
 [ 4.    2.    0.8 ]
 [ 2.    0.8   4.  ]
 [ 0.8   4.    8.8 ]
 [ 4.    8.8   7.12]]

A: Even though the thread is old, maybe it will help someone else. I'm a beginner, but I solved user5805065's question by following procedure. Maybe, someone can make it more elegant and efficient.

*

*converting Pandas series to NumPy:

rollTemperature = df['temperature'].values

*

*then I've created numpy array in a for loop with some initial variables:

period = 2
stop = len(rollTemperature)
diffRoll = np.zeros(stop)

for i in range(0,stop):

    if i == 0:
        diffRoll[i] = np.nan

    elif np.mod(i,period)!=0:
        diffRoll[i] = np.nan

    else:
        diffRoll[i] = (rollTemperature[i] + rollTemperature[i-period])/2

*

*than adding numpy array to existin dataFrame:

df['diffRoll'] = diffRoll

Than the output is:
   temperature  diffRoll
0         0.00       NaN
1         1.00       NaN
2         2.00       1.0
3          NaN       NaN
4         4.00       3.0
5         2.00       NaN
6         0.80       2.4
7         4.00       NaN
8         8.80       4.8
9         7.12       NaN

A: pd.concat([df1.shift(i) for i in range(3)],axis=1).loc[:,::-1]\
    .agg(list,axis=1)

0     [nan, nan, 0.0]
1     [nan, 0.0, 1.0]
2     [0.0, 1.0, 2.0]
3     [1.0, 2.0, nan]
4     [2.0, nan, 4.0]
5     [nan, 4.0, 2.0]
6     [4.0, 2.0, 0.8]
7     [2.0, 0.8, 4.0]
8     [0.8, 4.0, 8.8]
9    [4.0, 8.8, 7.12]
dtype: object


text:
Q: How do I find the variance of $\overline{X}^2 - \frac{1}{n}$ where $X_i\sim N(\theta,1)$? I have a problem here. The question asks to compare the UMVUE and MVBE of $\theta^2$ considering a random sample $X_1,...,X_n$ from a $N(\theta,1)$ distribution.
I found out the Cramer Rao Lower Bound for the variance of an unbiased estimator for estimating $\theta^2$ to be $\frac{4\theta^2}{n}$. Since $\overline{X}$ came out to be a sufficient and complete statistic, I used this to get the UMVUE which is  $T = \overline{X}^2 - \frac{1}{n}$.
Now I have to find the variance of $T$.
Now,$Var[T]=Var[\overline{X}^2]$.
I see that $Z=n(\overline{X} - \theta)^2$ has a $\chi_1^2$ distribution. So,
 $Var[Z] = 2$
$\implies Var[(\overline{X} - \theta)^2]= \frac{2}{n^2}$
$\implies Var[\overline{X}^2 +\theta^2 - 2\overline{X}\theta] = \frac{2}{n^2}$
$\implies Var[\overline{X}^2] + Var[2\overline{X}\theta] = \frac{2}{n^2}$
$\implies Var[\overline{X}^2] = \frac{2}{n^2} - Var[2\overline{X}\theta]$
$\implies Var[\overline{X}^2] = \frac{2}{n^2} - \frac{4\theta^2}{n}=Var[T]$
The answer says that $Var[T] = \frac{2}{n^2} + \frac{4\theta^2}{n}$.
So where am I going wrong?
Edit: My teacher had used this method which I wasn't able to understand in two places. If someone could clarify this for me,would be great.
$Var[T] = Var[\overline{X}^2] = E[\overline{X}^4] - E^2[\overline{X}^2]$
$=E[\overline{X}^4] - (\mu^2 +\frac{1}{n})^2$
Now, $E[\overline{X}^4]=E[\overline{X} - \mu + \mu]^4$
$=E[\overline{X} - \mu]^4 + 4E[\overline{X}-\mu]^3\mu + 6E[\overline{X}-\mu]^2\mu^2 +4E[\overline{X}-\mu]\mu^3 +\mu^4$
$=3\frac{1}{n^2} + 0 + 6\frac{1}{n}\mu^2 + 0 + \mu^4$.
I can't understand how the first two terms came about in the last step.

A: If $X_1,\dots,X_n$ are iid normal rvs with mean $\mu$ and variance $1$ then: $$Z:=\sqrt{n}\left(\overline{X}-\mu\right)=\frac{\sqrt{n}}{n}\sum_{i=1}^{n}\left(X_{i}-\mu\right)$$
has standard normal distribution so that $\mathbb{E}Z^{4}=3$ (see here).
That leads to $\mathbb{E}\left(\left(\overline{X}-\mu\right)^{4}\right)=\mathbb{E}\frac{1}{n^{2}}Z^{4}=\frac{3}{n^{2}}$
and $\mathbb{E}\left(\left(\overline{X}-\mu\right)^{3}\right)=\mathbb{E}\frac{1}{n\sqrt{n}}Z^{3}=0$


text:
Q: JSON to javascript to edit the value of JSON I have a JSON file (.json).
"spinOptionArray" : [
 {"probability":100, "type": "string", "value": "SECTION 1", "resultText": "Please choose an item from Section 1"},
 {"probability":100, "type": "string", "value": "SECTION 2", "resultText": "Please choose an item from Section 2"},
 {"probability":100, "type": "string", "value": "SECTION 3", "resultText": "Please choose an item from Section 3"},
 {"probability":100, "type": "string", "value": "SECTION 4", "resultText": "Please choose an item from Section 4"},
 {"probability":100, "type": "string", "value": "SECTION 5", "resultText": "Please choose an item from Section 5"},
 {"probability":100, "type": "string", "value": "SECTION 6", "resultText": "Please choose an item from Section 6"}
]

How to I store the JSON file as a JS object instead? As I want to change the probability value in the JSON file with every click of the button.
Button html (in a .php file):
<button class="spinBtn" id="spinBtn">SPIN</button>

anyway, used this function to call the JSON
function loadJSON(callback) {
   var xobj = new XMLHttpRequest();
   xobj.overrideMimeType("application/json");
            xobj.open('GET', './wheel_data.json', true);
        xobj.onreadystatechange = function () {
            if (xobj.readyState == 4 && xobj.status == "200") {
                //Call the anonymous function (callback) passing in the response
                callback(xobj.responseText);
            }
        };
        xobj.send(null);
    }

A: If I were you then I'll use LocalStorage for this kind of task. With localStorage you can easily

*

*Store the string version of object using localStorage.setItem() and JSON.stringify()

*To get data back on string use localStorage.getItem(), parse it to object using JSON.parse()

*Do some modification as you wish e.g increment probability value in your case.

*Again store that modified object data to string format with localStorage.setItem() and JSON.stringify()
TO store object data in string format with JSON.stringify()
localStorage.setItem('key_name',JSON.stringify(object));

TO get string data and make object JSON.parse()
JSON.parse(localStorage.getItem('key_name'));

var before_btn_click =  [
 {"probability":100, "type": "string", "value": "SECTION 1", "resultText": "Please choose an item from Section 1"},
 {"probability":100, "type": "string", "value": "SECTION 2", "resultText": "Please choose an item from Section 2"},
 {"probability":100, "type": "string", "value": "SECTION 3", "resultText": "Please choose an item from Section 3"},
 {"probability":100, "type": "string", "value": "SECTION 4", "resultText": "Please choose an item from Section 4"},
 {"probability":100, "type": "string", "value": "SECTION 5", "resultText": "Please choose an item from Section 5"},
 {"probability":100, "type": "string", "value": "SECTION 6", "resultText": "Please choose an item from Section 6"}
];

//set the initial value on localStorage
if (localStorage.getItem('spinOptionArray') === null) {
  localStorage.setItem('spinOptionArray', JSON.stringify(before_btn_click));
}

document.getElementById('spinBtn').addEventListener('click',
  function() {

    spinOptionArray = JSON.parse(localStorage.getItem('spinOptionArray'));
    result = spinOptionArray.map(function(arrayItem) {
      return {
        probability: arrayItem['probability'] += 1,
        type: arrayItem['type'],
        value: arrayItem['value'],
        resultText: arrayItem['resultText']
      };
    })
    localStorage.setItem('spinOptionArray', JSON.stringify(result));
  })
<button class="spinBtn" id="spinBtn">SPIN</button>

SEE WORKING DEMO HERE : https://jsfiddle.net/pez256hh/
To see the effect of Local Storage, just open your browser dev tools by F12
for Firefox: Storage->Local Storage
for Google Chrome : Application -> Storage -> Local Storage


text:
Q: ERP changes visibility status of products We are facing a stupid problem. Our Magento 2 shop is connected to an external ERP system. Our ERP system sends back the status to the shop as it should, once the products are shipped and sets the order to "Complete" from "Processing".
Now, whenever this happens, our sample articles, which are set to "Not visible individually" change the status to "Catalog Search". Articles remain the same but visibility status gets changed constantly.
Does anyone of you out there understands the logic of this setting and can give a hint, how I can prevent this change?
Best regards


text:
Q: Making LoadLibrary() notice the DLLs in my project and not require their full path I am writing a web app using Azure in C# and needed to use a C++ DLL, so I added that DLL to my Visual Studio project and used
[DllImport("myDLL", CallingConvention = CallingConvention.Cdecl)]

However, this DLL starts to crash after I call it too many times.  So, I switched to using LoadLibrary() instead as described in this blog entry, which lets me unload and reload the DLL when desired:
https://blogs.msdn.microsoft.com/jonathanswift/2006/10/03/dynamically-calling-an-unmanaged-dll-from-net-c/
A drawback with this approach is that (unlike DllImport()) it does not recognize that "myDLL" is part of the Visual Studio project; it requires a directory.  This becomes problematic when I try to publish my app to Azure because it can no longer access the DLL.  Is there a good work-around for this?


text:
Q: Direct sum related to trace is zero space Let $W$ be the space of $n\times n$ matrices whose trace is zero. Find a subspace $W'$ so that $\mathbb{R}^{n\times n}=W\oplus W'$ (Here $\oplus$ is direct sum notation.)
So, I have to find $W'$ such that $W\cap W'=0$. But no clue how to find such set $W'$. It is certainly NOT matrices whose trace is non-zero (then we can not get $W\cap W'=0$).
Any help appreciated.

A: Define $f:\Bbb R^{n\times n}\to\Bbb R$ as $f(M)=Tr(M)$. This function is linear and $W=\ker f$. So $\dim W=n^2-1$. Then $W'$ can be the $1$-dimensional space generated by any matrix not in $W$.

A: $W' = \operatorname{Span}(I)$ is the subspace you are looking for. Alternatively, for any $i\leq n$, the subspace $W' = \operatorname{Span}(E_{ii})$ also works, where $E_{ii}$ is the matrix that is all $0$ except for position $(i,i)$, where it is $1$. Or mix the two matrices before you take the span. Whatever you like.

A: Hint The subspace $W$ is precisely the kernel of the nontrivial linear map $\operatorname{tr} : \Bbb R^{n \times n} \to \Bbb R$, so it has codimension $1$.

 So, any $1$-dimensional subspace $W'$ not in $W$ (so, the line $\langle A \rangle$ for any $A \not\in W$) will do. On the other hand, there is a canonical choice for $A$, namely, the identity matrix $I$, so that $W'$ is precisely the space of scalar matrices, $\lambda I$, $\lambda \in \Bbb R$. By construction the trace map $\operatorname{tr}$ is essentially the projection onto this factor in the decomposition $\Bbb R^{n \times n} = W \oplus \langle I \rangle$: More precisely, the projection is $$A \mapsto \tfrac{1}{n} \operatorname{tr} A .$$


text:
Q: Cannot read data from SQLite database in android I'm writing an application that gets the first name and last name from user and inserts them into a database, then the user can write the first name in another field and search for the last name, and the program should show the last name of the searched name in the TextView.
package ir.itstuff.dbtest;

import java.util.List;

import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity {

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

        final EditText fName = (EditText) findViewById(R.id.editText1);
        final EditText sName = (EditText) findViewById(R.id.editText2);
        final TextView tv = (TextView) findViewById(R.id.textView1);
        EditText et3 = (EditText) findViewById(R.id.editText3);
        Button btdt = (Button) findViewById(R.id.button2);
        Button save = (Button) findViewById(R.id.button1);

        final SQLiteDatabase db = openOrCreateDatabase("MyDB", MODE_PRIVATE,null);
        db.execSQL("CREATE TABLE IF NOT EXISTS MyTable(id INTEGER PRIMARY KEY AUTOINCREMENT, FirstName varchar,SecondName varchar)");

        final String first_name = fName.getText().toString();
        final String second_name = sName.getText().toString();
        final String search_name = et3.getText().toString();
        // Inserting data from inputs
        save.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                db.execSQL("INSERT INTO MyTable (FirstName,SecondName) VALUES ('"
                        + first_name + "','" + second_name + "')");
                Toast.makeText(getBaseContext(), "Data Inserted",
                        Toast.LENGTH_LONG).show();
                                db.close();

            }
        });
        btdt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                // db.execSQL("SELECT * FROM MyTable WHERE FirstName='"+search_name+"'");
                Cursor c;
                c = db.query(false, "MyTable",null, "FirstName="+search_name, null, null, null, null, null);
                while(c.moveToNext()){
                    String result = c.getString(c.getColumnIndex("LastName"));
                    tv.setText(result);
                }
                db.close();

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

It works fine till the program inserts the data to the database, but when i search for a name, the program crashes.
This is the log cat output:
04-30 08:55:14.931: E/AndroidRuntime(1848): FATAL EXCEPTION: main
04-30 08:55:14.931: E/AndroidRuntime(1848): Process: ir.itstuff.dbtest, PID: 1848
04-30 08:55:14.931: E/AndroidRuntime(1848): android.database.sqlite.SQLiteException: near "=": syntax error (code 1): , while compiling: SELECT * FROM MyTable WHERE FirstName=
04-30 08:55:14.931: E/AndroidRuntime(1848):     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at ir.itstuff.dbtest.Main$2.onClick(Main.java:60)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at android.view.View.performClick(View.java:4438)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at android.view.View$PerformClick.run(View.java:18422)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at android.os.Handler.handleCallback(Handler.java:733)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at android.os.Handler.dispatchMessage(Handler.java:95)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at android.os.Looper.loop(Looper.java:136)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at android.app.ActivityThread.main(ActivityThread.java:5017)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at java.lang.reflect.Method.invokeNative(Native Method)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at java.lang.reflect.Method.invoke(Method.java:515)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-30 08:55:14.931: E/AndroidRuntime(1848):     at dalvik.system.NativeStart.main(Native Method)

A: You are closing the database and then trying to use it again without opening it. When someone clicks on btdt, the database is closed. You need to open it again before querying by the first name.

A: As per your edit, your problem seems to be in the query:
Use ? in your query and android will parse the value in.
Something like:
final String selectQuery = "SELECT " + BACKUP_TABLE_NAME + ".*, " + BACKUPCONTACTS_TABLE_NAME + "." + BACKUPCONTACTS_ID + ", "
                + BACKUPCONTACTS_TABLE_NAME + "." + BACKUPCONTACTS_VCARD + ", " + BACKUPCONTACTS_TABLE_NAME + "." + BACKUPCONTACTS_DISPLAY_NAME
                + " FROM " + BACKUP_TABLE_NAME + ", " + BACKUPCONTACTS_TABLE_NAME
                + " WHERE " + BACKUP_TABLE_NAME + "." + BACKUP_ID + " = " + BACKUPCONTACTS_TABLE_NAME+ "." + BACKUPCONTACTS_ID_BACKUP_FK
                + " AND " + BACKUP_TABLE_NAME + "." + BACKUP_ID + " = ?";

        final Cursor cursor = db.rawQuery(selectQuery, new String[]{String.valueOf(id)});

So, in your case it will be:
String query = "SELECT * FROM MyTable WHERE FirstName " + " = ? "

Cursor cursor = db.rawQuery(selectQuery, new String[]{search_name});

Tip: Use camel case to name your variables, and not underscores. That is the java convention. So, search_name would be renamed to searchName

A: First of all your create table query is not correct. Because SQLite does not support varchar datatype. Instead of varchar use TEXT datatype and then ,
try this  instead of your syntax to get the cursor from the table records
  c = db.query("MyTable",null,"FirstName=?",new String[]{FirstName }, null, null, null, null);


text:
Q: MySql returns different rows with the same query I'm running the next queries:
1. select * from page LIMIT 10;

2. select page.id from page LIMIT 10;

"id" is the primary key in this table. How it can be possible that MySql returns different rows?
I'm using MySql 8.19

A: In the absence of an order by clause, row order is arbitrary, but typically whatever is the most convenient for the database engine - often in the order rows are laid out on disk, or whatever rows are in cache memory, etc.
However, for queries that refer only to indexed columns, which would be the case for the id column query, databases usually perform an index only scan. Without an order by clause, such a scan would typically return rows in the order the index values are laid out on disk, not the order the rows are laid out on disk. Hence the difference.


text:
Q: Trying to "sync" 2 html tables (apply column widths) I'm having 2 tables: table1 (the "header-table", which only has 1 row with table columns) - and table2 (the "data-table", which has several rows with all the data).
table1 has widths assigned to most columns.
I'm now trying to apply the column widths from table1 to the 1st row of table2
(table1 has same width as table2).
My code is:
var tr1 = $("tr",tblHeader).eq(0); // 1st row from header-table
var tr2 = $("tr",tblData).eq(0);   // 1st row from data-table
var td2 = $("td",tr2);             // all cells from data-table

$('td',tr1).each(function(i)
{
    var td1 = $(this);                // table1 column header-cell
    var width = (td1.css('width'));   // column-width from header-table
    td1.css('width',width+"px");      // apply width to header-table-cell
    td2.eq(i).css('width',wi+"px");   // apply width to data-table-cell
});

The problem:
when setting td-padding in my css like: table td{padding:0px;} it all works nice (both tables have identical column widths).
but as soon as I'm changing padding to something like table td {padding:2px;padding-left:4px;padding-right:4px;} the data table gets screwed up. When checking the columns-widths with firebug, all columns have the same width (table1+table2) but they still look different.
Any ideas what could be wrong?

A: Why not just one table, like so:

            Name
            Age
            Country

            Mike
            26
            USA

            Peter
            27
            Great Britain

            Hans
            26
            Germany


text:
Q: How do I update my answer message coding? I am doing a coding where I need to program different math flashcards and the user has to answer them. But when answering them, the message keeps saying the same number and not updating the new numbers that it is supposed to get.
from tkinter import messagebox
from random import randint

def clicked():
    messagebox.showinfo('Rules of the Game', '1. You are going to be provided with basic arithmetic (Adding, Subtracting, Multiplying)'
    '\n2. You are going to answer them'
    '\n3. Based on the answer you gave, it will keep track of the correct and incorrect answers including how many in total you have answered')

root = Tk()
root.title('Math Flash Cards')
root.geometry('900x500')

Title = Label(root, text="Title", font=('Arial', 30))
Title.grid(row = 0, column = 4)

Rule_btn = Button(root, text="Click Here for Rules", font=('Arial'), command=clicked)
Rule_btn.grid(row = 3, column = 4)

#Create random flashcard numbers
def math_random():
    global nums
    number_1 = randint(1,10)
    number_2 = randint(1,10)

    add_1.configure(text = number_1)
    add_2.configure(text = number_2)

def answer_add():
    answers = number_1 + number_2
    if int(add_ans.get()) == answers:
        response = 'Correct ' + str(number_1) + ' + ' + str(number_2) + ' = ' + str(answers)
    elif int(add_ans.get()) != answers:
        response =  'Wrong! ' + str(number_1) + ' - ' + str(number_2) + ' = ' + str(answers)
    answer_message.config(text = response)
    add_ans.delete(0, 'end')
    math_random()

global nums
number_1 = randint(1,10)
number_2 = randint(1,10)

global add_1
global add_2
add_1 = Label(root, text='+', font=('Arial', 20))
add_2 = Label(root, text='+', font=('Arial', 20))
math_operator = Label(root, text='+', font=('Arial', 20))

add_1.grid(row = 5, column = 3)
math_operator.grid(row = 5, column = 4)
add_2.grid(row = 5, column = 5)

add_1.configure(text = number_1)
add_2.configure(text = number_2)

global add_ans
add_ans = Entry(root, font = ('Arial', 14))
add_ans.grid(row = 7, column = 4)
add_ans_btn = Button(root, text ='Click', font = ('Arial'), command= answer_add)
add_ans_btn.grid(row = 7, column = 5)

global answer_message
answer_message = Label(root, text='Type you answer with the provided space above', font=('Arial'))
answer_message.grid(row = 10, column = 4)

What should I do to make it update? I kept making changes to the code, but it is not changing when the numbers are changing.


text:
Q: How to individually assign a value from console to an array I am making a program that continually prompts the user to input numbers which are then stored in an array until the user provides a given response (E.g "continue"), where the program then displays the array in terminal.
I have been debugging my program and it is setting all values within the array to the last value from console input.
How can I stop the counter from going all the way to the max for that array and instead step through the array 1 by 1 and input a new value from console each time
for (int i = 0; i < inputArray.GetLength(0); i++)
inputArray[i] = Convert.ToDouble(input);
goto STARTOVER;

Here is my main code:
using System;

namespace Task3
{
    class MainClass
{
    public static void Main(string[] args)
    {
        double[] inputArray = new double[40];

        Console.WriteLine("Begin");
        while (true)
        {
            STARTOVER:
            var input = Console.ReadLine();
            if (input.Equals("exit", StringComparison.OrdinalIgnoreCase))
            {
                break;
            }

            if (input.Equals("continue",StringComparison.OrdinalIgnoreCase))
            {
                goto DISPLAY;
            }

            else
            {
                    for (int i = 0; i < inputArray.GetLength(0); i++)
                    inputArray[i] = Convert.ToDouble(input);
                    goto STARTOVER;
            }

        }
        DISPLAY:
        for (int i = 0; i < inputArray.GetLength(0); i++)
        {
            Console.Write("{0} ", inputArray[i]);
            Console.WriteLine();
        }

    }
}
}

From my understanding, I shouldn't use goto where possible but I cannot find an alternative to get the program to go back to where "STARTOVER:" is.

A: Aside from goto, which is pretty bad, the problem is the code loops through the entire array on every entry. It needs an integer variable that starts at 0 and increments with each new input, so it can set just that position each time.
public static void Main(string[] args)
{
    Console.WriteLine("Begin");
    double[] inputArray = new double[40];

    int inputCount = 0;
    var input = Console.ReadLine();

    while (!input.Equals("exit", StringComparison.OrdinalIgnoreCase)
        && !input.Equals("continue", StringComparison.OrdinalIgnoreCase)
        && inputCount < inputArray.Length)
    {
        inputArray[inputCount++] = Convert.ToDouble(input);
        input = Console.ReadLine();
    }

    for (int i = 0; i < inputCount; i++)
    {
        Console.Write("{0} ", inputArray[i]);
        Console.WriteLine();
    }
}

Even better to use a List:
public static void Main(string[] args)
{
    Console.WriteLine("Begin");
    var data = new List<double>;
    var input = Console.ReadLine();

    while (!input.Equals("exit", StringComparison.OrdinalIgnoreCase)
        && !input.Equals("continue", StringComparison.OrdinalIgnoreCase))
    {
        data.Add(double.Parse((input));
        input = Console.ReadLine();
    }

    for (double d in data)
    {
        Console.WriteLine(d);
    }
}

A: The key to repeatedly requesting input while a condition is met, is using a while loop
while(CurrentCondition != PassCondition)
{
   //do something, in this case ask for user input
}

a good idea would be to create methods, and call these methods where the goto methods are e.g
    public static double[] inputArray = new double[40];
    public static string input;
    public static int idx = 0;

    static void Main(string[] args)
    {
        GetInput();
        Console.Read();
    }

    public static void GetInput()
    {
        Console.Write("enter a number to add to the array or 'continue' to display the array: ");
        input = Console.ReadLine();

        while (!CheckInput(input))
        {
            Console.Write("enter a number to add to the array or 'continue' to display the array: ");
            input = Console.ReadLine();
        }
    }

    public static bool CheckInput(string _input)
    {
        bool Continue = false;

        if (input == "continue")
        {
            PrintArray();
            Continue = true;
        }

        else
        {
            inputArray[idx] = double.Parse(_input);
            idx++;
            Continue = false;
        }

        return Continue;
    }

    public static void PrintArray()
    {
        for(int i = 0; i < inputArray.Length - 1; i++)
        {
            Console.WriteLine(inputArray[i]);
        }
    }
}


text:
Q: Azure Resource Manager - Get publish username and password of an AzureWebApp I can get the publish settings use the following method:
$website = Get-AzureWebSite -Name $webSiteName

$websitePreProd = ($website | ?{ $_.Name -like "*Preprod)" })

$siteProperties = $websitePreProd.SiteProperties.Properties

$url = ($siteProperties | ?{ $_.Name -eq "RepositoryURI" }).Value.ToString() + "/MsDeploy.axd"

$userName = ($siteProperties | ?{ $_.Name -eq "PublishingUsername" }).Value

$pw = ($siteProperties | ?{ $_.Name -eq "PublishingPassword" }).Value

But ideally I want to use ARM via:
$existingSlot = Get-AzureWebApp -Name $websiteName -ResourceGroupName $resourcegroup -Slot "PreProd" -ErrorAction SilentlyContinue

How do I get URL, username and password using ARM?

A: @juvchan's answer will work. Here in an alternative for completeness:
$res = Invoke-AzureRmResourceAction -ResourceGroupName <RG name> -ResourceType Microsoft.Web/sites/config -ResourceName <sitename>/publishingcredentials -Action list -ApiVersion 2015-08-01 -Force
$userName = $res.Properties.PublishingUserName
$pwd = $res.Properties.PublishingPassword

A: You can try the simple script below to solve your problem.
 I assume you are trying to get the MS-Deploy publish profile.
Note: You should install the latest Azure PowerShell to be able to use the new Azure RM commands.
$webAppSlot = Get-AzureRMWebAppSlot -ResourceGroupName <Res-Grp-Name> -Name <webAppName> -Slot <slotName>

$pp = Get-AzureRMWebAppSlotPublishingProfile -WebApp $webAppSlot -OutputFile <OutputFileFullPathName>

[xml]$ppXml = Get-Content <OutputFileFullPathName>

# MSDeploy Publish Profile
$publishUrl = $ppXml.publishData.FirstChild.publishUrl
$userName = $ppXml.publishData.FirstChild.userName
$userPWD = $ppXml.publishData.FirstChild.userPWD


text:
Q: Ho do get best features with Spark LinearSVC model? I am trying to use ChiSqSelector to determine the best features for a Spark 2.2 LSVCModel, thus:
import org.apache.spark.ml.feature.ChiSqSelector
val chiSelector = new ChiSqSelector().setNumTopFeatures(5).
   setFeaturesCol("features").
   setLabelCol("label").setOutputCol("selectedFeatures")

val pipeline = new Pipeline().setStages(Array(labelIndexer, monthIndexer, hashingTF
   , idf, va, featureIndexer,  chiSelector, lsvc, labelConverter))

val model = pipeline.fit(training)
val importantFeatures = model.selectedFeatures

import org.apache.spark.ml.classification.LinearSVCModel
val LSVCModel= model.stages(6).asInstanceOf[org.apache.spark.ml.classification.
   LinearSVCModel]

val importantFeatures = LSVCModel.selectedFeatures

which gives the error:
<console>:180: error: value selectedFeatures is not a member of
org.apache.spark.ml.classification.LinearSVCModel
   val importantFeatures = LSVCModel.selectedFeatures

Is it possible to use ChiSqSelector with this model? If not, is there an alternative?

A: The Linear SVC will not do any feature selection. You should extract the ChiSqSelectorModel from the pipeline, not the LinearSVCModel.
import org.apache.spark.ml.feature.ChiSqSelectorModel
val chiSqModel = model.stages(6).asInstanceOf[ChiSqSelectorModel]

val importantFeatures = chiSqModel.selectedFeatures


text:
Q: Nested for loop and if condition pandas replacement I have two different pandas data frames where in the first data frame (price), I have two columns. The first column named value has some values in it and the second column amount has the available amount for each price. The second data frame (bins) has as index some price intervals which are produced from the price data frame. For each row of the price data frame I check each row of the value column to find the interval that it belongs from the bins data frame and if the value is in an interval I assign the available amount in the bins data frame. If another value is again in the same interval I sum up these amounts in the group_bins data frame.
import pandas as pd

bins = pd.DataFrame({
    'value': [1, 2, 5, 7, 8, 16, 20, 3, 9, 11, 35, 12, 54, 33, 3, 22, 23]
})

price = pd.DataFrame({
    'value': [2, 5, 7, 8, 16, 20, 3, 9, 11, 2.5, 3.4],
    'amount': [50, 112, 130, 157, 146, 148, 300, 124, 151, 100, 32]
})

bins['bins'] = pd.qcut(bins['value'], 12)
group_bins = bins.groupby(['bins']).sum()
group_bins['amount'] = 0
del group_bins['value']

for j in range(price.shape[0]):
    for i in range(group_bins.shape[0]):
        if price.loc[j, 'value'] in group_bins.index[i]:
            group_bins.loc[group_bins.index[i], 'amount'] += price.loc[j, 'amount']

            break

Expected Result:
                 amount
bins
(0.999, 2.333]        50
(2.333, 3.0]         400
(3.0, 5.0]           144
(5.0, 7.333]         130
(7.333, 8.667]       157
(8.667, 11.0]        275
(11.0, 13.333]         0
(13.333, 18.667]     146
(18.667, 22.0]       148
(22.0, 26.333]         0
(26.333, 34.333]       0
(34.333, 54.0]         0

My problem is that I have 100k data and all this process takes too long to finish.
Is there any elegant and much faster way to replace these nested for loops and the if condition?
The expected result is the final column in the group_bins amount column. Any help would be much appreciated! Thank you.

A: If you use for loop on a dataframe, you are doing it wrong 99% of the times. Try this instead:
bins = pd.DataFrame({
    'value': [1, 2, 5, 7, 8, 16, 20, 3, 9, 11, 35, 12, 54, 33, 3, 22, 23]
})
bins['bins'] = pd.qcut(bins['value'], 12)

price = pd.DataFrame({
    'value': [2, 5, 7, 8, 16, 20, 3, 9, 11],
    'amount': [50, 112, 130, 157, 146, 148, 300, 124, 151]
})

price.merge(bins, how='left', on='value') \
    .groupby('bins') \
    .agg({'amount': 'sum'})

Result:
                  amount
bins
(0.999, 2.333]        50
(2.333, 3.0]         600
(3.0, 5.0]           112
(5.0, 7.333]         130
(7.333, 8.667]       157
(8.667, 11.0]        275
(11.0, 13.333]         0
(13.333, 18.667]     146
(18.667, 22.0]       148
(22.0, 26.333]         0
(26.333, 34.333]       0
(34.333, 54.0]         0


text:
Q: Show Graphics on top of ParametricPlot3D I want to show a curved trajectory in 3D with a small Sphere/Point denoting a specific point. Therefore, the Sphere/Point needs to be always visualised "in front" of the curve; instead, I get exactly the opposite, even though I Show the sphere afterwards:
Show[ParametricPlot3D[{0, Cos[4 t], Sin[4 t]}, {t, 0, 2}],
 Graphics3D[{Red, PointSize[0.02], Opacity[1], Point[{0, 1, 0}]},
  Boxed -> False],
 Boxed -> False, Axes -> False, PlotRange -> Full]

Setting max opacity didn't help, as you can see.

Update: Using Ball does not solve the problem in all orientations:
Show[ParametricPlot3D[{0, Cos[4 t], Sin[4 t]}, {t, 0, 2}],
 Graphics3D[{Red, Ball[{0, 1, 0}, 0.05]}, Boxed -> False],
 Boxed -> False, Axes -> False, PlotRange -> Full,
 ViewAngle -> 0.05441036690859109`,
 ViewCenter -> {{0.5`, 0.5`,
    0.5`}, {-0.4060312376176072`, -0.06631185777677895`}},
 ViewPoint -> {1.2849282470004935`, -2.9518747023382326`,
   1.0418229896464233`},
 ViewVertical -> {0.8518775666674835`, -0.15812469380775868`,
   0.49930070360143686`}]

The inaccurate intersection is shown simply by using the ViewPoint setting, but I zoomed in to highlight the problem.

A: You mean you want even the part of the point/ball that is behind the curve to be drawn in front?  The normal 3D model won't do that, I'm pretty sure.  You could have layers, such as you get with Overlay, but you have to take care that all the visualization parameters agree (ViewPoint, PlotRange, ImageSize, etc.):
Overlay[{
  ParametricPlot3D[{0, Cos[4 t], Sin[4 t]}, {t, 0, 2},
   Boxed -> False, Axes -> False, PlotRange -> 1],
  Graphics3D[{Red, Ball[{0, 1, 0}, 0.05]}, Boxed -> False,
   Boxed -> False, Axes -> False, PlotRange -> 1]
  }]

Note that the output is not a Graphics3DBox[..] and cannot be rotated.
I feel that the OP's version of @MarcoB's suggestion is the best way, in which the curve passes through the ball in a natural way:
Show[
 ParametricPlot3D[{0, Cos[4 t], Sin[4 t]}, {t, 0, 2}],
 Graphics3D[{Red, Ball[{0, 1, 0}, 0.05]}, Boxed -> False],
 Boxed -> False, Axes -> False, PlotRange -> Full]

I think I understand the comment: The intersection of the Line and the Ball is not shown accurately from all view points.
Things seem to be displayed more accurately if the graphics elements all have the same dimension.  If we use surface elements for both the line and point, namely Tube and Ball, the displayed graphics perhaps look better.
Show[ParametricPlot3D[{0, Cos[4 t], Sin[4 t]}, {t, 0, 2},
  PlotStyle -> Tube[0.01]],
 Graphics3D[{Red, Ball[{0, 1, 0}, 0.05]}, Boxed -> False],
 Boxed -> False, Axes -> False, PlotRange -> Full]


text:
Q: Group records in ranges I have a set of 'followed' rows with the same value and I want to group them together to make a from and to. The proposed solution is usually to use ROW_NUMBER() and then group, but I find that there are cases that do not work, with an example it will be better understood:
WITH
CTE AS
    (SELECT *
     FROM (VALUES ('A', 37, ''),
                  ('A', 38, ''),
                  ('A', 39, ''),
                  ('A', 40, ''),
                  ('A', 41, ''),
                  ('A', 42, ''),
                  ('A', 43, ''),
                  ('B', 44, '=> error Grupo 43'),
                  ('B', 45, '=> error Grupo 43'),
                  ('C', 46, ''),
                  ('C', 47, ''),
                  ('B', 48, ''),
                  ('B', 49, ''),
                  ('B', 50, ''),
                  ('A', 51, '=> error Grupo 43'),
                  ('A', 52, '=> error Grupo 43'),
                  ('A', 53, '=> error Grupo 43')) DATA (LETRA, DESDE, ERROR) )
SELECT *,
       ROW_NUMBER() OVER (PARTITION BY LETRA ORDER BY DESDE) AS rn,
       DESDE - ROW_NUMBER() OVER (PARTITION BY LETRA ORDER BY DESDE) AS Grupo
FROM CTE
ORDER BY SINCE;

Is there a way to 'group' the records correctly?
a greeting

A: This is a gap and island problem and your calculus with DESDE - ROW_NUMBER() is correct, but you should further group by the letter instead of just this rest result.
WITH
CTE AS
    (SELECT *
     FROM (VALUES ('A', 37, ''),
                  ('A', 38, ''),
                  ('A', 39, ''),
                  ('A', 40, ''),
                  ('A', 41, ''),
                  ('A', 42, ''),
                  ('A', 43, ''),
                  ('B', 44, '=> error Grupo 43'),
                  ('B', 45, '=> error Grupo 43'),
                  ('C', 46, ''),
                  ('C', 47, ''),
                  ('B', 48, ''),
                  ('B', 49, ''),
                  ('B', 50, ''),
                  ('A', 51, '=> error Grupo 43'),
                  ('A', 52, '=> error Grupo 43'),
                  ('A', 53, '=> error Grupo 43')) DATA (LETRA, DESDE, ERROR))
,
Groups AS
(
    SELECT
        C.*,
        GroupID = C.DESDE - ROW_NUMBER() OVER (PARTITION BY LETRA ORDER BY C.DESDE)
    FROM
        CTE AS C
)
SELECT
    C.LETRA,
    Desde = MIN(C.DESDE),
    Hasta = MAX(C.DESDE)
FROM
    Groups AS C
GROUP BY
    C.LETRA,
    C.GroupID

Result:
LETRA   Desde   Hasta
A       37      43
A       51      53
B       44      45
B       48      50
C       46      47

A: Your code should work if you use aggregation:
SELECT MIN(DESDE), MAX(DESDE), ERROR
FROM (SELECT CTE.*,
             ROW_NUMBER() OVER (PARTITION BY LETRA ORDER BY DESDE) AS rn,
             DESDE - ROW_NUMBER() OVER (PARTITION BY LETRA ORDER BY DESDE) AS Grupo
      FROM CTE
     ) x
GROUP BY Grupo, ERROR;


text:
Q: JWT Invalid Token, React / Node JS / Reduce / Navigate I have a problem I need you to help me I'm blocked, I'm currently training in react node js. I have a problem with my TOKEN, I have the message invalid Token, moreover I have a 401 error. Can you help me?
Thank you very much, I show you my codes.
userRoutes.JS ( backend )
    userRouter.put(
  '/profile',
  isAuth,
  expressAsyncHandler(async (req, res) => {
    const user = await User.findById(req.user._id);
    if (user) {
      user.name = req.body.name || user.name;
      user.email = req.body.email || user.email;
      if (req.body.password) {
        user.password = bcrypt.hashSync(req.body.password, 8);
      }

      const updatedUser = await user.save();
      res.send({
        _id: updatedUser._id,
        name: updatedUser.name,
        email: updatedUser.email,
        phone: updatedUser.phone,
        fb: updatedUser.fb,
        insta: updatedUser,
        isAdmin: updatedUser.isAdmin,
        token: generateToken(updatedUser),
      });
    } else {
      res.status(404).send({ message: 'User not found' });
    }
  })
);

Profile.JS
import React, { useContext, useReducer, useState } from 'react';
import { Helmet } from 'react-helmet-async';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import { Store } from '../Store';
import { toast } from 'react-toastify';
import { getError } from '../utils';
import axios from 'axios';

const reducer = (state, action) => {
  switch (action.type) {
    case 'UPDATE_REQUEST':
      return { ...state, loadingUpdate: true };
    case 'UPDATE_SUCCESS':
      return { ...state, loadingUpdate: false };
    case 'UPDATE_FAIL':
      return { ...state, loadingUpdate: false };

    default:
      return state;
  }
};

export default function ProfileScreen() {
  const { state, dispatch: ctxDispatch } = useContext(Store);
  const { userInfo } = state;
  const [name, setName] = useState(userInfo.name);
  const [email, setEmail] = useState(userInfo.email);
  const [phone, setPhone] = useState(userInfo.phone);
  const [fb, setFb] = useState(userInfo.fb);
  const [insta, setInsta] = useState(userInfo.insta);
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');

  const [{ loadingUpdate }, dispatch] = useReducer(reducer, {
    loadingUpdate: false,
  });

  const submitHandler = async (e) => {
    e.preventDefault();
    try {
      const { data } = await axios.put(
        '/api/users/profile',
        {
          name,
          email,
          password,
          phone,
          fb,
          insta,
        },
        {
          headers: { Authorization: `Bearer ${userInfo.token}` },
        }
      );
      dispatch({
        type: 'UPDATE_SUCCESS',
      });
      ctxDispatch({ type: 'USER_SIGNIN', payload: data });
      localStorage.setItem('userInfo', JSON.stringify(data));
      toast.success('User updated successfully');
    } catch (err) {
      dispatch({
        type: 'FETCH_FAIL',
      });
      toast.error(getError(err));
    }
  };

  return (

      <Helmet>
        <title>User Profile</title>
      </Helmet>

User Profile

      <form onSubmit={submitHandler}>
        <Form.Group className="mb-3" controlId="name">
          <Form.Label>Name</Form.Label>
          <Form.Control
            value={name}
            onChange={(e) => setName(e.target.value)}
            required
          />
        </Form.Group>
        <Form.Group className="mb-3" controlId="name">
          <Form.Label>Email</Form.Label>
          <Form.Control
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
          />
        </Form.Group>
        <Form.Group className="mb-3" controlId="password">
          <Form.Label>Password</Form.Label>
          <Form.Control
            type="password"
            onChange={(e) => setPassword(e.target.value)}
          />
        </Form.Group>
        <Form.Group className="mb-3" controlId="password">
          <Form.Label>Confirm Password</Form.Label>
          <Form.Control
            type="password"
            onChange={(e) => setConfirmPassword(e.target.value)}
          />
        </Form.Group>
        <Form.Group className="mb-3" controlId="phone">
          <Form.Label>Phone</Form.Label>
          <Form.Control
            type="phone"
            value={phone}
            onChange={(e) => setPhone(e.target.value)}
            required
          />
        </Form.Group>
        <Form.Group className="mb-3" controlId="fb">
          <Form.Label>Fb</Form.Label>
          <Form.Control
            type="fb"
            value={fb}
            onChange={(e) => setFb(e.target.value)}
            required
          />
        </Form.Group>
        <Form.Group className="mb-3" controlId="insta">
          <Form.Label>Insta</Form.Label>
          <Form.Control
            type="insta"
            value={insta}
            onChange={(e) => setInsta(e.target.value)}
            required
          />
        </Form.Group>

          <Button type="submit">Update</Button>

      </form>

  );
}

Utils.JS
import jwt from 'jsonwebtoken';
import mg from 'mailgun-js';

export const generateToken = (user) => {
  return jwt.sign(
    {
      _id: user._id,
      name: user.name,
      email: user.email,
      phone: user.phone,
      fb: user.fb,
      insta: user.insta,
      isAdmin: user.isAdmin,
    },
    process.env.JWT_SECRET,
    {
      expiresIn: '30d',
    }
  );
};

export default function authHeader() {
  const user = JSON.parse(localStorage.getItem('user'));
  if (user && user.accessToken) {
    return { Authorization: 'Bearer ' + user.accessToken };
  } else {
    return {};
  }
}

export const isAuth = (req, res, next) => {
  const authorization = req.headers.authorization;
  if (authorization) {
    const token = authorization.slice(authorization.length); // Bearer XXXXXX
    jwt.verify(token, process.env.JWT_SECRET, (err, decode) => {
      if (err) {
        res.status(401).send({ message: 'Invalid Token' });
        console.log;
      } else {
        req.user = decode;
        next();
      }
    });
  } else {
    res.status(401).send({ message: 'No Token' });
  }
};

export const isAdmin = (req, res, next) => {
  if (req.user && req.user.isAdmin) {
    next();
  } else {
    res.status(401).send({ message: 'Invalid Admin Token' });
  }
};

export const mailgun = () =>
  mg({
    apiKey: process.env.MAILGUN_API_KEY,
    domain: process.env.MAILGUN_DOMIAN,
  });

export const payOrderEmailTemplate = (order) => {
  return `
Thanks for shopping with us

  Hi ${order.user.name},

We have finished processing your order.

[Order ${order._id}] (${order.createdAt.toString().substring(0, 10)})

  Product
  Quantity
  Price

  ${order.orderItems
    .map(
      (item) => `

    ${item.name}
    ${item.quantity}
     $${item.price.toFixed(2)}

  `
    )
    .join('\n')}

  Items Price:
   $${order.itemsPrice.toFixed(2)}

  Shipping Price:
   $${order.shippingPrice.toFixed(2)}

  Total Price:
   $${order.totalPrice.toFixed(2)}

  Payment Method:
  ${order.paymentMethod}

Shipping address

  ${order.shippingAddress.fullName},

  ${order.shippingAddress.address},

  ${order.shippingAddress.city},

  ${order.shippingAddress.country},

  ${order.shippingAddress.postalCode}

  Thanks for shopping with us.

  `;
};

Thanks you all


text:
Q: The member is not recognized or is not accessible In my WPF I have
public class AttachedColumnBehavior
{

    public static readonly DependencyProperty MappedValuesProperty =
            DependencyProperty.RegisterAttached("MappedValues",
            typeof(MappedValueCollection),
            typeof(AttachedColumnBehavior),
            new UIPropertyMetadata(null, OnMappedValuesPropertyChanged));

}

   public static MappedValueCollection GetMappedValues(DependencyObject dataGrid)
    {
        return (MappedValueCollection)dataGrid.GetValue(MappedValuesProperty);
    }

    public static void SetMappedValues(DependencyObject dataGrid, MappedValueCollection value)
    {
        dataGrid.SetValue(MappedValuesProperty, value);
    }

and in my Xaml I have
<DataGrid ItemsSource="{Binding MyCollectoin}" x:Name="myGrid"

                  loc:AttachedColumnBehavior.MappedValues="{Binding MyCollectionValues}"
                  AutoGenerateColumns="False">
            <DataGrid.Columns>

But I am getting The Member MappedValues is not recognized or is not acessible error.


text:
Q: Are non-linear connections with linear holonomy, linear? Let $\pi\colon TM\to M$ be the tangent bundle of a differentiable manifold, let $E=TM\backslash 0$ be the slit tangent bundle, and let $V_eE$ be the kernel of $\pi_*$ at $e\in E$. The set $VE=\cup_{e\in E} V_eE$ is the vertical bundle. A non-linear connection is a splitting $TE=VE\oplus HE$, where $HE$ is the horizontal bundle. Every vector $v\in TM$ can be lifted to a vector $V\in HE$, such that $\pi_*(V)=v$. Similarly one can lift closed curves of $M$ starting at $p$ to (non-)closed curves on $E$. For every closed curve $\gamma$ this gives a map $\Gamma:T_pM\to T_pM$. If the connection is linear it is well known that this holonomy is a linear map. Is the converse true?
In coordinates,
if $\{x^i\}$ are coordinates on $M$ then on TM we have coordinates $\{x^i,y^i\}$ and the basis of $HE$ obtained lifting the holonomic basis is
$$
\frac{\partial}{\partial x^i}-N_i^j(x,y) \frac{\partial}{\partial y^j}.
$$
The coefficients $N^i_j$ are said to be the coefficients of the non-linear connection, so I am asking if they are linear in $y$ under the assumpton of linear holonomy.

A: The answer to your literal question is 'no', you can even have the holonomy be trivial (in which case, it is certainly linear) and yet the connection not be linear.  This is a local
question, so you can construct examples as follows:  Take $M=\mathbb{R}^n$ with standard coordinates $x^i$ and let $y^i = \mathrm{d}x^i:TM\to\mathbb{R}$ be the corresponding functions on $TM$, so that $(x^i, y^i)$ define coordinates on $TM$.  Now take any $n$ smooth functions $F^i:TM\to\mathbb{R}$ with the property that
$$
\mathrm{d} x^1\wedge\cdots\wedge \mathrm{d} x^n\wedge \mathrm{d} F^1\wedge\cdots\wedge \mathrm{d}F^n \not=0,
$$
which implies that the kernel subbundle of the map $F = (F^i):TM\to\mathbb{R}^n$ is spanned by vector fields of the form
$$
X_i = \frac{\partial\ }{\partial x^i} + N_i^j(x,y)\frac{\partial\ }{\partial y^j}.
$$
These then define a connection on $TM$ that is, in general, nonlinear.  However, because the horizontal lifts of curves are given by lifting a curve in $M$ to a single level surface of $F$, all horizontal lifts of closed curves are closed.
Thus, the holonomy is trivial, but the connection need not be linear.


text:
Q: VUE- Eventlistener within directive can't read function defined in methods I want my function defined in 'methods' to be excuted when
my element is clicked. However, my eventlistener do something only when I use an anonymouse function like
el.addEventListener('click' function() {console.log('hi'))

When I set a function in methods, it spits error messages saying

vue.js?3de6:634 [Vue warn]: Error in directive myDirective bind hook:
  "ReferenceError: sizechange is not defined"
found in
--->  at /Users/soonkpaik/Downloads/Start 2/src/App.vue

  my code is as below.

<template>

Directives Exercise!

</template>

What did I do wrong??
Thank you in advance.

A: The issue here is sizechange() function is not accessible directly inside bind hook function directly. You will need to refer to the current vnode context like:
export default {
  directives: {
    myDirective: {
      bind(el, binding, vnode) {

        // Your logic here...

        var vm = vnode.context;
        el.addEventListener('click', vm.sizechange) // This works fine now
      }
    }
  },
  methods: {
    sizechange() {
      console.log('hi')
    }
  },
}


text:
Q: Ebean ManyToMany to same entity I'm trying to map a many to many releationship where every user has a set of friends, which also are users. In the database table this is solved using a assosiation table called user_friend. The user_friend table has two columns for user1 and user2 that is foreign keys to the user id in the user table.
The optimal solution would be to not create a java ebean model for the user_friend table, but let the user model have a set of users, where the current user is either user1 or user2 in the user_friend table. The mapping would then have to refer to the two columns in the user_friend table somehow...
Is this possible?
Edited: SQL for 1.sql added
CREATE TABLE User (
id bigint(20) NOT NULL AUTO_INCREMENT,
email varchar2(255) NOT NULL UNIQUE,
password varchar2(255) NOT NULL,
name varchar2(255) NOT NULL,
PRIMARY KEY (id)
);

CREATE TABLE User_friend (
id bigint(20) NOT NULL AUTO_INCREMENT,
user1 bigint(20) NOT NULL,
user2 bigint(20) NOT NULL,
sent TIMESTAMP NOT NULL,
accepted TIMESTAMP,
PRIMARY KEY (ID),
FOREIGN KEY(user1) REFERENCES User(id),
FOREIGN KEY(user2) REFERENCES User(id)
);

The thing is, want every user instance to have a set of users that he is linked to by being either user1 or user2.

A: It sounds like this is exactly how Ebean has set it up for you:
user_friend
   user1      user2
   (user_id)  (user_id)

Why do you want to change the ManyToMany relationship?  Could you provide us with the relevant piece of your 1.sql file in 'conf/evolutions/default'?
Update:
If your Java code looks like this:
@ManyToMany
public Set<User> friends = new HashSet<User>();

You should be able to get a set of friends by referencing user.friends.
The issue is it looks like you want to have additional fields in the User_friend table (sent, accepted).  Because of this you need to create a new model, UserFriend, that exposes these fields.


text:
Q: How to implement logout functionality in react native? As i'm trying to develop an app in react native , i want to implement logout functionality.Now i found a problem that for every user who is logging, the name,and details appearing in their profile is same for each user.I'm using asyncstorage for setting unique id.Now i'm trying to unset this session using
Asyncstorage.removeItem('key_uuid').Do i need to write this in a separate js file?I don't know actually  where to give this code in my project.Sorry can anybody help me to figure this out?

A: It is simple implementation, on login you need to save some logged in user information as to check weather a user is logged in or not.
You canprovide logout button anywhere in the app, and on clk of that you can clear your asyncStorage or remove only user info from storage.
And when user opens your app you can check user in asyncstorage.


text:
Q: Java library for creating straight skeleton? I have as an input a 2D polygon with holes, and I need to find it's straight skeleton, like in the picture:

(source: cgal.org)
Maybe there is a good Java library for it?
And if not, can you point me to the good explanation of the algorithm, so I could implement it myself? (I haven't found good resources on Google)

A: I wrote this a little while back. Not sure if it's robust enough.
https://github.com/twak/campskeleton
(edited for 2018...)

A: See http://www.sable.mcgill.ca/~dbelan2/roofs/roofs.html which contains an applet.

A: You may be able to use the JTS Topology Suite.  It is a very capable library that I've used on a number of projects - never for straight skeleton, but it may be possible.

A: Edit:
Ah.  I see that "Straight Skeleton" is a technical term.  The wikipedia article references several algorithms.  Have you looked at those?

As I understand it, you have a (convex?) polygon.  From it, you subtract 1 or more (potentially non-convex) polygons. You want to turn the result into a set of polygons without holes.  Are there extra rules that you're trying to apply?
I have a hard time coming up with a set of rules from the example that you provided.  The outer polygons are non-convex; so it doesn't seem like you're trying to find a convex set to represent the result (which is a relatively common task).
If you could use the breakdown shown below, the algorithm is pretty simple.  Can you clarify?

A: Can I ask u what is your purpose for finding Straight skeleton? Is it personal or commercial? I would be interested in knowing how you r using it to solve real time problems? I do have a java library that does that. My algorithm is listed here http://web.stcloudstate.edu/rsarnath/skeleton/definition.htm


text:
Q: Datepicker agenda I want to add calandar datepicker calendar
is it possible ?
how?
for example :
http://fullcalendar.io/js/fullcalendar-2.6.1/demos/agenda-views.html
thank you

A: You can quite easily implement fullCalendar in your Angular project by wrapping it in a custom directive, you could also try out ui-calendar which does just that.


text:
Q: Python Class to Return a Dictionary I researched online and still am having a hard time understanding how to create classes. The examples in SoloLearn, DataCamp, and other sites often use the Person / Employee example, such as this one:
class Person:

    def __init__(self, first, last):
        self.firstname = first
        self.lastname = last

    def Name(self):
        return self.firstname + " " + self.lastname

class Employee(Person):

    def __init__(self, first, last, staffnum):
        Person.__init__(self,first, last)
        self.staffnumber = staffnum

    def GetEmployee(self):
        return self.Name() + ", " +  self.staffnumber

x = Person("Marge", "Simpson")
y = Employee("Homer", "Simpson", "1007")

print(x.Name())
print(y.GetEmployee())

I am trying to create an example class that returns a dictionary by modifying it slightly. Here is the code:
 class Place:

    def __init__(self, country, province):
        self.country= country
        self.province = province

    def CountryState(self):
        return {
            'Province': self.province,
            'Country': self.country
            }

class Location(Place):

    def __init__(self, country, province, city, street, postal):
        super(Place, self).__init__(country, province, city, street, postal)
        self.city = city
        self.street = street
        self.postal = postal

    def GetLocation(self):
        return CountryState().update({
            'City': self.city,
            'Street': self.street,
            'Postal': self.postal
            })

if __name__=="__main__":

    x = Place('United States', "California")
    y = Location("United States", "California", "Los Angeles", "Johnson Street", "90007")

    print(x.CountryState())
    print(y.GetLocation())

I get a Traceback as follows using pdb.set_trace():
Traceback (most recent call last):
  File "/home/john/Python/class-example.py", line 37, in <module>
    y = Location("United States", "California", "Los Angeles", "Johnson Street", "90007")
  File "/home/john/Python/class-example.py", line 22, in __init__
    super(Place, self).__init__(country, province, city, street, postal)
TypeError: object.__init__() takes no parameters
> /usr/lib/python3.5/idlelib/run.py(370)runcode()
-> jit = self.rpchandler.console.getvar("<<toggle-jit-stack-viewer>>")

pdb list:
365                 self.usr_exc_info = sys.exc_info()
366                 if quitting:
367                     exit()
368                 # even print a user code SystemExit exception, continue
369                 print_exception()
370  ->             jit = self.rpchandler.console.getvar("<<toggle-jit-stack-viewer>>")
371                 if jit:
372                     self.rpchandler.interp.open_remote_stack_viewer()
373             else:
374                 flush_stdout()
375

I haven't been able to get __init__ to accept parameters. Please let me know what I am missing so I can return the dictionary from these lines:
print(x.CountryState())
print(y.GetLocation())

{ 'Country': 'United States', 'State': 'California' }

{ 'Country': 'United States', 'City': 'Los Angeles', 'Street':'Johnson Street', 'Postal Code': '90007'}

A: In the Location(Place) class you are calling
super(Place, self).__init__(country, province, city, street, postal)

You should call the super-class of the Location class. Now, you are calling the super class of Place. Since Place has no declared superclass, it derives from object class (which is the parent of all classes), and you are calling the object constructor, which takes no parameters.
Also, even if you fix that, you are giving more parameters than Place takes. The correct form would be
super(Location, self).__init__(country, province)


text:
Q: 404 on setting an association resource My first experiment with Spring Data Rest fails. I've taken the "Getting Started" and modified it a bit to create two entities that have a many-to-one relationships. The entities are Book and Shelve and many books can share a shelve.
The Shelve entity looks like this:
package hello;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Shelve
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private int length;

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }
}

The Book refers to it:
package hello;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
public class Book
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String title;

    @ManyToOne
    private Shelve shelve;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Shelve getShelve() {
        return shelve;
    }

    public void setShelve(Shelve shelve) {
        this.shelve = shelve;
    }
}

The full project is available here in GitHub.
Now I can add a Shelve:
curl -i -X POST -H "Content-Type:application/json" -d "{  \"length\" : \"30\" }" http://localhost:8080/shelves
HTTP/1.1 201
Location: http://localhost:8080/shelves/1
Content-Type: application/hal+json;charset=UTF-8
Transfer-Encoding: chunked
Date: Thu, 17 Nov 2016 16:05:02 GMT

{
  "length" : 30,
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/shelves/1"
    },
    "shelve" : {
      "href" : "http://localhost:8080/shelves/1"
    }
  }
}

Then a book:
curl -i -X POST -H "Content-Type:application/json" -d "{  \"title\" : \"The Battle of Life\" }" http://localhost:8080/books
HTTP/1.1 201
Location: http://localhost:8080/books/1
Content-Type: application/hal+json;charset=UTF-8
Transfer-Encoding: chunked
Date: Thu, 17 Nov 2016 16:05:02 GMT

{
  "title" : "The Battle of Life",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/books/1"
    },
    "book" : {
      "href" : "http://localhost:8080/books/1"
    },
    "shelve" : {
      "href" : "http://localhost:8080/books/1/shelve"
    }
  }
}

Then I try to put the book on the shelve, but that fails:
curl -i -X PUT -H "ContentType: text/uri-list" -d "http://localhost:8080/shelves/1" http://localhost:8080/books/1/shelve
HTTP/1.1 404
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Thu, 17 Nov 2016 16:05:02 GMT

{"timestamp":1479398702523,"status":404,"error":"Not Found","message":"No message available","path":"/books/1/shelve"}

Any idea what's going wrong here?

A: As pointed out by Oliver Gierke on the related JIRA ticket, the issue is in the curl request. It should have a hypen in Content-Type:
curl -i -X PUT -H "Content-Type: text/uri-list" -d "http://localhost:8080/shelves/1" http://localhost:8080/books/1/shelve
HTTP/1.1 204
Date: Sat, 19 Nov 2016 16:50:24 GMT

So everything works as expected, provided you use it the right way :)
@Oliver: Thanks a lot!

A: probably you need specify the link on 'Shelve' side, and try to add the book to the shelve
//Shelve model
@OneToMany(mappedBy = "shelve")
public Set<Book> getBooks() {
    return books;
}

public void setBooks(Set<Book> books) {
    this.books = books;
}

//curl add book to shelve
curl -i -X PUT -H "ContentType: text/uri-list" -d "http://localhost:8080/books/1" http://localhost:8080/shelve/1/books


text:
Q: Get attr(id) with a known href variable I want to get the id name thanks to a href value that is set in a variable.
To do this, I want to:

*

*get the attr('href') of a clicked element (that works).

*put it in a variable (OK).

*search this href in a every class called ".link" (not in #prev-ajax, #next-ajax id) (problem)

*Get the parent id.

I tried this :
$('#prev-ajax,#next-ajax').click(function(e) {
    e.preventDefault();
    var href = $(this).attr('href');
    $(".link[href*= href ]:not('#prev-ajax,#next-ajax')");
    var ajax = $(this).parents('.element').attr('id');
    alert(ajax);
});

A: As you're using a JavaScript variable, you need to escape the quotes. Also, don't wrap items in the :not selector in quotes.
Try this:
$(".link[href*= '" + href + "']:not(#prev-ajax, #next-ajax)");

Edit: Looking at your fiddle, you're also not doing anything with that selector. See this:
$(".link[href*= '" + href + "']:not(#prev-ajax, #next-ajax)");
var ajax = $(this).parents('.element').attr('id');

It should be:
var link = $(".link[href*= '" + href + "']:not(#prev-ajax, #next-ajax)");
var ajax = link.parents('.element').attr('id');

Demo: http://fiddle.jshell.net/UKyT4/1/


text:
Q: Tools for generating Haskell function dependency (control flow) graph? Note not "functional dependency". Are there tools available that allow me to build a static function dependency graph from source code? Something which indicates to me which functions depend on which other ones in a graphical manner.

A: Yes, there certainly are. If you look in the Development category on Hackage, you'll find tools for:

*

*graphing package dependencies -- n.b requres older cabal

*graphing module dependencies

*graphing function calls

*graphing running data structures
In particular, SourceGraph contains many analysis passes, including:

*

*visualizing function calls

*computing cyclomatic complexity

*visualizing module imports
Other tools that you might be interested in are:

*

*HPC, for visualizing test coverage

*ThreadScope, for visualizing runtime behavior

*lscabal, extract modules from a package
Here is the functional call graph produced by SourceGraph run over cabal2arch:


text:
Q: connect eclipse web application to sql 2012 database I'm looking into how to connect a web application to an sql 2012 database "MyTestDatabase" with Windows authentication. I have a similar project that is a simple java application that prints out the contents of a table. here's the code for it...
public class sqldriver {
Connection connection = null;
public sqldriver() {}
public boolean doConnection() {
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        connection = DriverManager
            .getConnection("jdbc:sqlserver://localhost:1433;database=MyTestDB;integratedSecurity=true");
        Statement stmt = connection.createStatement();
    } catch (ClassNotFoundException e) {
        System.out.println("ClassNotFoundException : " + e.getMessage()); return false;
    } catch (SQLException e) {
        System.out.println(e.getMessage()); return false;
    }
    return true;
}

All I can find are tutorials for Derby and that's not what I need. The error I keep getting is...

WARNING: Failed to load the sqljdbc_auth.dll cause : no sqljdbc_auth in java.library.path

I've added the sqljdbc_auth.dll to the web-inf/lib, but it doesn't fix the problem. Is there something I've missed?

A: To load sqljdbc_auth.dll, you either need to include the DLL in a location on the system PATH, or you need to explicitly specify the java.library.path property in the run configuration of Eclipse.

A: make sure you add your database in the odbc !!
Go to the start menu and type Odbc then it will appear a dialog >>
select the system dsn tap then select add then select your server whatever Mysql Or ms Access
after that enter your DB info if you select Mysql then save by click ok
then go to your Code and make a string whith your config and send it to the connection object!!
note:
You should delete your constructor and leave the compiler run the default..


text:
Q: How can I use apple com.apple.eawt functionality on Java 8? I have recently started learning java and I am working/improving on a java IDE. I'm trying to find a way so that when you double click a file, the file is automatically opened with my program.
So far the only way I have found to do that is by using the apple extension com.apple.eawt (question found here). The only problem is that I have JDK 1.8 and this extension no longer works. Following this question, I looked for it on my computer and I believe it was last included in JDK 1.6.
My questions are: is there a way to use this extension in java 1.8? Or is there an Apple or non-Apple replacement that will do the same?

A: Java 9 has replicated most of com.apple.eawt in the java.awt.Desktop class
For instance, you pointed to a question that recommended using Application.getApplication().setOpenFileHandler(myOpenHandeler).
This is equivalent to Desktop.setOpenFileHandler(OpenFilesHandler openFileHandler).
This functionality is also now available on platforms other than macOS, such as Windows.


text:
Q: Angular js:ng-model is over writing the items in the ng-repeat I have a strange problem with my ng-repeat array.
Currently, I am listing an array using ng-repeat and an edit button is placed to edit the particular item and save to the database.
But the problem is when the particular item in the text box is changed the ng-repeat items are also changed.
Here is the fiddle of my issue
https://plnkr.co/edit/D5NQitsRg7sCfZBE9IaB?p=preview
Change the value in textfield it will also affect the values in ng-repeat

A: you are assigning the reference of the variable that's why its changing. you have to copy the variable. below is working example:-

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {

  $scope.items= [
       {id:1,name:'first'},{id:2,name:'second'}
    ];

    $scope.editItem = function(index){
    //edit
      $scope.edit = angular.copy($scope.items[index]);

    }
});
<!DOCTYPE html>

{{item.id+','+item.name}}

  Click to Edit {{item.name}} item

Edit

   <input type="text" ng-model="edit.name" />


text:
Q: When is a continuous harmonic function holomorphic? I am trying some questions in complex analysis and I got struck on this particular question.

Question: Let $f:\bar {U} \to \mathbb{C}$ be a continuous function which is harmonic in $U$, the unit disc with center origin. Prove that $f$ is holomorphic in $U$ iff $\int_{-\pi}^{\pi} f(e^{it}) e^{int}dt  =0$ for all positive integers $n$.

Assuming $f$ to be holomorphic I proved the other side but I have no idea on how I can prove that f is holomorphic if it satisfies $\int_{-\pi}^{\pi} f(e^{it}) e^{int}dt  =0 $.


text:
Q: How to write an incremental loop in xslt I have a method that each time it is called I want to increment the counter and display that number beside my hello world (i have denoted the # sign as my number), I am not sure how to go about doing this in xslt.

    hello world #

For example say my method is called 3 times I would have
hello world 1
hello world 2
hello world 3
and if my method is called only once I would have just
hello world
(no number if just called once)

A: You have tagged as XSLT 2.0 where you can do e.g.
<xsl:for-each select="1 to 3">

    hello world <xsl:value-of select="if (last() gt 1) then . else ()"/>

</xsl:for-each>

With XSLT 1.0 if you have a template
<xsl:template match="foo">

    hello world <xsl:if test="last() > 1"><xsl:value-of select="position()"/></xsl:if>

</xsl:template>

you could use <xsl:apply-templates select="//foo"/>. But you would better show us the code you have that you call a method in XSLT, then it is hopefully clearer what you have and how you want to use it.


text:
Q: Trying to inherit theme / style and applying additional triggers I'm trying to work with, and understand XAML hierarchy for styles... in simple, a simple Textbox... seen all over the place for how to set the "disabled" background color based on the "IsEnabled" flag.  Great, got that.
Now, I want to have another class derived from TextBox... MyTextBox.  For this class, I have a property (not dependency property, so I was using DataTrigger).  So, I want to keep all the normal TextBox actions that were working, but now get the new trigger to properly update the background color to some other color..  So, here is what I have.  just to clarify, all my static resources for colors are SOLID BRUSHES...
<Style TargetType="TextBox" >
  <Setter Property="FontFamily" Value="Courier New" />
  <Setter Property="FontSize" Value="12" />
  <Setter Property="Foreground" Value="{StaticResource MyForeground}" />
  <Setter Property="Background" Value="{StaticResource MyBackground}" />
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="TextBox">
        <Border Name="Bd" BorderThickness="{TemplateBinding BorderThickness}"
            BorderBrush="{TemplateBinding BorderBrush}"
            Background="{TemplateBinding Background}"
            SnapsToDevicePixels="true">

            <ScrollViewer Name="PART_ContentHost"
                Background="{TemplateBinding Background}"
                SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
        </Border>

        <ControlTemplate.Triggers>
          <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Background" Value="{StaticResource MyDisBackground}" />
            <Setter TargetName="PART_ContentHost" Property="Background"
                 Value="MyDisBackground"/>
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

<!--  Now, my derived (or so I was hoping) style that just adds additional trigger -->
<Style TargetType="local:MyTextBox"  BasedOn="{StaticResource {x:Type TextBox}}" >
  <Style.Triggers>
    <DataTrigger Binding="{Binding Path=IsRequired}" Value="True">
      <Setter Property="Background" Value="{StaticResource RequiredBackground}" />
    </DataTrigger>
  </Style.Triggers>
</Style>

Am I missing something simple?

A: First, your DataTrigger is looking at the DataContext of your MyTextBox (not the control itself). So look at the control, you'd need to do something like:
<DataTrigger Binding="{Binding Path=IsRequired, RelativeSource={RelativeSource Self}}" Value="True">
    <Setter Property="Background" Value="{StaticResource RequiredBackground}" />
</DataTrigger>

Now that will set the MyTextBox.Background property when MyTextBox.IsRequired is true. But dependency property values have a precedence order. So the above will visually change the background used like:
<local:MyTextBox />

In the following case your RequiredBackground brush will not be used. Instead you'll see the MyDisBackground brush:
<local:MyTextBox IsEnabled="False" />

In this case, the ScrollViewer.Background is changed to MyDisBackground and no longer binds to the MyTextBox.Background property. The MyTextBox.Background would still be RequiredBackground, but it's no longer used anywhere.
Finally, in the following case your RequiredBackground brush will not be used.
<local:MyTextBox Background="Yellow" />

Here, the local value (yellow) is at #3 in the precedence list, while the style setter is at #8.
If you make your property a dependency property that defaults to false, then you could do something like:
<Style TargetType="TextBox" >
  <Setter Property="FontFamily" Value="Courier New" />
  <Setter Property="FontSize" Value="12" />
  <Setter Property="Foreground" Value="{StaticResource MyForeground}" />
  <Setter Property="Background" Value="{StaticResource MyBackground}" />
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="TextBox">
        <Border Name="Bd" BorderThickness="{TemplateBinding BorderThickness}"
            BorderBrush="{TemplateBinding BorderBrush}"
            Background="{TemplateBinding Background}"
            SnapsToDevicePixels="true">

            <ScrollViewer Name="PART_ContentHost"
                Background="{TemplateBinding Background}"
                SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
        </Border>

        <ControlTemplate.Triggers>
          <Trigger Property="local:MyTextBox.IsRequired" Value="False">
            <Setter Property="Background" Value="{StaticResource RequiredBackground}" />
            <Setter TargetName="PART_ContentHost" Property="Background"
                 Value="RequiredBackground"/>
          </Trigger>
          <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Background" Value="{StaticResource MyDisBackground}" />
            <Setter TargetName="PART_ContentHost" Property="Background"
                 Value="MyDisBackground"/>
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

<Style TargetType="local:MyTextBox"  BasedOn="{StaticResource {x:Type TextBox}}" />

Eventhough the property doesn't exist for TextBox, it can still get the default value of your dependency property and trigger off it. But since it would be set for a TextBox, that trigger will never be used.


text:
Q: AEM listen to bundle registration I know I can use a JCR EventListener to check things like changes on nodes. I also know OSGi bundles implement a ServiceListener interface which let them know when a bundle is registered or stopped.
I think I'm somewhat close but I can't seem to connect the dots. How in AEM can I deploy a bundle that can listen to other bundles ServiceEvent changes?

A: What is your use case? do you need a BundleTracker or a ServiceTracker.
As may be the case you may need to extend BundleTracker/ServiceTracker and handle your logic in addingxxxxxx/ modifiedxxxxxx/ removedxxxxxx methods.
Some examples you can check AEM commons code and Tracker

A: Yes, you are right. You can listen to OSGi events, using Felix EventAdmin.
There you can find specification but in a couple of words:

*

*First you need to implement interface EventHandler

*Register your handler for events with topic org/osgi/framework/BundleEvent/STARTED
In documentation they do not use annotations, but if you use maven scr plugin in you project - you can do it with annotations. Your code could look like:
@Component
@Service(value = EventHandler.class)
@Property(name = EventConstants.EVENT_TOPIC, value = { ReplicationAction.EVENT_TOPIC })
public class YourEventHandler implements EventHandler {

    @Override
    public void handleEvent(Event event) {
        // do smth with event
    }
}


text:
Q: Black Screen on Segue Animation / Glitchy & Extend swipe gesture length I have been following a tutorial on how to implement custom segues. Using a swipe gesture - I swipe my finger the segue works but instead of a smooth transition where the second ViewController slides upwards/downwards to replace the current one, I get a black screen then the destination ViewController loads..
This happens on both the forward and the rewind segue.
I have attached the animation code for my normal segue (not rewind).
Additonally, when I swipe the screen slightly the segue happens instantaneously. How would I make it so the segue does not occur until my finger is lifted off (or in the simulators case, the mouse click). Would I have to work with scrollViews? or is this effect possible just using swipeGestureRecognizers & custom segues.
Thanks!
class FirstCustomSegue: UIStoryboardSegue {

override func perform() {

    // Animate the transition.
    UIView.animateWithDuration(0.4, animations: { () -> Void in
        firstVCView.frame = CGRectOffset(firstVCView.frame, 0.0, -screenHeight)
        secondVCView.frame = CGRectOffset(secondVCView.frame, 0.0, -screenHeight)

        }) { (Finished) -> Void in

            // Animate the transition.
            UIView.animateWithDuration(0.4, animations: { () -> Void in
                firstVCView.frame = CGRectOffset(firstVCView.frame, 0.0, -screenHeight)
                secondVCView.frame = CGRectOffset(secondVCView.frame, 0.0, -screenHeight)

                }) { (Finished) -> Void in
                    self.sourceViewController.presentViewController(self.destinationViewController as! UIViewController,
                        animated: false,
                        completion: nil)
            }
       }
   }

}

A: Try this code, I changed the last line on self.destinationViewController...
class FirstCustomSegue: UIStoryboardSegue {

    override func perform() {

        // Animate the transition.
        UIView.animateWithDuration(0.4, animations: { () -> Void in
            firstVCView.frame = CGRectOffset(firstVCView.frame, 0.0, -screenHeight)
            secondVCView.frame = CGRectOffset(secondVCView.frame, 0.0, -screenHeight)

            }) { (Finished) -> Void in

                // Animate the transition.
                UIView.animateWithDuration(0.4, animations: { () -> Void in
                    firstVCView.frame = CGRectOffset(firstVCView.frame, 0.0, -screenHeight)
                    secondVCView.frame = CGRectOffset(secondVCView.frame, 0.0, -screenHeight)

                    }) { (Finished) -> Void in
                        self.sourceViewController.presentViewController(self.storyboard.instantiateViewControllerWithIdentifier("YOUR_IDENTIFIER"),
                            animated: false,
                            completion: nil)
                }
        }
    }

}

Replace YOUR_IDENTIFIER with the storyboard ID that matches your view controller.


text:
Q: Is using 001 as a number same as 1 in Javascript? EDIT : This is not a duplicate of the other question as to realise why prepending 0's to numbers can actually result in a different value, this question has nothing to do with Octals, In the other question does the significance of prepending 0's to a number resulting in a different (Octal) value is not obvious.
For code alignment to look nice, I formatted number of lines that would have an integer as an argument from 1,2,3,.. to 01,02,03,...
Are the two indistinguishable in JavaScript? ( please don't mistake 01 with "01" they are different types. anyone knows of any example in any programming language where 1 and 01 will not be the same value?).

A: For this example - yes.
But leading 0s like this is actually octal notation.
01 == 1.
But 011 is actually 9.
Basically - you don't want to do this.


text:
Q: Add additional button to Bootstrap navigation in WordPress custom walker I'm using the following code of a custom navigation walker for WordPress to generate a bootstrap navigation:

<?php

class NavWalker extends Walker_Nav_Menu {
  private $cpt; // Boolean, is current post a custom post type
  private $archive; // Stores the archive page for current URL

  public function __construct() {
    add_filter('nav_menu_css_class', array($this, 'cssClasses'), 10, 2);
    add_filter('nav_menu_link_attributes', array($this, 'filter_menu_link_atts'), 10, 3);
    add_filter('walker_nav_menu_start_el', array($this, 'filter_menu_item_output'), 10, 4);
    add_filter('nav_menu_item_id', '__return_null');
    $cpt           = get_post_type();
    $this->cpt     = in_array($cpt, get_post_types(array('_builtin' => false)));
    $this->archive = get_post_type_archive_link($cpt);
  }

  /**
  * @see Walker::start_lvl()
  * @since 3.0.0
  *
  * @param string $output Passed by reference. Used to append additional content.
  * @param int $depth Depth of page. Used for padding.
  */
  // @codingStandardsIgnoreStart
  public function start_lvl(&$output, $depth = 0, $args = array()) {
    parent::start_lvl($output, $depth, $args);
    $pos    = strrpos($output, '">', -1);
    $output = substr_replace($output, ' dropdown-menu depth'.$depth.'" role="menu">', $pos);
  }
  // @codingStandardsIgnoreEnd

  /**
   * Traverse elements to create list from elements.
   *
   * Display one element if the element doesn't have any children otherwise,
   * display the element and its children. Will only traverse up to the max
   * depth and no ignore elements under that depth.
   *
   * This method shouldn't be called directly, use the walk() method instead.
   *
   * @see Walker::start_el()
   * @since 2.5.0
   *
   * @param object $element Data object
   * @param array $children_elements List of elements to continue traversing.
   * @param int $max_depth Max depth to traverse.
   * @param int $depth Depth of current element.
   * @param array $args
   * @param string $output Passed by reference. Used to append additional content.
   * @return null Null on failure with no changes to parameters.
   */

  // @codingStandardsIgnoreStart
  public function display_element($element, &$children_elements, $max_depth, $depth, $args, &$output) {
    if (!$element) {
      return;
    }

    $id_field = $this->db_fields['id'];
    $this->has_children = !empty($children_elements[$element->$id_field]);

    parent::display_element($element, $children_elements, $max_depth, $depth, $args, $output);
  }
  // @codingStandardsIgnoreEnd

  public function cssClasses($classes, $item) {
    if ($this->has_children) {
      $classes[] = 'dropdown';
    }

    if ($item->menu_item_parent != 0) {
      $classes[] = 'dropdown-item';
    }

    if ($item->menu_item_parent == 0) {
      $classes[] = 'nav-item';
    }

    if (strcasecmp($item->attr_title, 'header') == 0) {
      $classes[] = 'dropdown-header';
    }

    $slug = sanitize_title($item->title);

    if ($this->cpt) {
      $classes = str_replace('current_page_parent', '', $classes);
      if (strcasecmp($this->archive, $item->url) === 0) {
        $classes[] = 'active';
      }
    }

    //$classes = preg_replace('/(current(-menu-|[-_]page[-_])(item|parent|ancestor))/', '', $classes);
    $classes = preg_replace('/^((menu|page)[-_\w+]+)+/', '', $classes);
    $classes[] = 'menu-' . $slug;
    $classes = array_unique($classes);

    return array_filter($classes, function ($element) {
      $element = trim($element);
      return !empty($element);
    });
  }

  /*
   * This filter is used to customize the
 attributes.
   */
   // @codingStandardsIgnoreStart
  public function filter_menu_link_atts($atts, $item, $args) {

    if (is_object($args->walker)) { // Filter if custom walker
      $classes   = array();
      $classes[] = 'nav-link';

   /*
      if ($args->walker->has_children) {
        $atts['data-toggle']   = 'dropdown';
        $classes[]             = 'dropdown-toggle';
        $atts['aria-haspopup'] = 'true';
      }
      */

      if (strcasecmp($item->attr_title, 'disabled') == 0) {
        $classes[] = 'disabled';
      }

      if ($item->current == 1) {
        $classes[] = 'active';
      }

      if ($item->parent == 1) {
        $classes[] = 'active';
      }

      $atts['class'] = implode(' ', $classes);
    }

    return $atts;
  }
  // @codingStandardsIgnoreEnd

  /*
   * This filter is used to customize the
 final output.
   */
   // @codingStandardsIgnoreStart
  public function filter_menu_item_output($item_output, $item, $depth, $args) {
    $indent = str_repeat("\t", $depth);

    if (strcasecmp($item->attr_title, 'divider') == 0 && $depth === 1) {
      $item_output .= $indent . '
';
    } else if ((strcasecmp($item->attr_title, 'header') == 0 && $depth === 1) && $depth === 1) {
      $item_output = $indent . '
' . esc_attr($item->title) . '
';
    }

    $args->link_before = '';
    $args->link_after = '';

    return $indent . $item_output;
  }
  // @codingStandardsIgnoreEnd
}

I'm also using the following JS code to open the dropdown in the navigation on mouse over:

 $('ul.nav li.dropdown.nav-item').hover(function() {
     $(this).find('.sub-menu.dropdown-menu.depth0').stop(true, true).delay(200).fadeIn(500);
   }, function() {
     $(this).find('.sub-menu.dropdown-menu.depth0').stop(true, true).delay(200).fadeOut(500);
   });

      $('li.dropdown.dropdown-item').hover(function() {
     $(this).find('.sub-menu.dropdown-menu.depth1').stop(true, true).delay(200).fadeIn(500);
   }, function() {
     $(this).find('.sub-menu.dropdown-menu.depth1').stop(true, true).delay(200).fadeOut(500);
   });

In this case, the mobile user has no chance to open the dropdown. He will always click on the link. This is absolutly ok for me. I just need one more link for mobile users (arrow-icon on the right side) to let them open the dropdown.
I just don't understand where I have to add this link in the custom walker.

A: I've found a solution. Change this code:
public function start_lvl(&$output, $depth = 0, $args = array()) {
     parent::start_lvl($output, $depth, $args);
     $pos    = strrpos($output, '">', -1);
     $output = substr_replace($output, ' dropdown-menu depth'.$depth.'" role="menu">', $pos);
}

to this:
public function start_lvl(&$output, $depth = 0, $args = array()) {
    $indent = str_repeat("\t", $depth);
    $output .= "\n$indent<button class=\"btn btn-link btn-menu pull-xs-right hidden-lg-up\" data-toggle=\"dropdown\"></button>\n";

    parent::start_lvl($output, $depth, $args);
    $pos    = strrpos($output, '">', -1);
    $output = substr_replace($output, ' dropdown-menu depth'.$depth.'" role="menu">', $pos);
 }