text:
Q: Reparametrization of regular curves I'm studying curves in $\mathbb{R}^3$, and I came up with a question that I don't manage to answer on my own, so I would like your help. Since the definitions can vary from book to book, I'll first give some definitions and conventions that my book uses:

Regular curve
Let $(\gamma,\mathbf{r})$ be a curve
$\mathbf{r}:I\subseteq \mathbb{R} \to \mathbb{R}^3 , I \text{  interval}$
$(\gamma,\mathbf{r})$ is regular iff $\mathbf{r} \in C^1(I)$ and $\mathbf{r}'(t)\neq 0 \ \forall t\in I$.

Intuitively(if I didn't misunderstood) a curve is regular if and only if $\mathbf{r}$ "walks on $\gamma$" in a continous way withouth jumping or coming back or stopping or zig-zagging, etc.
Then there is this definition:

Reparametrization
Let $(\gamma,\mathbf{r}_1)$ and $(\gamma,{\mathbf{r}_2})$ be two regular curves.
$\mathbf{r}_1:I_1\subseteq \mathbb{R} \to \mathbb{R}^3 $
$\mathbf{r}_2:I_2\subseteq \mathbb{R} \to \mathbb{R}^3 $
$(\gamma,{\mathbf{r}_2})$ is a reparametrization of  $(\gamma,{\mathbf{r}_1})$ if there exists a bijection:
$\varphi:I_2 \to I_1$
$\varphi \in C^1(I_2)$
$\varphi'(t)\neq 0 \ \forall t \in I_2$
Such that $\mathbf{r}_2=\mathbf{r}_1 \circ \varphi$

Clearly the properties of $\varphi$ are imposed by the fact that $\mathbf{r}_2$ has to be regular. Now I can start to come to my question.Let's proceed step by step.
I wondered if two regular curves $(\gamma,\mathbf{r}_1)$, $(\gamma,\mathbf{r}_2)$ are always one the reparametrization of the other. And I come up to a negative answer. In fact I can take:
$$\mathbf{r}_1(t)=(\cos(t),\sin(t)) \ \ t\in [0,2\pi]$$
$$\mathbf{r}_2(t)=(\cos(t),\sin(t)) \ \ t\in [0,4\pi]$$
And this curves are not one the reparametrization of the others, because if they were they should pass the same number of times on each point of $\gamma$ in fact if $\mathbf{r}_2=\mathbf{r}_1 \circ \varphi$, let $P$ be a point of $\gamma$:
$$|\mathbf{r}_2^{-1}(P)|=|(\mathbf{r}_1 \circ \varphi)^{-1}(P)|=|\varphi^{-1}(\mathbf{r}_1^{-1}(P))|=|\mathbf{r}_1^{-1}(P)|$$
Where the last step is justified because $\varphi^{-1}$ is a bijection so it preserves cardinalities.
So I tried to solve this problem by imposing another hyphothesis.

Conjecture
Let $(\gamma,\mathbf{r}_1)$ and $(\gamma,{\mathbf{r}_2})$ be two regular curves.
$|\mathbf{r}_1^{-1}(P)|=|\mathbf{r}_2^{-1}(P)|<\aleph_0 \ \forall P \in \gamma$.
$\Rightarrow $ $(\gamma,\mathbf{r}_1)$, $(\gamma,\mathbf{r}_2)$ are one the reparametrization of the other

However I think that I found a counterexample also to this one, even though it's just a sketch:

(The arrows indicate how each parametrizations walks on $\gamma$, the red point is the start point the coincides with the end point, and just to make it clear $\mathbf{r}_1$ and $\mathbf{r}_2$ are injective(except for the start end point))
This is a countexample because if $\mathbf{r}_1$ and $\mathbf{r}_2$ were one the reparametrization of the other the tangent versors should be equal in every point or opposite in every point.
When I come to this point I thought that the problem was that the way that the self-intersection was constructed(because not all self-intersection give problems), but I soonely found out that self-intersections can get pretty nasty and sneaky,so I gave up and I came up with this weaker conjecture:

Final Conjecture
Let $(\gamma,\mathbf{r}_1)$ and $(\gamma,{\mathbf{r}_2})$ be two regular simple curves(if they are close suppose in addiction that the starting\end point of the two parametrizations coincide). Then one is the reparametrization of the other.

I would like to know if this Final Conjecture is true, and if possible I would like some insight about the self-intersections problem and if there is some result about this. I'm sorry if it's a long post, but I'm really interested in this topic so I get carried away.
Thank you in advance.
:)

A: If I understand your hypotheses correctly, I think the answer to your final conjecture is yes. By your notation $(\gamma, r)$, I take it to mean that $\gamma = r(I)$ is the image of $r$. Then a simple curve presumably means one such that $r: I\to \gamma$ is one-to-one. The key point is that if $r$ is regular at $p\in I$ (meaning $r'(p) \neq 0$), then there is are open neighborhoods $U\subset I$ of $p$ and $V\subset \mathbb R^3$ of $r(p)$, and a $C^1$ function $g: U\to V$, such that $g\circ r = id_U$. In other words, near a regular point $p$, $r$ is a local diffeomorphism to its image. This is a consequence of the inverse function theorem; note that assuming that $r$ is simple means there is an inverse function defined on $\gamma$, but regularity means that the inverse is (locally) the restriction of a differentiable function. Equivalently, if the language is familiar, $\gamma(U)$ is an embedded submanifold of $\mathbb R^3$.
Now if $r_1$, $r_2$ are as in your final conjecture, let $h: \gamma\to I_2$ be the inverse of $r_2$. This exists as a set function since $r_2$ is one-to-one. Moreover, the composition $h\circ r_1: I_1 \to I_2$ is $C^1$: to see this it's enough to check at a given point $p\in I_1$, and since $h$ is the restriction of a $C^1$ function $g$ as above, defined near $r_1(p)$, we get that, near $p$, $h\circ r_1 = g\circ r_1$ is the composition of $C^1$ functions, hence is $C^1$. In fact, $\varphi = h\circ r_1$ is a $C^1$ bijection, since it has an inverse of the form $\tilde h\circ r_2$ where $\tilde h$ is the inverse of $r_1$. Moreover $\varphi$ has nonzero derivative everywhere (from the chain rule and using regularity of $r_1$ and $r_2$), and we have $r_2\circ\varphi = r_1$ since $r_2\circ h = id$ on $\gamma$. So $\varphi$ is the desired reparametrization.
Note that in general for a simple regular curve $r$ there need not be a differentiable function $g$ defined on an open neighborhood of all of $\gamma$ such that $g\circ r = id_{I}$. However, such a $g$ does exist if $I$ is compact.


text:
Q: tkz-fct produces no plots, why? tkz-fct produces no plots, for instance I copied the following code from the manual:
    \documentclass{article}

    \usepackage{color}
    \usepackage{tikz}%
    \usepackage{tkz-euclide}
    \usepackage{tkz-fct} \usetkzobj{all}

    \begin{document}
    \begin{tikzpicture}[scale=.5]
    \tkzInit[xmax=100,xstep=10,
    ymax=1000000, ystep=100000]
    \tkzAxeX[right] \tkzAxeY[above]
    \tkzGrid \tkzFct[color=red,
    domain=0:100]{\x**3}
    \end{tikzpicture}
    \end{document}

This results in the following picture:

gnuplot --version gives:

gnuplot 4.4 patchlevel 2

Any ideas how to solve the problem?

A: Your code works:

You need to read your .log file to verify two things:

*

*the path for gnuplot. If the path is fine then you must find a line like gnuplot executed or something like that

*if in your .log file, you have something like

file.table not found,

then you need to use the option --shell-escape or write18 in your script for the compilation.
The problem is the same with pgfplots or another package that uses gnuplot.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to perform update partially in Flask? Is there anyway to update with PUT method in flask restul with partially fields?
currently my PUT method perform this however if the fields it's not there gonna throw error.
item = ItemModel.find_by_id(id)
    item_json = request.get_json()

    if(item):
        item.name = item_json['name']
        item.code = item_json['code']
        item.tags = item_json['tags']
    else:
        try:
            item = item_schema.load(
                item_json
            )
         except ValidationError as err:
            return err.messages, HTTPStatus.BAD_REQUEST

    item.save_to_db()
    return {'message': item_schema.dump(item)}, HTTPStatus.OK

A: I found a way but not sure it's the best way or not.
So the idea we make new function on model to update and pass JSON object and set attribute using the object.
from . import db

class ItemModel(db.Model):
    __tablename__ = "items"

    id = db.Column(db.Integer, primary_key=True)
    code = db.Column(db.String(), nullable=False)
    name = db.Column(db.String(), nullable=False)
    tags = db.Column(db.String(), nullable=False)
    created_at = db.Column(db.DateTime, server_default=db.func.now())
    updated_at = db.Column(
        db.DateTime,
        server_default=db.func.now(),
        server_onupdate=db.func.now()
    )

    def update_to_db(self, data):
        for key, value in data.items():
            setattr(self, key, value)
        db.session.commit()

Now in resource we call the update function with input JSON from request.
@classmethod
def put(self, id: int):
    item = ItemModel.find_by_id(id)

    if(item):
        try:
            item.update_to_db(
                request.get_json()
            )
        except ValidationError as err:
            return err.messages, HTTPStatus.BAD_REQUEST

        return {'message': item_schema.dump(item)}, HTTPStatus.OK

    return {'message': gettext('item_not_found')}, HTTPStatus.NOT_FOUND

This is works but still not sure if there's any best way to do this.

A: Here's what I do:

*

*Use a POST method to create a new item, and a PUT method to update an item.

*Use the marshmallow Schema to validate the data first when the requests is received. You can use webargs for that. It is maintained by the marshmallow dev team. It throws the appropriate HTTP error (400 if the request is misformed and 422 if it is a correct json but fails validation).

*There is no universal rule for the PUT. From a resource point of view, the PUT on an item is meant to replace the whole item (as opposed to a PATCH). This does not mean it is meant to replace the whole item in database, as there can be fields that are not modifiable by the user (the ID, created_at, updated_at, or some other fields that may be exposed in another resource, it really depends). The update_to_db method in your answer looks fine.
Note you still have to catch potential errors when writing to the database (database connexion error, item not found, integrity error (invalid foreign key),...) but at least the validation takes place as soon as possible.


text:
Q: I can't create database by user input in python 1.Getting problem in creating databases by taking user input
table_name = input("Enter the Table name : ")
attribute_1 = input('Enter the First Attribute : ')
type_1 = input('Enter the type for the first attribute : ')
attribute_2 = input('Enter the Second attribute : ')
type_2= input('Enter the type for Second attribute : ')
sql1 = 'CREATE TABLE',table_name,'(',attribute_1,'',type_1,'', attribute_2,'', type_2,')'
cur.execute(sql1)
db.commit()

A: You can't concatenate strings using commas in Python. You should instead use the str.join method. Also note that there should be a comma in the SQL string between attributes:
sql1 = ' '.join(('CREATE TABLE',table_name,'(',attribute_1,'',type_1,',', attribute_2,'', type_2,')'))


text:
Q: Java Sudoku Solver, does it work the same with different sudoku sizes? I have a sudoku solver that works with 9x9 sudokus perfectly. I would like to get it to work with 9x6 sudokus and other sizes too. Is it possible to just change this function?
You can see that the "9" is always hardcoded. So I tried changing these values to 9 and 6 but the result is only 0s in my solution.
So before I continue messing around with this, is it even possible to change this to support different grid sizes without changing the functions?
    public boolean solve(int i, int j, int[][] cells) {

        if (i == 9) {
            i = 0;
            if (++j == 9) {
                return true;
            }
        }
        if (cells[i][j] != 0)
        {
            return solve(i + 1, j, cells);
        }

        for (int val = 1; val <= 9; ++val) {
            if (legal(i, j, val, cells)) {
                cells[i][j] = val;
                if (solve(i + 1, j, cells)) {
                    return true;
                }
            }
        }
        cells[i][j] = 0;
        return false;
    }

    public static boolean legal(int i, int j, int val, int[][] cells) {
        for (int k = 0; k < 9; ++k) // rij
        {
            if (val == cells[k][j]) {
                return false;
            }
        }

        for (int k = 0; k < 9; ++k) // kolom
        {
            if (val == cells[i][k]) {
                return false;
            }
        }

        int boxRowOffset = (i / 3) * 3;
        int boxColOffset = (j / 3) * 3;
        for (int k = 0; k < 3; ++k) // box
        {
            for (int m = 0; m < 3; ++m) {
                if (val == cells[boxRowOffset + k][boxColOffset + m]) {
                    return false;
                }
            }
        }

        return true;

    }

A: The most primitive sudoku is a 2x2 sudoku
1 2
2 1

You have excaclty two solutions and every number is present in every row and every number is present in every column.
Another example is a 3x2
1 2
2 3
3 1

This is not solvable because not all numbers are present in every row.
Also a 9x6 will not have every number present in every row.
Therefore no solution is possible and this is not a sudoku.


text:
Q: EnableWindow(hWnd, false) doesn't disable keyboard input I am attempting to disable a window under certain conditions using EnableWindow(hWnd, false);
According to the documentation, this should "disable mouse and keyboard input to the specified window".
The problem I am seeing is that it does, in fact, disable like it says, except if the cursor is currently inside of a text box in the window and the window has the focus that does not get disabled. I was thinking of doing some sort of code to take the focus off of the window as well.
Is there a better way to go about this?
Note: The window being disabled is a binary ran via _spawnl().

A: I'm not sure if this is a Windows feature or a bug. Either way, disabling the foreground window is not a good idea.
If you are able to modify the program you start with _spawnl() then that is a better solution. You could make it respond to WM_APP or something like that when you need to control it.
If it is a 3rd-party application then you are left with hacks.
You could try to change the foreground window with SetForegroundWindow but this will only work if you do it very soon after _spawnl() before your thread loses the foreground lock. Using LockSetForegroundWindow before _spawnl()  might be able to help you keep the lock longer. There are also various other hacks to change the foreground with AttachThreadInput etc.
If you don't want to change the foreground I was able to come up with a workaround:
  ShellExecute(NULL, NULL, TEXT("Notepad"), NULL, NULL, SW_SHOW);
  Sleep(2000);
  HWND hNP = FindWindow(TEXT("Notepad"), NULL);
  Sleep(2000); // Start typing in Notepad now...
  if (hNP)
  {
    DWORD tid = GetWindowThreadProcessId(hNP, NULL);
    GUITHREADINFO gti;
    gti.cbSize = sizeof(gti);
    if (tid && GetGUIThreadInfo(tid, &gti))
    {
      HWND hChild = NULL;
      if (gti.hwndFocus != hNP && gti.hwndFocus)
      {
        EnableWindow(hChild = gti.hwndFocus, false);
      }
      if (GetForegroundWindow() == hNP)
      {
        SendNotifyMessage(hNP, WM_ACTIVATE, WA_INACTIVE, NULL);
        SendNotifyMessage(hNP, WM_ACTIVATE, WA_ACTIVE, NULL);
        SendNotifyMessage(hNP, WM_SETFOCUS, NULL, NULL);
        // SendNotifyMessage(hNP, WM_NCACTIVATE, false, NULL); // Uncomment to make it look like it is inactive
      }
      EnableWindow(hNP, false);
      if (hChild)
      {
        EnableWindow(hChild, true);
      }
    }
    MessageBox(NULL, TEXT("Done?"), NULL, MB_TOPMOST);
    SetForegroundWindow(hNP);
    PostMessage(hNP, WM_CLOSE, 0, 0);
  }

This is certainly not optimal, it leaves Notepad in a state where it looks like it is enabled but it is really not. The idea is to disable the focused child window and trigger a fake activation change and forcing the focus to change. It might not work with other applications, who knows.
If you are willing to risk a deadlock you can do this instead:
    DWORD tid = GetWindowThreadProcessId(hNP, NULL);
    GUITHREADINFO gti;
    gti.cbSize = sizeof(gti);
    if (tid && GetGUIThreadInfo(tid, &gti))
    {
      if (GetForegroundWindow() == hNP)
      {
        if (AttachThreadInput(GetCurrentThreadId(), tid, true))
        {
          SetFocus(NULL);
          AttachThreadInput(GetCurrentThreadId(), tid, false);
        }
      }
      EnableWindow(hNP, false);
    }


text:
Q: api10: connectedAndroidTest + espresso: no tests found I want to use espresso automatically via the command line. I have written some tests which work great running from android studio and they also work with emulators api level 16 and 23. On api level 10 I get this error message (only running via gradle connectedAndroidTest):
com.android.builder.testing.ConnectedDevice > No tests found.
[Nexus_4_API_10(AVD) - 2.3.7] [31mFAILED [0m
No tests found.
This usually means that your test classes are not in the form that your test runner expects
(e.g. don't inherit from TestCase or lack @Test annotations).
:app:connectedSourceDebugAndroidTest FAILED

(Source=flavor, Debug=build type)
i followed this guide:
https://developer.android.com/training/testing/ui-testing/espresso-testing.html
@RunWith(AndroidJUnit4.class)
public class LocaleTest{

@Rule
public ActivityTestRule<MainActivity> activityTestRule =
        new ActivityTestRule<>(MainActivity.class);

@Test
public void testSomethings(){
    //some code
}
}

my build.gradle dependencies:
dependencies {
compile ('com.android.support:support-annotations:23.0.1')
androidTestCompile ('com.android.support.test:runner:0.5'){
    exclude group: 'com.android.support', module: 'support-annotations'
}
androidTestCompile ('com.android.support.test:rules:0.5'){
    exclude group: 'com.android.support', module: 'support-annotations'
}
androidTestCompile ('com.android.support.test.espresso:espresso-core:2.2.2'){
    exclude group: 'com.android.support', module: 'support-annotations'
}
compile 'com.android.support:appcompat-v7:23.0.1'
}

to default config i added
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

Thanks in advance, I'm running out of ideas.
EDIT(27.06.2016):
LogCat output
06-27 13:02:30.768 4485-4485/? D/dalvikvm: DexOpt: 'Ljunit/extensions/ActiveTestSuite$1;' has an earlier definition; blocking out
06-27 13:02:30.768 4485-4485/? D/dalvikvm: DexOpt: 'Ljunit/framework/Assert;' has an earlier definition; blocking out
06-27 13:02:30.768 4485-4485/? D/dalvikvm: DexOpt: 'Ljunit/framework/AssertionFailedError;' has an earlier definition; blocking out
06-27 13:02:30.768 4485-4485/? D/dalvikvm: DexOpt: 'Ljunit/framework/Protectable;' has an earlier definition; blocking out
06-27 13:02:30.768 4485-4485/? D/dalvikvm: DexOpt: 'Ljunit/framework/Test;' has an earlier definition; blocking out
06-27 13:02:30.768 4485-4485/? D/dalvikvm: DexOpt: 'Ljunit/framework/TestFailure;' has an earlier definition; blocking out
06-27 13:02:30.768 4485-4485/? D/dalvikvm: DexOpt: 'Ljunit/framework/TestListener;' has an earlier definition; blocking out
06-27 13:02:30.768 4485-4485/? D/dalvikvm: DexOpt: 'Ljunit/framework/TestResult;' has an earlier definition; blocking out
06-27 13:02:30.772 4485-4485/? D/dalvikvm: DexOpt: 'Ljunit/extensions/TestDecorator;' has an earlier definition; blocking out
06-27 13:02:30.772 4485-4485/? D/dalvikvm: DexOpt: 'Ljunit/extensions/TestSetup$1;' has an earlier definition; blocking out
06-27 13:02:30.777 4485-4485/? D/dalvikvm: DexOpt: 'Ljunit/framework/ComparisonFailure;' has an earlier definition; blocking out
06-27 13:02:30.777 4485-4485/? D/dalvikvm: DexOpt: 'Ljunit/framework/TestCase;' has an earlier definition; blocking out
06-27 13:02:30.777 4485-4485/? D/dalvikvm: DexOpt: 'Ljunit/framework/TestResult$1;' has an earlier definition; blocking out
06-27 13:02:30.777 4485-4485/? D/dalvikvm: DexOpt: 'Ljunit/framework/TestSuite;' has an earlier definition; blocking out
06-27 13:02:30.784 4485-4485/? D/dalvikvm: DexOpt: 'Ljunit/extensions/ActiveTestSuite;' has an earlier definition; blocking out
06-27 13:02:30.784 4485-4485/? D/dalvikvm: DexOpt: 'Ljunit/extensions/RepeatedTest;' has an earlier definition; blocking out
06-27 13:02:30.784 4485-4485/? D/dalvikvm: DexOpt: 'Ljunit/extensions/TestSetup;' has an earlier definition; blocking out
06-27 13:02:30.784 4485-4485/? D/dalvikvm: DexOpt: 'Ljunit/framework/TestSuite$1;' has an earlier definition; blocking out
06-27 13:02:30.832 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/AssertionFailedError;'
06-27 13:02:30.832 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/Test;'
06-27 13:02:30.832 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/Test;'
06-27 13:02:30.836 4485-4485/? D/dalvikvm: DexOpt: not verifying 'Ljunit/extensions/ActiveTestSuite$1;': multiple definitions
06-27 13:02:30.836 4485-4485/? D/dalvikvm: DexOpt: not verifying 'Ljunit/framework/Assert;': multiple definitions
06-27 13:02:30.836 4485-4485/? D/dalvikvm: DexOpt: not verifying 'Ljunit/framework/AssertionFailedError;': multiple definitions
06-27 13:02:30.836 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/Assert;'
06-27 13:02:30.836 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/Test;'
06-27 13:02:30.836 4485-4485/? D/dalvikvm: DexOpt: not verifying 'Ljunit/framework/Protectable;': multiple definitions
06-27 13:02:30.836 4485-4485/? D/dalvikvm: DexOpt: not verifying 'Ljunit/framework/Test;': multiple definitions
06-27 13:02:30.836 4485-4485/? D/dalvikvm: DexOpt: not verifying 'Ljunit/framework/TestFailure;': multiple definitions
06-27 13:02:30.836 4485-4485/? D/dalvikvm: DexOpt: not verifying 'Ljunit/framework/TestListener;': multiple definitions
06-27 13:02:30.836 4485-4485/? D/dalvikvm: DexOpt: not verifying 'Ljunit/framework/TestResult;': multiple definitions
06-27 13:02:30.836 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/TestSuite;'
06-27 13:02:30.844 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/AssertionFailedError;'
06-27 13:02:30.844 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/AssertionFailedError;'
06-27 13:02:30.844 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/AssertionFailedError;'
06-27 13:02:30.844 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/AssertionFailedError;'
06-27 13:02:30.864 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/TestResult;'
06-27 13:02:30.868 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/TestCase;'
06-27 13:02:30.868 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/Test;'
06-27 13:02:30.868 4485-4485/? D/dalvikvm: DexOpt: not verifying 'Ljunit/extensions/TestDecorator;': multiple definitions
06-27 13:02:30.868 4485-4485/? D/dalvikvm: DexOpt: not verifying 'Ljunit/extensions/TestSetup$1;': multiple definitions
06-27 13:02:30.868 4485-4485/? D/dalvikvm: DexOpt: not verifying 'Ljunit/framework/ComparisonFailure;': multiple definitions
06-27 13:02:30.868 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/TestResult;'
06-27 13:02:30.872 4485-4485/? D/dalvikvm: DexOpt: not verifying 'Ljunit/framework/TestCase;': multiple definitions
06-27 13:02:30.872 4485-4485/? D/dalvikvm: DexOpt: not verifying 'Ljunit/framework/TestResult$1;': multiple definitions
06-27 13:02:30.872 4485-4485/? D/dalvikvm: DexOpt: not verifying 'Ljunit/framework/TestSuite;': multiple definitions
06-27 13:02:30.872 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/TestSuite;'
06-27 13:02:30.872 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/TestFailure;'
06-27 13:02:30.872 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/TestCase;'
06-27 13:02:30.872 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/TestCase;'
06-27 13:02:30.888 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/TestCase;'
06-27 13:02:30.888 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/TestSuite;'
06-27 13:02:30.888 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/Protectable;'
06-27 13:02:30.888 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/TestSuite;'
06-27 13:02:30.888 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/TestSuite;'
06-27 13:02:30.888 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/TestSuite;'
06-27 13:02:30.888 4485-4485/? D/dalvikvm: DexOpt: not verifying 'Ljunit/extensions/ActiveTestSuite;': multiple definitions
06-27 13:02:30.888 4485-4485/? D/dalvikvm: DexOpt: not verifying 'Ljunit/extensions/RepeatedTest;': multiple definitions
06-27 13:02:30.888 4485-4485/? D/dalvikvm: DexOpt: not verifying 'Ljunit/extensions/TestSetup;': multiple definitions
06-27 13:02:30.888 4485-4485/? D/dalvikvm: DexOpt: not verifying 'Ljunit/framework/TestSuite$1;': multiple definitions
06-27 13:02:30.888 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/TestResult;'
06-27 13:02:30.888 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/TestSuite;'
06-27 13:02:30.896 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/TestSuite;'
06-27 13:02:30.896 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/Test;'
06-27 13:02:30.904 4485-4485/? I/dalvikvm: DexOpt: not resolving ambiguous class 'Ljunit/framework/TestSuite;'


text:
Q: MVC Web API/Rest: Requests by related object I got two controllers; ProjectController and DocumentController. One project can have several documents.
If I want to get documents by projectid, how and where should that be done using REST? (In general I havent got how REST deals with related data)
Edit: Found MVC Web API, get sub items that might be what I'm looking for.
Ivar

A: I believe this should be done in the DocumentController. Below is an example
public class DocumentController : ApiController {

    public IQueryable<Document> GetDocs()
    {

        //get db context

            return db.documents;

    }

    public ICollection<Document> Get(int id)
    {
        return db.documents.where(d = d.ProjectId == id);

    }

}

The IQuerable version can be queried using odata filter query. like below:
http://server:port/api/Document/getdocs?$filter=ProjectId eq '1'
http://server:port/api/Document/getdocs?$filter=DocumentId eq '1001'

(you will have to modify the MapHttpRoute to register this route)
The get version (second function) will simply return collection based on the project id.


text:
Q: C: Not counting spaces and new lines I have the following source code to count blank spaces, new lines and characters in a file:
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(){
    int fd;
    int b=0, nl=0, c=0;
    char ch[1];
    fd=open("text.txt", O_RDONLY);

    while((read(fd, ch, 1))>0)
    {
        if(ch==" ")
            b++;
        if(ch=="\n")
            nl++;
        c++;
    }
    printf("no of blanks %d\n", b);
    printf("no of new line %d\n", nl);
    printf("no of characters %d\n", c);
}

The result is like this:
no of blanks 0
no of new line 0
no of characters 24

My text.txt file's content is:
hello world
hello
world

Number of charactes is right (it includes spaces and new lines). But why are the result of variables b and nl wrong?
PS: I'm new to C, but have a little practice in C++.

A:
if(ch==" ")

should be

if(ch==' ')

And same for the other comparison, "\n" should be '\n'
The double quotation is for string. Use single quotation for character.
And yes you should use fopen instead of low level open call.
int ch;
FILE *fp=fopen("text.txt", "r");

while((ch = getc(fp)) != EOF)
{
    if(ch==' ')
        b++;
    if(ch=='\n')
        nl++;
    c++;
}

That should solve the issue.

A: #include<stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h> // or just include <string> it may vary depending on the compiler you use
int main(){
int fd;
int b=0, nl=0, c=0;
char ch[1];
fd=open("text.txt", O_RDONLY);

while((read(fd, ch, 1))>0)
{
if(strcasecmp(ch, " ") == 0) //you need to use strcasecmp() instead of == for strings
b++;
if(ch[0] == '\n') //you can also check like this.
nl++;
c++;
}
printf("no of blanks %d\n", b);
printf("no of new line %d\n", nl);
printf("no of characters %d\n", c);
}

A: Try putting the space " " and newline character "\n" in single quotes and declare ch as char.

A: In C language,you can't directly compare two strings.
You have to use strcmp(char *str1,char *str2) or strncmp(char *str1,char *str2,ssize_t size).
If you will directly compare the strings it will return 0,which is why blanks and newlines are not incrementing.
Try this correction.
#include<stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main()
{
 int fdesc;
 int blanks=0, newlines=0, characters=0;
 char buf[1];
 fdesc=open("text.txt", O_RDONLY);
 while((read(fdesc,buf, 1))>0)
 {
  if(strcmp(buf," "))
   blanks++;
  if(strcmp(buf,"\n"))
   newlines++;
  characters++;
 }
 printf("no of blanks %d\n", blanks);
 printf("no of new line %d\n", newlines);
 printf("no of characters %d\n", characters);
}

A: Thanks to all ur feedback I managed to fix the code and finally it looks like that :
#include<stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main(){
int fd;
int b=0, nl=0, c=0;

char ch[1];
fd=open("text.txt", O_RDONLY);

while((read(fd, ch, 1))>0)
{
if(ch[0]==' ')
b++;
if(ch[0]=='\n')
nl++;
c++;
}
printf("no of blanks %d\n", b);
printf("no of new line %d\n", nl);
printf("no of characters %d\n", c);
}


text:
Q: How does the permute function in matlab work This is a somewhat silly question but I can't seem to figure out how permute works in matlab. Take the documentation example:
A = [1 2; 3 4]; permute(A,[2 1])
ans =
 1     3
 2     4

What is going on? How does this tell matlab that the 3 and 2 need to be swapped?

A: permute does a permutation of the dimensions of an array, not of its elements, as one may expect from its name.
Thus, permute(A,[2,1]) flips dimension 2 (the columns) of array A with dimension 1 (the rows) of array A, which is equivalent to a transpose (A').
permute(A,[3,2,1]) would produce a 1-by-2-by-2 array (because size(A,3)==1), where the array is "flipped up horizontally".

A: Jonas already explained what permute does. There is no function to permute elements, because it's directly possible using indexing.
x='abcd'

now we want the permutation [3,4,2,1]:
x([3,4,2,1])

ans =

cdba

A: Wow, this is one of the hardest functions to figure out among all the different SDKs I have used up to now. Therefore, I used the F*ck word many times during " my journey of understanding the permute function" . Here are some examples to prevent you from suffering a similar excruciating pain:
First, let's remember the dimensions' names of matrix in matlab: A = zeros(4,5,7) , matrix A has 4 rows, 5 columns and 7 pages. And if you don't specify a dimension, its default count is set to 1. ( i.e. B=zeros(10,3)  has 10 rows, 3 columns and 1 page, this order is important!)
order argument passed to permute swap these dimensions in the matrix and produce an awkward combination of arrays, I think permute is a misnomer for this effect.
Now let's move to the examples, Finally:
% A has 4 rows, 2 columns and 1 page
A =[     5     6
         8     2
         2     2
         1     3];
    % (numbers in the order argument of permute function indicates dimensions,
    % 3 = page , 2 = column and 1 = row dimensions):

    B = permute(A,[3,2,1]); % [3,2,1] means [ page,column,row]
    C = permute(A,[3,1,2]); % [3,1,2] means [ page,row,column]
    D = permute(A,[1,3,2]); % [1,3,2] means [ row,page,column]
    E = permute(A,[2,3,1]); % [2,3,1] means [ column,page,row]
    F = permute(A,[2,1,3]); % [2,1,3] means [ column,row,page]
    G = permute(A,[1,2,3]); % [1,2,3] means [ row,column,page]

EXPLANATIONS:
B = permute(A,[3,2,1]);

1x2x4 ( page(3) dimension of A = 1, column(2) dimension of A = 2, row(1) dimension of A = 4; 1 is row dimension, 2 is column dimension and 4 is page dimension for the generated B. Keep reading here until you understand)
So, there will be 4 1x2 (1x2x4) row matrixes. As in:
ans(:,:,1) =
     5     6

ans(:,:,2) =
     8     2

ans(:,:,3) =
     2     2

ans(:,:,4) =
     1     3

*
C = permute(A,[3,1,2]);

1x4x2 ( page(3) dimension of A = 1, row(1) dimension of A = 4, column(2) dimension of A = 2; 1 is row dimension, 4 is column dimension and 2 is page dimension for the generated C)
So, there will be 2 1x4 (1x4x2) row matrixes. As in:
ans(:,:,1) =
      5     8     2     1

ans(:,:,2) =
      6     2     2     3

*
D = permute(A,[1,3,2]);

4x1x2 ( row(1) dimension of A = 4, page(3) dimension of A = 1, column(2) dimension of A = 2; 4 is row dimension, 1 is column dimension and 2 is page dimension for the generated D)
So, there will be 2 4x1 (4x1x2) column matrixes. As in:
ans(:,:,1) =

     5
     8
     2
     1

ans(:,:,2) =

     6
     2
     2
     3

*
E = permute(A,[2,3,1]);

2x1x4 ( column(2) dimension of A = 2, page(3) dimension of A = 1, row(1) dimension of A = 4; 2 is row dimension, 1 is column dimension and 4 is page dimension for the generated E)
So, there will be 4 2x1 (2x1x4) column matrixes. As in:
ans(:,:,1) =

     5
     6

ans(:,:,2) =

     8
     2

ans(:,:,3) =

     2
     2

ans(:,:,4) =

     1
     3

*
F = permute(A,[2,1,3]); % this is transpose and same as [2,1]

2x4x1 ( column(2) dimension of A = 2, row(1) dimension of A = 4, page(3) dimension of A = 1; 2 is row dimension, 4 is column dimension and 1 is page dimension for the generated F)
So, there will be 1 2x4 (2x4x1) matrix. As in:
 ans =

     5     8     2     1
     6     2     2     3

*
G = permute(A,[1,2,3]); % this makes no difference,  using to show the reasoning

4x2x1 ( row(1) dimension of A = 4, column(2) dimension of A = 2, page(3) dimension of A = 1; 4 is row dimension, 2 is column dimension and 1 is page dimension for the generated G)
So, there will be 1 4x2 (4x2x1) matrix(itself!). As in:
 ans =

 5     6
 8     2
 2     2
 1     3

Yes, this looks hard and it is indeed hard! To check if you understand thoroughly, try predicting a square Matrix's similar different permutations. Have fun, I mean have less pain :)

A: Here is what I understand for permute in matlab.
B_{kji}=a_{ijk}
if you use
B = permute(a,[3 2 1])

============================
That means
B_{211}=a_{112}
B_{213}=a_{312}
....

You can test it by using the following code
A1=sym('a', [3 4 5])
B1 = permute(A1,[3 2 1])


text:
Q: how to apply permission class to particular method in class based views in Django-Rest Framework? I want to apply permission only for "PUT" method not for "POST"
class Signup(APIView):
    def post(self, request, format=None):
        something...something

    @authentication_classes((ExpiringTokenAuthentication,))
    @permission_classes((IsAuthenticated,))
    def put(self, request, format=None):
        something...something

A: Check the HTTP method on your permission class has_permission method and apply your checks if it was PUT:
class ExpiringTokenAuthentication(permissions.BasePermission):

    def has_permission(self, request, view):
        if request.method == 'PUT':
           # do it here

class Signup(APIView):
    permission_classes = (BlacklistPermission,)


text:
Q: Pear upgrade over 7.5G? I am attempting to upgrade Pear, and it is currently asking for more than 7.5G of memory. I set memory limit in php.ini:
memory_limit=7.5G
and am still getting an memory error.
$ pear upgrade
PHP Fatal error:  Allowed memory size of 7516192768 bytes exhausted (tried to allocate 130968 bytes) in /usr/local/pear/share/pear/PEAR/Registry.php on line 417
Any ideas on how to resolve, a little much isn't it?
Thanks in advance for your help.
Regards


text:
Q: Selinux: how to allow an application to access a device I m working on the integration of a new HW device in an Android phone.
The kernel driver is working correctly, already tested with shell test scripts.
Now I would like to allow an application to open the device and communicate with it.
It works well when I disable the enforcing mode thanks to "setenforce 0" command, requiring root priviledge.
But I would like to modify the selinux files to allow such access without such modification.
When I launch the apk, I have the following error message:
denied { setattr } for name="device_name" dev="tmpfs" ino=11979 scontext=u:r:shell:s0 tcontext=u:object_r:my_device:s0 tclass=chr_file permissive=0

I guess the scontext is not correct. I have a specific context (my_dev_context) allowed to access to my_device.
Any ideas ?

A: Try audit2allow.  It takes in your log and spits out the correct allow statements you need.
You're in security context "shell" because you're using adb shell.


text:
Q: Spring integration Kafka MessaheChannel Thread? I have an Spring Integration flow bean (configured via Java DSL) which processes the messages from kafka queue message channel binded with Spring CloudStream.
The source of kafka message is an external application so what I really want to understand, is what thread/threads will actually process that messages.
Is it a single dedicated thread created with application, or is there a thread pool created and configured automatically by CloudStream, or something else?
And could I manage it somehow?

A: The kafka message channel binder uses one thread by default; if you increase the binding consumer.concurrency property, you will get that number of threads - you need at least as many partitions as the concurrency setting because a partition can only be consumed by one consumer.


text:
Q: Does it sound awkward if you use the same word two times in a text to express two different things? In this case I'm using the word "look" to express two different things. Does it make the text sound unnatural or awkward?
Look how every man in the party are extremely kind with her. That's something that only happens when you have that kind of look.

A: In this case, no, it seems quite natural to me. After all the entire length of two sentences are between the two uses of "look". But when the repeated words are in closer proximity to one another, it can be come confusing, and recasting the sentence to avoid repetition is often a good idea.

You only have to look, to see her new look is stunning.

Here the reuse of look is far more likely to be confusing. Sometimes this is done intentionally, as a form of wordplay.
There was a young fellow named Hall
Who fell in the spring in the fall.
'twould have been a sad thing
has he died in the spring
but he didn't -- he died in the fall.

Both "spring" and "fall" are used in multiple senses here: body of water, season, and for "fall" accident.

Unrelated to the reuse of "look", the example has an error in agreement.

Look how every man in the party are extremely kind to her.

That should be "every man ... is extremely kind..." because "man" is singular and the form of the verb "to be" must agree. If instead of "every man" the writer had used "all the men" then the form "are" would have been correct.


text:
Q: Define $A:= \{f \in \Bbb R^{\Bbb R} \mid f \text{ injective} \} \subseteq \Bbb R^\Bbb R$. Determine wheter $A$ open or closed in $\Bbb R^\Bbb R$?
Define $A:= \{f \in \Bbb R^{\Bbb R} \mid f \text{ injective} \} \subseteq \Bbb R^\Bbb R$. Determine wheter $A$ open or closed in $\Bbb R^\Bbb R$ when $\Bbb R^\Bbb R$ has the product topology.

How can I make an educated guess on wheter $A$ should be open or closed? I don't think I have any tools at my disposal which I could use here. The complement of $A$ is the set of all maps $f : \Bbb R \to \Bbb R$ that aren't injective, but I have as little information about the complement as I do with $A$ so no help there either.
By the product topology $A$ is open in $\Bbb R^\Bbb R$ if $A$ is of the form $\prod_i U_i$ where $U_i \subset \Bbb R$ is open and $U_i = \Bbb R$ for all but finitely many $i$. Can I do something with this information?

A: First note that the product topology has more open sets than those of the form $\prod_{x \in \mathbb R} U_x$ where $U_x \subset \Bbb R$ is open and $U_x = \Bbb R$ for all but finitely many $x$. In fact, these sets form a basis for the product topology, so the open sets are all unions of such basic open sets.
The product topology is the topology of pointwise convergence. That is, a net $(f_\alpha)$ in $\mathbb R^{\mathbb R}$ converges to $f \in \mathbb R^{\mathbb R}$ iff all nets $(f_\alpha(x))$ in $\mathbb R$ converge to $f(x) \in \mathbb R$.

*

*$A$ is not closed.
Let $f_n : \mathbb R \to \mathbb R, f_n(x) = x/n$. These functions are injective, i.e. $(f_n)$ is a sequence in $A$. Clearly $f_n \to 0 \in \mathbb R^{\mathbb R}$ pointwise. Since $0 \notin A$, we see that $A$ is not closed.

*$A$ is not open.
Let $f \in A$. If $A$ were open, there would be a basic open $\prod_x U_x$ such that $f \in \prod_x U_x \subset A$. Only finitely many $U_{x_i} \ne \mathbb R$, thus
$$g  :\mathbb R \to \mathbb R, g(x) = \begin{cases} f(x) & x \le  \max x_i \\ f( \max x_i) & x \ge  \max x_i\end{cases}$$
is non-injective but contained in  $\prod_x U_x$. This is a contradiction.
Update:
As it is defined, $\mathbb R^{\mathbb R}$ contains all functions $\mathbb R \to \mathbb R$. We can, however, consider the subset $C$ of all continuous functions $\mathbb R \to \mathbb R$. This subset inherits a topology from $\mathbb R^{\mathbb R}$. The above arguments show that $A_C = A \cap C$ is neither closed nor open in $C$. In fact, the functions $f_n$ and $0$ are in $C$, and if $f\in C$, then also $g \in C$.

A: Can think of $\mathbb R^\mathbb R$ as the product $\prod _{\alpha\in\mathbb R} \mathbb R$. So every map $f$ on $\mathbb R$ is identified with a family $(f(\alpha)) _{\alpha\in\mathbb R} \in \prod _{\alpha\in\mathbb R} \mathbb R$.
A basis in the product topology consists of subsets of the form $\prod _{\alpha\in\mathbb R} U_\alpha$, where $U_\alpha\in\tau _\mathbb R$ and $U_\alpha =\mathbb R$ for almost every $\alpha$.
$A$ is not open. Let $\prod U_\alpha\neq \emptyset$ be basic. There exist $\alpha_1\neq\alpha_2$ such that $U_{\alpha _i} = \mathbb R, \ i=1,2$. Take any $f \in \prod U_\alpha$ that satisfies $f(\alpha _1 ) = f(\alpha _2)$. So $A$ is unattainable as union of basic subsets.
$A^c$ is not open, either because any nonempty basic subset contains injective maps.
Let $U_{\alpha _i} \subset\mathbb R$ be nonempty proper open subsets for $i=1,\ldots, n$. If they are pairwise disjoint, fix any $f(\alpha _i) \in U_{\alpha _i}$ for all $i$. Otherwise pick different elements in case of intersection. Let the largest of the $f(\alpha _i)$ be $M$. Pick your favourite injective map whose values are $>M$ to populate the rest of the family.
E.g take $f(x) = e^x + M$ and then redefine $f(\alpha _i)$ to whatever you picked them to be.


text:
Q: flutter TabBarView doesn't change by TabController by tapping on tabs/tabs doesn't change when swiping but tabbarview does i have been trying lots of solutions on changing appbar title with tabs, and i solved it but now there is a small problem; the appbar does change with the tabs when the tabs are pressed, but not the tabbarview. Swiping left or right on the tab bar view changes the tabbarview but not the tabs(appbar title does not change too).
my code below:
final List<Tabs> _tabs = [new Tabs(title: "Registered UAS", icon: new IconData(58826, fontFamily: 'MaterialIcons')),
new Tabs(title: "Registration", icon: IconData(57680, fontFamily: 'MaterialIcons'))
];

Tabs _myHandler ;

void initState() {
super.initState();
_controller = new TabController(length: 2, vsync: this);
_myHandler = _tabs[0];
_controller.addListener(_handleSelected);
}
void _handleSelected() {
setState(() {
  _myHandler= _tabs[_controller.index];
});
}

@override
Widget build(BuildContext context) {
return WillPopScope(
    child: DefaultTabController(
      length: 2,
      child: new Scaffold(
          appBar: AppBar(
            title: Text(_myHandler.title),
            bottom: new TabBar(
              controller: _controller,
              tabs: <Widget>[
                new Tab(icon: new Icon(_tabs[0].icon)),
                new Tab(icon: new Icon(_tabs[1].icon))
              ],
            ),
          ),
          body: new TabBarView(children: [...])

I followed this for changing appbar title on tab change and now im stuck with a similar situation like this, except i dont think the solution for it works for me(i have tried it)

A: solved it by adding controller: _controller, under TabBarView

A: If you want to use own controller, then you shouldn't use DefaultTabControllerwidget. In example, which you use DefaultTabController is absent.
If you want to use own controller you should use this example.
https://api.flutter.dev/flutter/material/TabController-class.html
If you want to use DefaultTabController without own controller, you should this example.
import 'package:flutter/material.dart';

void main() {
  runApp(TabBarDemo());
}

class TabBarDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: AppBar(
            bottom: TabBar(
              tabs: [
                Tab(icon: Icon(Icons.directions_car)),
                Tab(icon: Icon(Icons.directions_transit)),
                Tab(icon: Icon(Icons.directions_bike)),
              ],
            ),
            title: Text('Tabs Demo'),
          ),
          body: TabBarView(
            children: [
              Icon(Icons.directions_car),
              Icon(Icons.directions_transit),
              Icon(Icons.directions_bike),
            ],
          ),
        ),
      ),
    );
  }
}


text:
Q: local Laravel web page takes several minutes to update I am running an apache server locally and building a web service in Laravel. Yesterday, my local Laravel webpage was very responsive, reflecting any changes made as soon as I saved and refreshed. Today it is taking upwards of 5 minutes for the page to update. I have not changed my code since yesterday. A couple of interesting tidbits...
-I am running the page in Chrome and have disabled caching
-My system clock is set to the correct time
-I have run php artisan clear:compiled with no success
-I have manually deleted cached views in my storage->views folder
-If I send a POST request to my web service with postman, any changes will still take a few minutes to apply
I know this is not a lot to go off of, but I am totally stumped and this is sapping my productivity! Any help would be greatly appreciated.

A: In case anyone else has the same problem, I fixed this by disabling caching in my php.ini file and restarting my server (see this post) why this became an issue out of the blue after several weeks, I have no idea.

A: Even though you have cache disabled in Chrome, I would still do a hard reload. I would also run the following:
php artisan route:clear
php artisan cache:clear

to clear the cache, not needed in dev env, imo.


text:
Q: Check if $_POST is empty I realize this question has been asked multiple times, but none have resolved the issue for me.
I want to check if any values in the $_POST array are empty except for two (sHostFirstName and sHostLastName), and throw a 400 error if there is an empty value. The only way I can get it to throw the 400 error is by putting a die() command after the header command, however I get the 400 error no matter if there are empty values or not.
foreach ($_POST as $key => $value) {
    if (empty($value) || !isset($value) && $key != 'sHostFirstName' || 'sHostLastName') {
        header("HTTP/1.1 400 Bad Request");
        break;
    }
}

A: isset() will return true if the variable has been initialised. If you have a form field with its name value set to userName, when that form is submitted the value will always be "set", although there may not be any data in it.
Instead, trim() the string and test its length
if("" == trim($_POST['userName'])){
    $username = 'Anonymous';
}

A: Something like this
   //store and set default if not set - only needed for checkbox or radio buttons. for example, text fields are always submitted as an empty string.
   $sHostFirstName = isset($_POST['sHostFirstName']) ? $_POST['sHostFirstName'] : false;
  unset($_POST['sHostFirstName']); //remove so it's not part of our count
   //store and set default if not set - only needed for checkbox or radio buttons.
   $sHostLastName = isset($_POST['sHostLastName']) ? $_POST['sHostLastName'] : false;
   unset($_POST['sHostLastName']); //remove so it's not part of our count

   $post = array_filter(array_map('trim', $_POST)); //copy post remove empty items.
   if( count( $post ) != count($_POST)
       //if count $_POST is not the same as count $post ( empty removed via array_filter) then something was removed / empty
       header('HTTP/1.1 400 Bad Request', true, 400);
       exit();
   }

should do after unset is used on them.  See,

*

*store them in variables

*remove them from post

*then remove empty from a copy of post

*count copy ( - empties ) and compare to count of original

*if the count is different then something was removed ( ie. empty )

no need for a loop.
Also you can send the optional 2nd and 3rd params for header:
http://php.net/manual/en/function.header.php

2nd = replace -  The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in FALSE as the second argument you can force multiple headers of the same type.
3rd =  http_response_code - Forces the HTTP response code to the specified value. Note that this parameter only has an effect if the string is not empty.

A: There's no need to loop through your POST data. Store your POST data in a variable $postData and remove the keys sHostFirstName and sHostLastName since these two need not be checked.
This $postData contains all key value pairs which need to be checked for blank entries. Now, use array_filter() to filter out any blank entries and store it in $filteredArray.
Finally, if there were no blank entries, the length of $postData will be same as ``$filteredArray`. If lengths don't match, that will imply one or more array keys had been filtered.
$postData = $_POST;
unset($postData['sHostFirstName'], $postData['sHostLastName']); // $postData contanis all key value pairs which can't be empty

$filteredArray = array_filter($postData); // Filters out the blank entries

/* If the length of `$filteredArray` and `$postData` aren't the same, that means one or more fields had been filtered out */

if (count($filteredArray) != count($postData)) {
    header("HTTP/1.1 400 Bad Request");
}


text:
Q: \maketitle Error \documentclass{doublecol-new}
\def\newblock{\hskip .11em plus .33em minus .07em}

\begin{document}
\setcounter{page}{1}
\LRH{ABCD}
\RRH{EFGH}
\VOL{x}
\ISSUE{x}
\PUBYEAR{xxxx}
\BottomCatch

\PUBYEAR{201X}
\subtitle{}
\title{IJKL}
\authorA{}
\affA{}
\authorB{}
\affB{}
\authorC{}
\affC{}

\maketitle

\begin{abstract}

\end{abstract}

\section{Introduction}

\end{document}

When I try to compile this minimum working example, I get an error

! Output loop---100 consecutive dead cycles.
\clearpage ...rite \m@ne {}\vbox {}\penalty -\@Mi
l.45 \maketitle

Could anybody please help me fix this?
PS: Link to the .cls file: http://www.inderscience.com/www/download/latex-double-column.zip.
Unzipping the linked file would provide the .cls file.

A: The document works if you force the old behaviour by adding
\RequirePackage[2014/01/01]{latexrelease}

as the very first line.
There were several fixes to the float handling in double column documents in the 2014 and 2015 latex releases, and these combined with the rather bizarre coding on the class file cause latex to loop.
I'm just looking to see if the format can be made more robust to give a more helpful error (or work) but the above should get you working again. The main problem is that \BottomCatch causes a float of negative height (height -7pt, depth 0pt) to be added and while normally latex copes with such things here it fails to flush the float at \end{document} (so tries 100 times then gives up with an error).

Actually it is hard to blame the class file, here is a MWE just using article
%\RequirePackage[2014/01/01]{latexrelease}

\documentclass{article}

\begin{document}

\begin{table}
\vspace{-15pt}
\end{table}

\end{document}


text:
Q: Summing infinitesimals to 1 Tl;dr: Could someone give me an explanation as to how infinitesimal numbers might be added together to get 1?
Why I want to know: some people (philosophers) like to introduce infinitesimals into probability theory when considering cases like an infinite amount of coin tosses. To say that the event that this coin will land heads every time has probability 0, they think, is bad, as probability 0 should be reserved for the impossible. Instead, they say it should have an infinitesimal probability.
Fair enough. But presumably, the probability that the coin corresponds to some infinite sequence of heads and tails is 1. If we like countable additivity, this means the probability of all the possible infinite sequences should sum up to 1.
Apparently this is consistent with their theory. Each infinitesimal probability of each infinite sequence will, when added together, equal 1.
I'm confused as as to how this could happen. Why would an infinite amount of infinitesimals add up to 1, and not, say, 2?

A: The short answer is you need to integrate up the infinitesimals, rather than summing them. This is because infinitesimal probabilities emerge from continuous distributions. With a pdf $f(x)$, $f(x)dx$ is an infinitesimal probability for $x$ existing in a width-$dx$ range of values.
We can flesh this out. Take an infinite sequence of coin tosses and label the tosses with integers $\ge1$. If $S$ is the set of tosses yielding heads, associate the sequence with $x(S):=\sum_{n\in S}2^{-n}\in[0,\,1]$. In countably infinitely many cases, a number is achievable with multiple sequences; but integration doesn't care about that. For any subset $T$ of $[0,\,1]$ for which $\int_Tdx$ is defined, we can say that integral is the probability of the sequence's representation being an element of $T$. Unitarity is then the condition $\int_0^1dx(S)=1$.

A: Note that the geometric series $$1/2 + 1/4 +1/8+.... =\sum _1 ^\infty \frac {1}{2^n} =1$$
More interesting is for a small positive real number $\epsilon$ $$\sum _1 ^\infty \frac {\epsilon}{2^n} =\epsilon $$
Therefore you can add  infinitely many "infinitesimals and  get another infinitesimal.


text:
Q: Leetcode Two Sum Python Solution not working when I submit on Leetcode, but works on other compiler I've just started using leetcode and I don't know if I'm wrong or if there's some bug in leetcode.
This is the code I typed on Leetcode to solve the Two Sum question that didn't work
class Solution:
    def twoSum(self, nums, target):
        i=0
        j=0
        for k in nums:
            for l in nums:
                if i!=j:
                    if (nums[i]+nums[j])==target:
                        return [i,j]
                j+=1
            j=0
            i+=1

This is the code I typed on Programiz online compiler that worked
class Solution:
    def twoSum(self, nums, target):
        i=0
        j=0
        for k in nums:
            for l in nums:
                if i!=j:
                    if (nums[i]+nums[j])==target:
                        return [i,j]
                j+=1
            j=0
            i+=1

testCase=[3,2,4]
target=6
test=Solution()
print(test.twoSum(testCase,target))

Both of them had the same test case, but my code works on programiz and not on Leetcode

A: The solution you mentioned

Time Limit Exceeded

Although the code runs fine for some small inputs, it fails the time limit of one big input,
because of two for loops.
Try this,
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
     dic = {}

    for i, v in enumerate(nums):
        remaining = target - v

        if remaining in dic:
            return [dic[remaining], i]
        dic[v] = i


text:
Q: how to select css class attributes from mootools,getStyle()? I need to clone an object and I try to find how to retrieve class css attributes from mootools
css:
.card {
width: 109px;
height: 145px;
}

html:

js:
window.addEvent('domready', function(){
 Duplicacartes();
});
function Duplicacartes(){
 var uiCards= document.getElementById('cards');
 for(var i=1;i<521;i++)
{
        var clone = $('c0').clone();
        clone.set('id', 'c'+i);
        clone.setStyle('left', (clone.getStyle('width') + 20) * (i % 40));
        clone.setStyle('top', (clone.getStyle('height')  + 20) * Math.floor(i / 40));
        clone.inject('cards','bottom');

}

but I have not result:
The function clone.getStyle(), not gets the class CSS attributes, only the 'element' attributes.
I was tryed for a lot of ways without success.
$('c'+i).getStyle('width');
$('c'+i).style.width;
...

What is the way to do this? thanks

A: I don't think you can get that from the cloned element, but you could copy that from the original and use .getComputedSize() like this:
var computed = $('c0').getComputedSize();

So your function could look like:
window.addEvent('domready', function () {
    Duplicacartes();
});
function Duplicacartes() {
    var uiCards = document.getElementById('cards');
    var computed = $('c0').getComputedSize();
    for (var i = 1; i < 521; i++) {
        var clone = $('c0').clone();
        clone.set('id', 'c' + i);
        clone.setStyle('left', (computed.width + 20) * (i % 40));
        clone.setStyle('top', (computed.height + 20) * Math.floor(i / 40));
        clone.inject('cards', 'bottom');

    }
}

Fiddle
Note:
- I added also position:absolute; to the css.
- .getComputedSize() is part of More, so you need to load More also.

A: Element Method: getStyle
GetStyle() returns css property of the Element as string ( in this case returns width as "300px"). Because of that the mathematical formula is incorrect and returns NaN ( "Not-a-Number" value ), so left and top css styles are not set by MooTools.
Therefore width and height properties should be converted to an integer with toInt() function:
clone.getStyle('width').toInt()

Because of creation of large number of elements some optimization of the script is required, like not saving a reference of cloned element, and also, it is enough to find the element to be cloned only once.
window.addEvent('domready', function(){;
    Duplicacartes();
});

function Duplicacartes() {
    var card = $('c0');
    for ( var i=1; i<521; i++ ) {
        card.clone().set({
            id: 'c'+i,
            styles: {
                left:   (card.getStyle('width').toInt() + 20) * (i % 40),
                top:    (card.getStyle('height').toInt() + 20) * Math.floor(i / 40)
            }
        }).inject( 'cards', 'bottom' );
    }
}


text:
Q: How do I list databases on SQL Azure server using SMO when not all databases have the user used to connect to the server? SMO's Server.Databases will throw an exception if one database on the server does not have the SQL User I've used to create the SMO server connection with.
I don't get this same error to occur if using a local SQL 2017 instance.
For example:
I have a SQL Azure server named 'myazuresqlserver.database.windows.net'

*

*Create a login on master:
CREATE LOGIN testlogin WITH PASSWORD = 'ThisIsMySecretPassword'

*Create 2 databases, DB1 and DB2.

*Create the User 'testuser' in DB1 but NOT DB2:
CREATE USER testuser FOR LOGIN testlogin
Then, using C# and SMO I cannot get a list of databases for that server using the credentials for the testlogin login - an exception occurs.
static void Main(string[] args)
{
    string[] names = GetDatabaseNames("myazuresqlserver.database.windows.net");
}

public static string[] GetDatabaseNames(string serverName)
{
    ServerConnection connection = new ServerConnection(serverName, "testuser", "ThisIsMySecretPassword");
    var server = new Server(connection);
    return (from Database database in server.Databases
        where !database.IsSystemObject && !database.IsDatabaseSnapshot
        select database.Name
       ).ToArray();
}

The exception is:
SqlException: The server principal "testlogin" is not able to access the database "DB2" under the current security context.
Cannot open database "DB2" requested by the login. The login failed. Login failed for user 'testlogin'.

I would have expected no exception to be thrown, and instead the Server.Databases to only contain databases which the credentials provided were valid - this seems to be the behaviour for a local SQL 2017 instance.

A: I came across the same issue. It's as if attempting to look at Server.Databases at all causes enumeration to occur, and in doing so database properties are being looked at - properties that the user may not have permission to interrogate. An exception is thrown immediately.
I ended up using a different technique to get a list of databases. I simply fired a sql query:
SELECT name FROM sys.databases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');

For the above query to work, the user must have permission to access the master database. Here is my code block:
Dim Server As Server = New Server(New ServerConnection("myserver.server.net", "testlogin", "password"))
Dim databaseList As New DataTable
databaseList.Columns.Add("Name")

If Server.Edition = "SQL Azure" Then
    Dim SQLReader As SqlClient.SqlDataReader = Nothing
    Try
        SQLReader = Server.ConnectionContext.ExecuteReader("SELECT name FROM sys.databases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');")

        Do While SQLReader.Read = True
            databaseList.Rows.Add(Manager.Database.Sanitise(SQLReader, "name").ToString)
        Loop

        SQLReader.Close()
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        If Not SQLReader Is Nothing Then
            SQLReader.Close()
        End If
    End Try
End If


text:
Q: RegEx replacing IMG src attributes I have a var baseURL that I know is: baseURL = c:\whatever\mybasedir\
I have an HTML source code that may contain this:

or/and:

or/and:

or/and:

I need to replace all src tags so that result path is Unix style relative to baseURL:

or if there was an alt attribute (or other. order of attributes may vary):

How do I match ?
Any ideas what RegEx (or other method) can help here?
(I cannot use DOM to do this job, since the IE8/9 DOM is causing this situation in the first place - automatically adding <base href> to all relative src tags)

A: You can do
Regex: (]*)src="[^"]*c:.whatever.mybasedir.
Replace with:$1src="

A: Replace ()
with $1$3
EDIT
Hope this will work
Replace ()
with $1$3$4$6


text:
Q: Give moderators a bit more control over the Community Bulletin A few weeks ago, I featured a meta post: Vote Early, Vote Often to encourage folks to vote.  Today, I got sick of seeing it (and not noticing any effect), so I removed the featured tag.  This is the result:

Now I think the reason is that when I removed the tag, it bumped the question, which caused the algorithm to pick it as a "hot discussion" item.  (Yes, our meta is so slow that the mere act of removing a tag can make a meta post "hot".)
Initially, I was going to suggest a tweak in the algorithm, but it occured to me that the problem really is that the community can't control what gets posted there.  For instance, I'm not sure how interested our users are in Stack Overflow blog posts.  (And if they are interested, it's because they are SO users already.)  Most offices, schools, hospitals, etc. have strict rules on what gets nailed up and requires notes that don't meet the criteria to be taken down.  Nobody, not even ♦ moderators, can do that on Stack Exchange.
Don't get me wrong: I like the automated posting feature.  For many sites, it should work well with a few tweaks here and there.  But the bulletin will be more useful if it can be curated by some actual person who knows the community and its needs.  At a minimum (and this might be all that is needed) moderators should be able to remove notifications that don't speak to their community.

A: Actually, it just takes a while for that bulletin to refresh - the contents are cached, so removing featured doesn't immediately remove it from the list.
You can tell, because featured / scheduled posts are shown at the top, followed by blog posts, followed by a random selection of "hot" questions. FWIW: these are your hot meta questions (those scoring 3 or more will be eligible for the board).
If you look at the site now, it's gone.
I should also mention: the goal here was to provide moderators with enough control over the contents that they could always feature the posts they wanted, while making sure that other activity was displayed in situations when there was nothing so pressing that it needed to be there. Hence the blog (note that sites with blogs get their own blog posts listed as well) and the random selection of hot posts.


text:
Q: Python program,assign_add, the result might be a little confusing
   b= tf.ones([3,3],dtype=tf.float32)
   c= tf.Variable(tf.random_normal([3,3],mean=1,stddev=2,dtype=tf.float32),name="c")
   d=tf.assign_add(c,b)
   init_op= tf.global_variables_initializer()
   with tf.Session() as sess:
     sess.run(init_op)
     x,y,z= sess.run([c,b,d])
     print(x,"\n!!\n",y,"\n!!\n",z,"\n!!")
     print(sess.run(d))

the third array output result should be added  'b' and 'c', but the result did not print as expected. Can you help me? Many thanks.
I expect the third Array output result should be the same as the fourth Array. I am confused at the third Array result.

A: It seems like contrary to how I understand the docs on assign_add, this op might actually return the value of the variable before the adding is done, not after.
So in this example c is the variable with value [[4.723362, ...]]. In the first sess.run, you are printing c which has the pre-assign_add value since the update is done after, b which looks as expected and d which also returns the pre-assign_add value because that's presumably how the op works.
After this, c is updated to now contain values [[5.723362, ...]]. Now you run d (the assign_add op) again, which updates c but once again returns the pre-update value, which is [[5.723362, ...]].
In conclusion, if we accept that the return value of tf.assign_add is the variable before adding, and that running c along with d in the first "parallel" run call will return c before doing the update, this makes sense. You could verify this by adding a sess.run(c) at the very end, which should return [[6.723362,...].


text:
Q: Angular Material - prevent default on md-tab I have a number of tabs, representing different services. I wish to have a final 'tab' tagged on the end of the list used to add a new service. Denoted by a simple '+'. This will open a simple dialogue.
I was hoping I could put my own ng-click behaviour on this single tab and prevent default but this doesn't work.
Is there any way I can 'catch' the tab click event BEFORE the tab body switch takes place and prevent it from happening?

A: It seems that it is not possible at the moment (see e.g. https://groups.google.com/forum/#!topic/ngmaterial/rNWMk3S9uDI) - at least using official api.
If you are ok with a solution which hacks into the directive internals then you can do following:
angular.module('MyApp').directive('tabWatcher', function() {
return {
    require: ['mdTabs'],
    restrict: 'A',
    link: function(scope, el, attrs, controllers) {
        var mdTabsCtrl = controllers[0];
        var origSelectFn = mdTabsCtrl.select;

        // overwrite original function with our own
        mdTabsCtrl.select = function(index, canSkipClick) {
            if (...) {
                origSelectFn(index, canSkipClick);
            }
        }
    }
};

I've placed a demo here http://codepen.io/jarek-jpa/pen/wGxqOq . Try to click some tabs. The select() call will be intercepted and depending on a condition let pass or not.
Disclaimer: Again, it hacks into the md-tabs directive internals, so may stop working any time (tested with angular-material 1.0.7)

A: You can set pointer-events to none to prevent the md-tab from responding to clicks.
Example:
<style>
md-tabs.readonly {
  pointer-events: none;
  user-select: none;
}
</style>

<md-tabs class="readonly">
  <md-tab label="can't touch this"></md-tab>
</md-tabs>

This is tested to work with Angular Material 1.0.1


text:
Q: Special case of Karatsuba algorithm I need some help with the following problem:
Let's consider a computer with word length of sqrt(n) bits. That means that any  multiplication between 2 sqrt(n)-bit integers is O(1).
The problem is to prove that the complexity of doing with this computer the multiplication of 2 n-bit integers using the Karatsuba algorithm is O(n^1.29).
I have tried to write a recursive relation like:
        T(sqrt(n)) = 3T(sqrt(n)/2) + Θ(sqrt(n))
Then, by replacing sqrt(n) with n, I end up with: T(n) = 3T(n/2) + Θ(n)
which gives T(n) = Θ(n^1.58).
I can't understand where I have made a mistake.
Thank you very much!!

A: You have correctly stated that the original recurrence relation is T(n) = 3T(n/2) + Θ(n); the logical error you made was to directly replace n with sqrt(n).
What you must instead do here is re-derive the time complexity with a different stopping condition - i.e. T(m) = O(1) Ɐ m ≤ sqrt(n). The given result T(n) = Θ(n^1.58) follows from making the stopping condition equal to some small constant, which is not the case here.
Let's repeatedly expand this recurrence:

... and apply the modified stopping condition:

... using some logarithm laws. And thus we arrive at:

... which is the required result.


text:
Q: Best way to notify user that jobs is done using RabbitMQ and WebSockets I'm using Yii2 and yii2-queue extension to push jobs in RabbitMQ in some queue.
These jobs are importing xls|csv files to the database. At the end of job I send message to another queue - listens by python pika, and send to client by websocket.
php, piece of Job code, that sends new message
if (!empty($imported)) {

            $connection = new AMQPStreamConnection($queue->host, $queue->port, $queue->user, $queue->password);
            $channel = $connection->channel();

            $channel->queue_declare('import_queue', true, true, false, false);

            $message = 'Catalog, imported items: ' . count($imported);
            $message = new AMQPMessage($message, [
                'content_type' => 'text/plain',
                'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT
            ]);

            $channel->basic_publish(
                $message, '', 'import_queue'
            );

            $channel->close();
            $connection->close();
        }

python code.
credentials = pika.PlainCredentials('admin', 'password')
parameters = pika.ConnectionParameters('localhost',
                                       5672,
                                       '/',
                                       credentials)

amqp_conn = pika.BlockingConnection(parameters)
amqp_ch = amqp_conn.channel()

def threaded_rmq():
    amqp_ch.queue_declare(queue="import_queue", durable=True)
    amqp_ch.basic_consume(callback, queue="import_queue", no_ack=True)
    amqp_ch.start_consuming()

def callback(ch, method, properties, body):
    data = {'type': 'imported_catalog_items', 'message': body}
    json_data = json.dumps(data)
    for client in clients:
        client.sendMessage(u'' + json_data)

def disconnect_to_rabbitmq():
    amqp_ch.stop_consuming()
    amqp_conn.close()

The problem:
I don't know when the last job will be done.
When user sends file, I block the html form and apply loader icon.
I set session var to block this. I want to unblock the form, (remove the loader) when all jobs will be executed, and notify user that "Import jobs is done".
What is the best way to do that? Thanks.


text:
Q: Is there a regexp to match 2 char multiple times? I have a regex problem I can't seem to solve. The pattern is of 2 characters A and B. They can occour multiple times but change only once.
For example, I want to match

*

*AAABBB

*AABBBBB

*AAAA

*BBBBBB

*BBAAAA

but not

*

*ABAB

*AAABBBBA

Is there some regex pattern that can do this?

A: Try This :

var patt = /(^A+B*$)|(^B+A*$)/

console.log(patt.test('AAABBB'));
console.log(patt.test('AAABBAA')) ;
console.log(patt.test('BBBBAAAA'));
console.log(patt.test('BBBB'))


text:
Q: Как юзать VK API в Украине? У меня есть скрипт с VK APi. Но чтобы его запустить я юзаю PythonAnyWhere. Но проблема в том, что в скрипте есть ещё и парсер. А сайт не пропускають запрос с IP PythonAnyWhere. Как мне запустить скрипт на своем ПК?

A: *

*Используйте прокси и/или vpn.

*Купите платную подписку pythonanywhere

*Пользуйтесь другими хостингами, например, есть бесплатный heroku, на нем все запросы проходят на ура


text:
Q: Filtering array with RXJS I am trying filtering the return of HTTP request in Angular 7 using RXJS6.
I must filter the response; only get the Users with IdSkill equals to 1234.
However, I cannot achieve this. I just received this error:
Type 'Observable' is not assignable to type 'Observable>'.
  Type 'User[]' is missing the following properties from type 'Pagination': total, items
RXJS is not my strong skill; I just use the basics, only to do simple get/post HTTP requests.
My code:
/* Interface */
export interface Pagination<t> {
    total: number;
    items: t[];
}

export interface User {
    idUser: number;
    name: string;
    active: boolean;
    skill: Skill;
}

export interface Skill {
    idSkill: number;
    name: string;
}

/* Service */
getUsers(): Observable<Pagination<User>> {
    return this._httpClient.get<Pagination<User>>(
      'http://localhost/api/users',
      { headers: this._auth }
    ).pipe(
      filter(x => x.items.filter(user => user.skill.idSkill == 1234))
    );
}

Thank you

A: The operator you need would be a map, since you want to remap (filter) your inner result. RxJs filter is used when you want to filter the result itself that was emitted from Observable.
import { map } from 'rxjs/operators';

/* Service */
getUsers(): Observable<Pagination<User>> {
    return this._httpClient.get<Pagination<User>>(
      'http://localhost/api/users',
      { headers: this._auth }
    ).pipe(
      map((pagination: Pagination<User>) => ({
         ...pagination,
         items: pagination.items.filter(user => user.skill.idSkill == 1234)
      }))
    );
}

A: Your endpoint returns what is returns so simply use find to get the single match out of it. Or filter to give you an array of matches.
getUsers(): Observable<Pagination<User>> {
    return this._httpClient.get<Pagination<User>>(url,{ headers: this._auth })
       .pipe(take(1))
       .subscribe(users => {

            // finds a single result
            theObject = users.find(obj => obj.IdSkill == 5);

            // return an array of all matching results
            arrayOfResults = data.filter(obj => obj.IdSkill === 'JavaSc');

       });
}


text:
Q: css nth-child selector not working I am trying to skip every third element, 1,2,4,5,7,8 etc... should have a margin-right of 9px and every 3rd should have a margin-right of 0 so I am using the code below with no luck!
css
.thumbImg:nth-child(3n + 1), .thumbImg:nth-child(3n + 2)  {margin-right:9px;}

HTML

JSFIDDLE
https://jsfiddle.net/fnc69q9m/

A: You did it on the wrong element. It should be the  not the  inside it.
Updated demo
a:nth-child(3n+1),
a:nth-child(3n+2) {
    margin-right:9px;
    border-bottom:10px red solid;
}

or
a:nth-child(3n+1) img,
a:nth-child(3n+2) img {
    margin-right:9px;
    border-bottom:10px red solid;
}


text:
Q: Is it possible to customize Dconf's file storing path? Is it possible to customize Dconf's file storing path?
I'd like to store Dconf configuration file in one of my synced directory, like Google-Drive/Dropbox or any other for constant syncing.
Let's say I have Dropbox auto synced directory at ~/Dropbox
I'd like to store Dconf config file at:
~/Dropbox/dconf
so that it's is autamatically synchronised (by Dropbox client) and I have settings backuped.

A: man 7 dconf explains that the user configuration is saved by default in file $XDG_CONFIG_HOME/dconf/user. Depending on your system, this often means file ~/.config/dconf/user when XDG_CONFIG_HOME is not defined.
You should be able to move this directory to the wanted place, and replace  it with a symbolic link. Eg
mv ~/.config/dconf ~/Dropbox/
ln -s ~/Dropbox/dconf ~/.config/dconf

Alternatively, you can make a bind mount which makes the same directory appear in 2 different places:
mkdir ~/Dropbox/dconf
sudo mount -o bind ~/.config/dconf ~/Dropbox/dconf

To undo the binding use sudo umount ~/Dropbox/dconf.


text:
Q: how to change the value of json file after comparing its element to another json file? I've two json files named one.json and two.json, one.json has multiple projectId's if the value of any ProjectId of one.json matches to ID of two.json the completedCount of two.json should change to completedCount of one.json for the matching ID...
I don't know how to read or write the JSON file using JavaScript as i'm very new to JavaScript, so any help with that will also be appreciated
I've tried it using array.
one.json is as follows
[ { projectId: '230',
    title: 'Nikhil',
    status: 'Nikhil',
    seenCount: 0,
    inProgressCount: 0,
    completedCount: 30 },
  { projectId: 434,
    title: null,
    status: null,
    seenCount: 0,
    inProgressCount: 0,
    completedCount: 1 } ]

two.json is as follows
[ { id: '434',
    name: 'project-qa-test',
    customQuestion: 'What did you get done today?',
    maxSyncItems: null,
    orderIndex: 0,
    hidden: false,
    dones: [],
    unReported: 0,
    seenCount: 0,
    inProgressCount: 0,
    completedCount: 0 } ]

need to update the value of completedCount in two.json and print it using javaScript...

A: Below code should solve your issue of reading, logic and writing into your file.
'use strict';

const fs = require('fs');

let rawdata_one = fs.readFileSync('one.json');
let rawdata_two = fs.readFileSync('two.json');
let onedata = JSON.parse(rawdata_one);
let twodata = JSON.parse(rawdata_two);

onedata.forEach(
    function(obj){
        let ob = twodata.findIndex( o => o.id == obj.projectId );
            if(ob != -1){
                twodata[ob].completedCount = obj.completedCount;
            }
     }
 )

 let data = JSON.stringify(twodata);
 fs.writeFileSync('two.json', data);

This write will overwrite your two.json with the updated data.
You can also read the json file using require('one.json'). However, it can be done only once in your entire code.

A: Slight improvement in above answer :
  one.forEach((obj) => {
      let ob = two.find( o => o.id == obj.projectId );
      if(ob) { ob.completedCount = obj.completedCount };
      console.log(ob);
  })


text:
Q: Request processing failed; nested exception is org.hibernate.QueryException: @Transactional
@Modifying
public boolean deleteBook(String callno, String studentid) {

    boolean userFounds= false;

    Session session=this.sessionFactory.openSession();
     System.out.println("check update:"+callno);
     System.out.println("check update:"+studentid);

        // delete operation
    String SQL_QUERY2 ="delete from IssueBook where callno= ? and studentid=?";

    Query query= session.createQuery(SQL_QUERY2);

     query.setParameter(0, callno).executeUpdate();
     query.setParameter(1, studentid).executeUpdate();
     return userFounds;

    }

i am getting 500-server exception
on  here
     query.setParameter(0, callno).executeUpdate();
         query.setParameter(1, studentid).executeUpdate();
See stacktrace:

A: String SQL_QUERY2 ="delete from IssueBook where callno=:callno and studentid=:studentid";
Query query= session.createQuery(SQL_QUERY2);
     query.setParameter(callno, callno);
     query.setParameter(studentid, studentid);
     return query.executeUpdate();

The issue in your code is executeUpdate() should be invoked once after setting all the parameters.


text:
Q: Only Title bar shows, the JFrame is not showing The title bar only shows after I click run, the frame is not working....
Here is my code
I have no ideas what is going on!
Can someone help me?
import java.awt.Canvas;
import javax.swing.JFrame;

public class Display extends Canvas implements Runnable {

    private static final long serialVersionUID = 1L;
    public static final int WIDTH = 800;
    public static final int HEIGH = 600;
    public static String TITLE = "3D Game";

    private Thread thread;
    private boolean running = false;
    private void start(){
        if(running) return;
        running = true;
        thread = new Thread();
        thread.start();

        System.out.println("Working");
    }

    private void stop(){
        if(!running)
            return;
        running = false;
        try{
        thread.join();
        }catch (Exception e){
            e.printStackTrace();
            System.exit(0);
    }
    }
    public void run(){
        while(running){

        }
    }

    public static void main(String[] args){

        Display game = new Display();
        JFrame frame = new JFrame();
        frame.add(game);
        //frame.pack();
        frame.setTitle(TITLE);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(WIDTH,HEIGHT);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true);

        game.start();

    }

}

A: Take a look at the difference between
public static final int HEIGH = 600;

and
frame.setSize(WIDTH, HEIGHT);

Canvas indirectly defines two public static fields called WIDTH and HEIGHT set to 1 and 2 respectively
A better solution would be to override Canvass getPreferredSize method and return the preferred size you want...
@Override
public Dimension getPreferredSize() {
    return new Dimension(800, 600);
}

The you can just use pack
Display game = new Display();
JFrame frame = new JFrame();
frame.add(game);
frame.pack();
frame.setTitle(TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);

A word or warning against using setSize on a top level container.  A window normally contains frame decorations, these are included WITHIN the windows bounds. If you use setSize, you are reducing the content area by the amount of window decorations, which will result in a smaller then expected size.  Instead, you should override the getPreferredSize method of your main container and call pack. This allows the window to "pack" itself around the content, but leave space for the frame decorations, preserving the space you have requested.

You can also have a look at:

*

*How to get JPanel equal width and height

*How to get the EXACT middle of a screen, even when re-sized

*Graphics rendering in title bar

*How can I set in the midst?
For more details

A: You have made a typo when declaring the static height variable, You have declared it as "HEIGH" but in the JFrame you have used the word "HEIGHT"
public static final int HEIGH = 600;

frame.setSize(WIDTH,HEIGHT);

So change the variable to HEIGHT and it should work


text:
Q: Struct c# and the memory related to it given Struct Point :
public struct Point {
    double x, y;
    Point(double i, double j) {
        x=i;
        y=j;
    }
}

Q1:whats the diffrence between:
Point p;

and
Point p=new Point(2.0,3.0);

as i understood it, in the second part annonymous Point struct is being allocated on the heap, and is being copied bit by bit to the p variable's memory allocated on the stack. am i correct?
Q2:what do i need to do to carry reference to Point instead of allocating it on stack  and passing it around by value? (without using unsafe pointers)
class Linear {
    private double m, n;
    ref Point p = new Point(2.0,3.0); // not compiling
}

A: class Wrapper
{
    public Point Point { get; set; }
}

Using a reference type (class) wrapping a value type (struct) you will allocate it in the heap.

A: A1: In the first statement you are just declaring the variable, you're not creating an instance of the struct, as you do in the second statement.
A2: You need to use the REF keyword where you are 'giving' the object to another method, not where you are declaring the variable.

A: I usually create a very simple class if I do not want a valuetype struct. Which would look soemthing like the code below for your example. A class will prevent struct boxing/unboxing performance hits in some situations. But if you have a List<> of structs it is a single block of memory for all data. With List<> of class you get a a single block of pointers to a lot of class instances.
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Point
{
    public double x, y;

    public Point(double i, double j)
    {
        x = i;
        y = j;
    }
}

A: In the second statement, an anonymous temporary storage location of type Point is created, most likely on the stack, and it it is passed as an implicit ref parameter to a parameterized constructor.  After the constructor is complete, the Point variable p is mutated by overwriting each field (public or private) with the corresponding fields in that anonymous temporary, which is then abandoned.  Note that the behavior is the same whether or not the struct pretends to be immutable.


text:
Q: Issue with oauth2 , can't get access_token when it is created I've spent nearly 5 hours searching on internet trying to solve this problem and nothing comes up. I want to get my access_token when it is created, save it into a variable, and then store it on db. However, I can't extract the created access_token.
package main

import (
    "fmt"
    "log"
    "net/http"

    oauth2 "gopkg.in/oauth2.v3"
    "gopkg.in/oauth2.v3/models"

    "gopkg.in/oauth2.v3/errors"
    "gopkg.in/oauth2.v3/manage"
    "gopkg.in/oauth2.v3/server"
    "gopkg.in/oauth2.v3/store"
)

func main() {
    manager := manage.NewDefaultManager()

    manager.SetAuthorizeCodeTokenCfg(manage.DefaultAuthorizeCodeTokenCfg)

    manager.MustTokenStorage(store.NewMemoryTokenStore())

    clientStore := store.NewClientStore()
    clientStore.Set("12345", &models.Client{
        ID:     "12345",
        Secret: "12345",
        Domain: "http://localhost:9094",
    })
    manager.MapClientStorage(clientStore)

    srv := server.NewDefaultServer(manager)
    srv.SetAllowGetAccessRequest(true)
    srv.SetClientInfoHandler(server.ClientFormHandler)
    manager.SetRefreshTokenCfg(manage.DefaultRefreshTokenCfg)

    srv.SetInternalErrorHandler(func(err error) (re *errors.Response) {
        log.Println("Internal Error:", err.Error())
        return
    })

    srv.SetResponseErrorHandler(func(re *errors.Response) {
        log.Println("Response Error:", re.Error.Error())
    })

    http.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
        srv.HandleTokenRequest(w, r)
    })

    http.HandleFunc("/protected", validateToken(func(w http.ResponseWriter, r *http.Request) {

        w.Write([]byte("Hello, I'm protected"))
    }, srv))

    log.Fatal(http.ListenAndServe(":9099", nil))

}

func validateToken(f http.HandlerFunc, srv *server.Server) http.HandlerFunc {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        _, err := srv.ValidationBearerToken(r)
        if err != nil {
            http.Error(w, err.Error(), http.StatusBadRequest)
            return
        }
        f.ServeHTTP(w, r)
    })
}

I would appreciate any help, since I'm just a trainee programmer and this is still new for me.
Thanks :).

A: Never mind, it's impossible to get the token due the plugin do the job for you.!!!


text:
Q: The result of a modulo operation is negative Why does the following C code produce negative numbers as output? And how do I prevent this from happening?
    #include <stdio.h>

    int main()
    {
            int i;
            char buf[1024];
            for (i = 0; i < 1024; i++)
                    buf[i] = i%256;

            for (i=0; i<1024; i++) {
                    printf("%d ", buf[i]);
                    if (i%32==31)
                            printf("\n");
            }
    }

A: Let's look at this line of code:
buf[i] = i%256;

Here, i % 256 is computed as a value of type int. However, buf is an array of chars, so when the value is assigned into the array, it's truncated to a char. If the result of the modulus is outside of the range of positive values that can be stored in a char, it may end up wrapping around and being stored as a negative number instead.
In other words, it's not that the modulus produced a negative value as much as you stored the result in a type that can't hold it. Try changing the array to an int array or unsigned char array and see if that fixes things.
Hope this helps!


text:
Q: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1] I have exception when I want to read JSON array from local address php.
String in php looks like this:
[{"firstname":"ime1","lastname":"prezime1"},{"firstname":"ime2","lastname":"prezime2"},{"firstname":"ime3","lastname":"prezime3"}]

And my code for loading looks like this:
JSONArray jsonArray = new JSONArray("http://192.168.1.23/get_people.php");

Exceptoin is:
org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]

A: You have an exception because your application never calls your service url http://192.168.1.23/get_people.php. So, when you use new JSONArray("http://192.168.1.23/get_people.php"), the application tries to create a JSONArray using the string "http://192.168.1.23/get_people.php", and not considering the return value of your ws.
There are many ways to consume a WS, you can look at restTemplate, cxf or other library.


text:
Q: layout:weight on Button change Android I want to make a MediaPlayer and control Play and Pause with the same button.
I did this:
play.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            try {
                if(mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                    play.setBackgroundResource(R.drawable.play);
                } else {
                    mediaPlayer.prepareAsync();
                    play.setBackgroundResource(R.drawable.pause);
                }
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    });

and this is the layout code for that:
<ImageView
        android:id="@+id/play"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight=".33"
        android:layout_marginRight="6dp"
        android:src="@drawable/play" />

Everything works fine except the fact that the button Pause shows up and it keeps its full size, the

android:layout_weight=".33"
  command doesn't apply on it.

What is the problem? and how can I fix it?

A: It's seem that you changed the background image instead of the image of ImageView.
You may try:

*

*setImageResource instead of setBackgroundResource (http://developer.android.com/reference/android/widget/ImageView.html#setImageResource(int))

*add  android:scaleType="centerInside" to ImageView xml

*change to android:layout_width="0dp"

A: if(!mediaPlayer.isPlaying()){
    mediaPlayer.start();
    buttonPlayPause.setImageResource(R.drawable.button_pause);
}else {
    mediaPlayer.pause();
    buttonPlayPause.setImageResource(R.drawable.button_play);
}


text:
Q: Polymer Iron Flex Layout Classes Not Working I was trying to use iron-flex-layout during the development of a website and became extremely frustrated when I spent hours try to get it to work, but to no avail. Eventually, I decided to try a bare-bones web page to see if it would work (thinking that it was probably something in my website). However, I tried the following code and I still can't get it to work! Can anyone spot my errors?

        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="import" href="bower_components/iron-flex-layout/iron-flex-layout.html">

div

flex (horizontal layout)

div

Here is what the result is supposed to look like
And here is what I am getting

A: If you want to use the CSS classes, you need to import them separately:
<link rel="import" href="bower_components/iron-flex-layout/classes/iron-flex-layout.html">
The import you have only gives you access to the @apply mixins. Do note that Polymer is dropping /deep/ support in their elements and are encouraging people to use the mixins instead of the classes: https://blog.polymer-project.org/announcements/2015/12/01/deprecating-deep/


text:
Q: Reading List of Node using Xpath this is my XML file :
<sitemesh>
    <mapping path="/editor/tempPage/**" exclude="true"/>

        <mapping decorator="/WEB-INF/views/decorators/detailstheme.jsp"
            path="/*" exclude="false" />

    </sitemesh>

I want list of mapping node with their attribute  values.
this should be done using Xpath.
my xpath expression is :
expr = xpath.compile("/sitemesh/mapping");

but i am getting null in nodelist.
this is my code:
Map<String,String> map=new HashMap<String, String>();

        // reading xml file
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        Document doc = null;
        XPathExpression expr = null;
        try {
            builder = factory.newDocumentBuilder();
            // creating input stream
            doc = builder.parse(file);
            XPathFactory xpf = XPathFactory.newInstance();
            XPath xpath = xpf.newXPath();
            expr = xpath.compile("//mapping");
        } catch (Exception e) {
            LOG.error("some exception message", e);
        }

        //------------------------------------------------------------------------

        NodeList attributeElements = null;
        try {
            attributeElements =(NodeList)expr.evaluate(doc, XPathConstants.NODE);

        } catch (XPathExpressionException e) {
            LOG.error("some exception message", e);
        }
        System.out.println("lenght:"+attributeElements.getLength());
        for (int i = 0; i < attributeElements.getLength(); i++) {
                Node node=attributeElements.item(i);
                System.out.println("node:"+node.getNodeValue());
             NamedNodeMap attrs = node.getAttributes();
              for(i = 0 ; i<attrs.getLength() ; i++) {
                Attr attribute = (Attr)attrs.item(i);
                System.out.println("Node Attributes : " + attribute.getName()+" = "+attribute.getValue());
              }
        }

        //-------------------------------------------------------------------------

        // writing xml file
        TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
        Transformer transformer;
        try {
            transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(file);// creating output
                                                            // stream
            transformer.transform(source, result);
        } catch (Exception e) {
            LOG.error("some exception message", e);
        }

        return   map;

i am getting null for attributeElements

i want to show values of path,decorator and exclude on JSP page.But i am unable to get list of node through xpath expression.
I want solution for reading mapping node element in Xpath.

A: [edit] /sitemesh/mapping also works .
The issue here is that you evaluating the express for XPathConstants.NODE while the nodeList maps to XPathConstants.NODESET. please refer below link.
http://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/xpath/XPathConstants.html#NODESET
Added sample code for illustration purpose only:
public void testXpathExpr(){

String testXML = "<sitemesh><mapping path=\"/editor/tempPage/**\" exclude=\"true\"/><mapping decorator=\"/WEB-INF/views/decorators/detailstheme.jsp\" path=\"/*\" exclude=\"false\" /></sitemesh>";

NodeList nodeList = getNodeList(testXML);
}

private NodeList getNodeList(String xml) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException {
  DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = docFactory.newDocumentBuilder();

  document = builder.parse(new ByteArrayInputStream( xml.getBytes() ) );
  XPathExpression exprPath = xpath.compile(xpathExpr);
  NodeList nodeList = (NodeList) exprPath.evaluate(document, XPathConstants.NODESET);;
return nodeList;
}

Hope this helps!

A: Your xpath works perfectly for me. Below is the sample code:
public class Parser {

    public static void main(String[] args) throws Exception, Exception {
        final DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();
        final DocumentBuilder builder = factory.newDocumentBuilder();
        final Document doc = builder.parse("src/sitemesh.xml");
        final XPathFactory xPathfactory = XPathFactory.newInstance();
        final XPath xpath = xPathfactory.newXPath();
        final XPathExpression expr = xpath.compile("/sitemesh/mapping");
        Object node = expr.evaluate(doc, XPathConstants.NODE);

        System.out.println(node);
    }
}

sitemesh.xml contains your sample input.