text:
Q: similarity between two sentences I have run an experiment where users were given a distorted sentence and asked to restore it. Currently, I am interested to grade the results on the scale between 0 to 1. I'm wondering if there any well-known ways to do so?
I am not interested in the "semantic quality" but only in the word for word similarity.

A: There is the BLEU score (see https://en.wikipedia.org/wiki/BLEU ) used in machine translation that might fit your intentions.
For a more detailed discussion of the BLEU score see this stackoverflow question: https://stackoverflow.com/questions/5390397/bleu-score-implementation-for-sentence-similarity-detection

A: There are many solutions for this kind of problem. Have you tried for instance the Levenshtein distance, jaccard index overlap coefficient, or any other string distance method? Wikipedia link
Keep in mind that your sentences should be tokenized into words before applying these methods...


text:
Q: Equivalent norms imply equivalent inner products? Let $H$ be Hilbert and let it have two innner products $(\cdot,\cdot)_1$ and $(\cdot,\cdot)_2$.
If the norms $|\cdot|_1$ and $|\cdot|_2$ are equivalent, does this ever imply: there exist constants $C_i$ such that
$$C_1(a,b)_2 \leq (a,b)_1 \leq C_2(a,b)_2$$
(i.e. the inner products are equivalent in some sense)?
under what conditions on $H$ does this happen?

A: You have such constants that
$$C_1\langle a\mid b\rangle_2 \leqslant \langle a \mid b\rangle_1 \leqslant C_2\langle a\mid b\rangle_2$$
for all $a,\, b \in H$ if and only if the two norms are constant multiples of each other.
Firstly, such an inequality can only hold if $\langle\mid\rangle_2$-orthogonality implies $\langle\mid\rangle_1$-orthogonality.
Assume that to be the case.
Then let $(e_\nu)$ be a $\langle\mid\rangle_2$-ONB.
For $\nu \neq \mu$ (if $\dim H = 1$, there is nothing to show), we have $\langle e_\nu + e_\mu \mid e_\nu - e_\mu\rangle_2 = \lVert e_\nu\rVert_2^2 - \lVert e_\mu\rVert_2^2 = 0$, and therefore
$$\langle e_\nu + e_\mu \mid e_\nu - e_\mu\rangle_1 = \lVert e_\nu\rVert_1^2 - \lVert e_\mu\rVert_1^2 = 0,$$
i.e. $\lVert e_\nu \rVert_1$ is constant, and thus, up to scaling by a factor independent of $\nu$, $(e_\nu)$ is also an ONB for $\langle\mid\rangle_1$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Integral morphisms are closed Let
$$
\pi: X \to Y
$$
be an integral morphism of schemes, i.e., a morphism which is affine and such that for any affine open $\operatorname{Spec} B\subset Y$, we have $\pi^{-1} \operatorname{Spec} B =\operatorname{Spec} A \subset X$, such that the induced ring morphism
$$
\pi^\sharp:B\to A
$$
is integral. I want to show that every integral morphism is closed. In the affine case it is easy: a closed subset of $\operatorname{Spec} A$ is defined by an ideal $I\subset A$. There is the corresponding ideal $J=(\pi^\sharp)^{-1}(I)\subset B $. Now notice that
$$
\pi^\sharp:B/J\to A/I
$$
is an integral extension. Then take $\operatorname{Spec}$ of the above and use Lying Over Lemma.
Is it possible to reduce the general case to the affine case? If $K\subset X$ is closed, then I can take a cover of $X$ by affines and intersect with $K$ to get a cover of $K$, but this cover may be horribly infinite... Or I can consider $\pi(K)$ and cover it and try to use the fact that $\pi$ is affine. I don't think these steps will lead me anywhere.

A: Given a topological space $T$ together with an open covering $\{U_i\}_{i\in I}$, a subset $Z\subset T$ is closed in $T$ if and only if $T\cap U_i$ is closed in $U_i$ for all $i$. Now just note that $\pi(K)\cap U=\pi(K\cap \pi^{-1}(U))$, and apply this to $U$ affine.


text:
Q: Python: re.sub single item in list with multiple items I'm new to Python and trying to use re.sub or other approach to find individual items in a list and replace with multiple items. For example:
import re
list = ['abc', 'def']
tolist = []
for item in list:
    a = re.sub(r'^(.)(.)(.)$', '\\1\\2', '\\2\\3', item)
    tolist.append(a)
print tolist  # want: ['ab', 'bc', 'de', 'ef']

The '\1\2', '\2\3' part clearly doesn't work, just there to lamely illustrate the idea.

A: You could pair characters without regexes:
lst = ['abc', 'def']
result = [a+b for chars in lst for a, b in zip(chars, chars[1:])]
print(result)
# -> ['ab', 'bc', 'de', 'ef']

A: Here's a rather generic approach where you have a list of tuples for all the substitutions you want to do with each item:
In [1]: import re

In [2]: subs = [(r'^(.)(.)(.)$', r'\1\2'), (r'^(.)(.)(.)$', r'\2\3')]

In [3]: inlist = ['abc', 'def']

In [4]: [re.sub(*sub, string=s) for s in inlist for sub in subs]
Out[4]: ['ab', 'bc', 'de', 'ef']

The second element in each tuple can also be a function, because re.sub allows it. I renamed your initial list because list is a built-in type name and shouldn't be used for variables.

A: >>> res = []
>>> m = re.compile('(..)')
>>> for items in list:
...   for p in range(0,len(items)):
...     r = m.search(items[p:])
...     if r != None:
...        res.append(r.group())

make a regexp that matches two characters and groups them
first for loop, iterate the list
second for loop, character indexes in each list item
search for the character pairs starting at further on offsets
store anything that's found


text:
Q: Why I have to open data channel before send peer connection offer? I'm coding a simple chat application and I'd like to add a shared drawing canvas to my application which is using data channel to send canvas points between them. But it's a optional specification so I don't want open a data channel each time of opening a chat. If I open data channel after establish the peer connection (after offer), I can not send any data over data channel. Otherwise I can send (I got this point from here: https://stackoverflow.com/a/35141500/5663292). So why I have to open data channel before peer connection offer?

A: The SDP offer/answer is what establishes how exactly your peers want to communicate. The offer includes the actual connection method (IP/port/TURN relay) and what streams, codecs and channels you want to use. The answer narrows this down/confirms what the other peer can accept.
If you want to add anything to the communication, like an additional media stream or a data channel, you need to inform the other peer of that, otherwise it doesn't expect anything/can't handle it.
The flow is always:

*

*prepare anything you want to send to a remote peer on your local RTCPeerConnection

*generate a local description

*send it to the remote peer

*await the remote peer's answer

*incorporate the remote's answer (setRemoteDescription)

Only then are both peers on the same page and can really talk to one another. Repeat this procedure whenever necessary, i.e. whenever you substantially change anything about what you're sending.


text:
Q: Testing react app with cypress and firestore shows Timed out retrying: cy.wait() I'm using react 16.8.1, cypress 3.1.5 and firebase 5.5.3 for e2e tests.
Currently I need to wait for the page to load all the components and then run the tests like getting a button and clicking on it.
Before each test, the programm checks if the user is logged in and if so, it'll wait for firebase to send some POST and GET requests.
Unfortunately cypress shows CypressError: Timed out retrying: cy.wait() timed out waiting 100000ms for the 1st response to the route: 'googleGETRoute'. No response ever occurred. for both GET and POST requests, which makes clicking or continuing the tests impossible.
Before each request I run the following:
beforeEach(function () {
    cy.server().route({ url: /https:\/\/.*google.*/, method: "POST" }).as("googleRoute");
    cy.server().route({ url: /https:\/\/.*google.*/, method: "GET" }).as("googleGETRoute");
    cy.visit('/event');
    cy.wait('@googleRoute', xhr => {
        cy.url().then((url) => {
            if (url === 'http://localhost:3000/login') {
                cy.loginByForm(testUserAccount, testUserPassword);
            }
        });
    });
});

And to delete an event:
it('should deleteEvent', function() {
    cy.wait('@googleGETRoute', { responseTimeout:100000, log:true });
    cy.wait('@googleRoute', { responseTimeout: 100000, log:true });

    deleteEvent(event);
    cy.contains(event.title).should('not.be.visible');
});

still no responses from firestore. I've also checked #1652 and #2374 which are almost the same as this problem.
Has anyone faced this issue before? Would appreciate any help

A: You shouldn't rely on firestore or firebase to start a test because it's an external service that you have no control over especially

*

*when are these firestore requests sent?

*what are these requests for?

*how do they work?

If we don't understand, we cannot expect Cypress knows what's going on because it's a framework.
Instead, you can just wait for a specific component to be available. By default, the cy.get command has a built-in timeout. It'll wait for the given component to be rendered before failing a test.
In  your case, you can increase the timeout of the very first cy.get which, I think, in deleteEvent(). In addition, you need get rid of all cy.server & cy.wait for firestore which are unreliable and useless.


text:
Q: How to stop text overflowing into the another div while maintaining exact div ratios? I have the following requirements

*

*The two boxes on the left should always be 50/50 split

*The Image on the right should stretch to accommodate the text height on the left

*The text on the left should never clip, the box should just enlarge to fit the text

Right now the problem is that the text on the top overflows into the bottom div like this

I've added sample code to show this problem

.section-8 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
}

.div-block-230 {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  width: 40%;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
  -ms-flex-direction: column;
  flex-direction: column;
}

.div-block-231 {
  width: 20%;
  min-height: 300px;
  background-color: #06c;
}

.div-block-232 {
  width: 40%;
}

.div-block-233 {
  height: 50%;
}

.div-block-234 {
  height: 50%;
}

          Duis in tellus velit. Mauris vel nunc ac mi imperdiet imperdiet. Suspendisse ultrices Lorem ipsum dolor sit Duis in tellus velit. Mauris vel nunc ac mi imperdiet imperdiet. Suspendisse ultrices Lorem ipsum dolor sitDuis in tellus velit. Mauris vel nunc
          ac mi imperdiet imperdiet. Suspendisse ultrices Lorem ipsum dolor sitDuis in tellus velit. Mauris vel nunc ac mi imperdiet imperdiet. Suspendisse ultrices Lorem ipsum dolor sitDuis in tellus velit. Mauris vel nunc ac mi imperdiet imperdiet.
          Suspendisse ultrices Lorem ipsum dolor sitDuis in tellus velit. Mauris vel nunc ac mi imperdiet imperdiet. Suspendisse ultrices Lorem ipsum dolor sit

This is some text inside of a div block.

A: CSS Grid will do the job well. The layout will be simplified:

Top text block

Bottom text block

The right blue column

With CSS grid you'll apply min 50% to the rows grid-template-rows: minmax(50%, 1fr); and that will give you the desired result.
Finally, we'll make the blue column to span on 2 rows. So it always occupies the full height of the container.
Here's the full solution. EDIT: Forgot minmax(50%, 1fr) for the second row.

.container {
  display: grid;
  grid-auto-flow: column;
  grid-auto-columns: 1fr;
  grid-template-columns: 1fr;
  grid-template-rows: minmax(50%, 1fr) minmax(50%, 1fr);
}

.blue-column {
  background-color: blue;
  grid-row-start: span 2;
  grid-row-end: span 2;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse varius enim in eros elementum tristique. Duis cursus, mi quis viverra ornare, eros dolor interdum nulla, ut commodo diam libero vitae erat. Aenean faucibus nibh et justo cursus id rutrum lorem imperdiet. Nunc ut sem vitae risus tristique posuere.

This is some text inside of a div block.

A: Here is my solution:
https://jsfiddle.net/mn927ugt/101/
css:
.container {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 100%;
  width: 100%;

}

.text-container {
  display: flex;
  flex-direction: column;
  width: 50%;
  align-content: space-between;
}

.lorem-ipsum {
  margin-bottom: 10px;
}

p {
  margin: 0;
}

.image-container {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  width: 50%;
}

.image {
  background-color: blue;
  width: 50%;
}

.empty-div {
  width: 50%;
}

html:

        Duis in tellus velit. Mauris vel nunc ac mi imperdiet imperdiet. Suspendisse ultrices Lorem ipsum dolor sit Duis in tellus velit. Mauris vel nunc ac mi imperdiet imperdiet. Suspendisse ultrices Lorem ipsum dolor sitDuis in tellus velit. Mauris vel nunc ac mi imperdiet imperdiet. Suspendisse ultrices Lorem ipsum dolor sitDuis in tellus velit. Mauris vel nunc ac mi imperdiet imperdiet. Suspendisse ultrices Lorem ipsum dolor sitDuis in tellus velit. Mauris vel nunc ac mi imperdiet imperdiet. Suspendisse ultrices Lorem ipsum dolor sitDuis in tellus velit. Mauris vel nunc ac mi imperdiet imperdiet. Suspendisse ultrices Lorem ipsum dolor sit

        This is some text inside of a div block.

Update:
Vertically aligned textboxes and added empty div


text:
Q: React Native app crashes without any error The app will build successfully in both development and production but when I run expo start --dev-client my app crashes, I try to resolved last two days but not fix it. I am stuck please help me out. Why my app crash??
I  check adb logcat but nothing found any error. If you have any idea?
Here is my image


text:
Q: SpriteKit + iOS8. Does SpriteKit support "baking" rendered results? I am implementing a paint program in SpriteKit and I am super impressed by the simplicity of implementation SprikeKit enables. Very cool indeed!
Each brush stroke is implemented as a SKSpriteNode with attached SKShader. Everything works as I expect.
Issue: Currently I am steadily growing the SKScene graph as brush strokes are appended. This is not a scalable solution as resource consumption mushrooms and framerate slows to a crawl. So, what I want to do "bake" the SKScene graph after brush stroke is painted.
I tried setting myScene.shouldRasterize = YES on my SKScene instance but it appeared to have no effect. How do I "bake" rendering results in SpriteKit? Do I have to roll my own?
Thanks,
Doug

A: The only was I can think of to do this is to call textureFromNode on your SKView passing in the SKNode that you want to "bake". Then take that texture, apply it to a SKSpriteNode, and remove the SKNode(s) that you just "baked" in to the texture.

A: Wanted to add a comment but reputation won't allow me. Just would like to add that you can rasterize group of sprites by using SKEffectNode. Just add any sprite to this node then use the same shouldRasterize property. You can even apply CoreImage filters to it such as Gaussian Blurs.
The downside is obviously performance when created the rasterized node.


text:
Q: Set.pop() isn't random? From the python docs, "set.pop() remove and return an arbitrary element from s". While generating some random data to test a program, I noticed strange behavior of this pop() function. Here is my code (python 2.7.3):
testCases = 10
numberRange = 500

poppedValues = []
greaterPercentages = []

for i in range (testCases):
    s = Set()

    """ inserting 100 random values in the set, in the range [0, numberRange) """
    for j in range (100):
        s.add(random.randrange(numberRange))

    poppedValue = s.pop()
    greaterCount = 0

    """ counting how many numbers in the set are smaller then the popped value """
    for number in s:
        if poppedValue > number:
            greaterCount += 1

    poppedValues.append(poppedValue)
    greaterPercentages.append(float(greaterCount) / len(s) * 100)

for poppedValue in poppedValues:
    print poppedValue, '\t',

print

for percentage in greaterPercentages:
    print "{:2.2f}".format(percentage), '\t',

What I'm doing here is,

*

*Inserting some random values in the set s where each element is in the range [0, numberRange)

*Pop an element from the set (according to the docs, it should be a random one)

*Counting how many elements in the set are smaller then the popped value

I expected that the popped value should be a random one and about 50% of the numbers in the set will be greater then the popped value. But seems that pop() almost always returns the lowest number in the set. Here are the result for numberRange = 500. First row denotes the values of the popped element. Second row is the percentage of elements which are smaller then the popped value.
9   0   3   1   409     0   1   2   4   0
0 % 0 % 0 % 0 % 87 %    0 % 0 % 0 % 0 % 0 %

I've conducted this test with different values of numberRange. It seems that for lower values of the set elements, pop() almost always returns the lowest element. But for higher values it returns a random element. For numberRange = 1000, the result is:
518     3586    3594    4103    2560    3087    4095    3079    3076    1622
7 %     72 %    73 %    84 %    54 %    51 %    79 %    63 %    67 %    32 %

which I think is pretty random. Why this strange behavior? Am I doing something wrong?
EDIT: Thanks for everyone's answer and comment, seems that by "arbitrarily", it isn't guaranteed that it will be "random".

A: When the doc says:

remove and return an arbitrary element from s; raises KeyError if empty

that means the behaviour isn't defined and the implementation can do whatever it's possible. In this case, it seems that the implemented behaviour is to remove the smallest value. That's all.
In fact, set.pop() is based on a HashMap and remove the first element of this (which is the smaller hashcode). In the case of set of ints, it's the smallest int.
On other implementation of Python could return a random value or the first pushed... You can't know.

A: It's an implementation detail - set is implemented as a HashMap (similar to dict but without a slot for a value), set.pop removes the first entry in the HashMap, and an ints hash value is the same int.
Combined, this means that your set, which is ordered by the hash values, is actually ordered by the entries modulo hashtable size as well; this should be close to natural ordering in your case as you are only inserting numbers from a small range - if you take random numbers from randrange(10**10) instead of randrange(500) you should see a different behaviour. Also, depending on your insertion order, you can get some values out of their original hashing order due to hash collisions.


text:
Q: DataContract dll used in WCF Service project and a client Project I have a WCF service project in which i included datacontract dll.
Then i have a client .NET application build in WPF which uses the same data contract dll.
The problem is when i pass the entity filled from client application to webservice application and check the same entity over there, some of the data is available as null there, despite the fact that i passed it from the client applicaion.
Is there any thing missing on my part?


text:
Q: Identifying objects, shapes in a image and recognizing them using UITouch in iOS? The app I create has a set of images. The images will have flow charts. The chart will have different nodes and arrows indicating the flows between them and nodes will have titles with them.
Now when user clicks on the Node (say titled Start Operation), I need to capture this event with the information of the title of the node and other node information.
I think this is not possible unless I store some information in the image when it is created and when user taps on the image, I can capture the location of touch and try extracting the information encoded.
What are your suggestions on this?


text:
Q: How to run app that work in tablets to smartphone? I am very very new to Android and  I was assigned  a project of a system that is working on tablet and the idea is that it also works in smartphone. From what I could see, it was developed with the API 13, and I would take it to the API 19, but is giving me some errors:
C:\Projects\TestAndroid\app\build\intermediates\res\merged\debug\values-v21\values-v21.xml
Error:(13) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Inverse'.
Error:(15) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Large.Inverse'.
Error:(21) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Medium.Inverse'.
Error:(206) Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.ProgressBar'.
Error:(208) Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.ProgressBar.Horizontal'.
Error:(216) Error retrieving parent for item: No resource found that matches the given name 'android:Theme.Material'.
Error:(223) Error retrieving parent for item: No resource found that matches the given name 'android:Theme.Material.Light'.

C:\Projects\TestAndroid\app\build\intermediates\exploded-aar\com.android.support\appcompat-v7\23.0.0\res\values-v21\values-v21.xml
Error:(82, 5) No resource found that matches the given name: attr 'android:colorAccent'.
Error:(82, 5) No resource found that matches the given name: attr 'android:colorButtonNormal'.
Error:(82, 5) No resource found that matches the given name: attr 'android:colorControlActivated'.
Error:(82, 5) No resource found that matches the given name: attr 'android:colorControlHighlight'.

Does anyone know of any material in which to handle this issue? From already thank you very much.

A: just remove the \res\values-v21\ folder. You won't need it when your target API Level is 19. (Material Design Theme needs API Level 21)


text: Q: How to set sigmask and do a long jump atomically in my signal handler? I am implementing a coroutine scheduler. A thread is interrupted(by SIGURG) regularly to make a switch. I am using swapcontext(from ucontext.h) in sighandler to achieve that. But I found swapcontext doesn't atomically set sigmask and do a long jump. Instead it firstly call sigprocmask and then do a jmp(which I think may cause trouble like signal handler reentry). How can I avoid this?


text:
Q: Parsing function returns NaN instead of zero as requested I've got these functions:

const precisionRound = (number, precision = 0) => {
  const factor = 10 ** precision;
  return Math.round(number * factor) / factor;
};

const superParseFloat = (numberish, precision = 2) => {
  if (!!numberish) {
    return precisionRound(parseFloat(numberish.toString().replace(/[^0-9.-]/g, '')), precision);
  }
  return 0;
}

console.log(
  superParseFloat('www 111'),
  superParseFloat('222'),
  superParseFloat(333),

  superParseFloat(null),
  superParseFloat(undefined),
  superParseFloat('some text')
)

It should replace all non numeric characters from string with '', and only return numbers, for example:
superParseFloat('www 111') => 111
superParseFloat('222') => 222
superParseFloat(333)) => 333

For 'null', 'undefined' or for a string without numeric characters it should return 0, eg.:
superParseFloat(null) => 0
superParseFloat(undefined) => 0
superParseFloat('some text') => 0

It works fine apart from when I'm passing a string without numeric characters. Then it returns NaN, for example:
superParseFloat('some text') returns NaN
I think it's something to with putting another if statement using isNaN() for return value but I can't figure out how to use it (if i'm right in thinking at all?)

A: We can put the isNaN before the rounding

const precisionRound = (number, precision = 0) => {
  const factor = 10 ** precision;
  return Math.round(number * factor) / factor;
};

const superParseFloat = (numberish, precision = 2) => {
  if (!!numberish) {
    const replaced = parseFloat(numberish.toString().replace(/[^0-9.-]/g, ''));
    return Number.isNaN(replaced) ? 0 : precisionRound(replaced, precision);
  }
  return 0;
}

console.log(
  superParseFloat('www 111'),
  superParseFloat('222'),
  superParseFloat(333),

  superParseFloat(null),
  superParseFloat(undefined),
  superParseFloat('some text')
)

A: the problem is parseFloat('') returns NaN
instead do this:
var formattedValue = numberish.toString().replace(/[^0-9.-]/g, '');
if (!! formattedValue) {
   return precisionRound(parseFloat(formattedValue), precision);
} else
   return 0;

A: OK, I think I've got it:
const superParseFloat = (numberish, precision = 2) => {
  if ( !!numberish) {
    const converted = precisionRound(parseFloat(numberish.toString().replace(/[^0-9.-]/g, '')), precision);
    if (!Number.isNaN(Number(converted))) {
      return converted;
    }
     return 0;
  }
  return 0;
}


text:
Q: Illegal start of expression in Java AFTER ATTEMPTED SOLUTIONS I am aware that this questions has been asked before, but I still face the same issue after trying to resolve it. Here's the code and an image:
import java.util.Scanner;

class Testing {

    public static void main(String[] args){
        Greeting();
        AgeVerification();
        Calculator();
    }

        static void Greeting(){
            System.out.println("Hey. I'm Java, you are...?");
            Scanner getname = new Scanner(System.in);
            String name = getname.next();
            System.out.println("Nice to meet you "+name+".\n");
        }

        static void AgeVerification(){
            System.out.println("How old are you?");
            Scanner getage = new Scanner(System.in);
            Int age = getage.next();
            if(age => 18){
                System.out.println("Access granted, go ahead.");
            }
            else {
                System.out.println("Access denied, you're still a minor.");
            }
        }

        static void Calculator(){
            System.out.println("Now lets do some maths. Do you want to add, subtract, multiply, or divide?");
            Scanner getoperation = new Scanner(System.in);
            String operation = getoperation.next();
            if(operation == "add" | operation == "Add"){
                System.out.println("Which two numbers would you like to add? Enter them separately.");
            }
        }

}

https://ctrlv.cz/3JDJ
I originally had the three methods below the main listed as public, but removed the "public" attributes only to encounter the same issue. I am new to Java programming, and appreciate the help.

A: There's a couple of problems with your code.
First, on this line:
Int age = getage.next();

To declare an integer, use the int type. Also, you probably want to use nextInt() instead of next().
Next, this check is the wrong way around:
if(age => 18){

It should be if (age >= 18){.
And finally, in this line:
if(operation == "add" | operation == "Add"){

| is not doing what you think it is here, you should use ||.
As pointed out in the comments, you should check string equality using the equals() method.
    if(operation.equals("add") || operation.equals("Add")){

Finally, and this is just nitpicky, but if you wanted to you could change this if-statement to just check:
if (operation.equalsIgnoreCase("add")) {

Hope this helped!

A: You should change this:
Int age = getage.next();

to:
int age = getage.nextInt();

Case is important in Java, and while int is a built-in primitive type, Int has no meaning unless you define your own class called Int (which it seems you have not done). That will get rid of the "Illegal start of expression error". However, it will give you a different error because Scanner#next() returns a String and you want an integer value. Thus, you should be calling nextInt() instead of next().
Also, as others have pointed out, the integer comparison operator you want to use in the next line is >= (think "greater than or equal"); there is no => operator in Java.

A: In AgeVerification(), change
Int age = getage.next();

to
int age = getage.nextInt();

Next there is no => opertor in java. So to compare the age change
if(age => 18){
  System.out.println("Access granted, go ahead.");
}

to
if(age >= 18){
      System.out.println("Access granted, go ahead.");
}

Also, you can " | " refers to bitwise OR. Whereas you want to check if the string equals add or Add. So change it to
if(operation.equalsIgnoreCase("add")){
   System.out.println("Which two numbers would you like to add? Enter them     separately.");
}


text:
Q: Consume Rest API on same ip but different port Let's suppose a backend application, which exposes some Rest API, running on a Jetty webserver at address 192.168.1.10:8889.
I would like to have a frontend application (html/javascript only, on a apache2 webserver) running at the same IP but on a different port (e.g. 8000), which should consume the API exposed by the backend application.
How can i get this architecture working without get into "No 'Access-Control-Allow-Origin'" error?

A: I think that you should install a nginx proxy.
configure it as a reverse proxy you can see documentation here :
https://www.nginx.com/resources/admin-guide/reverse-proxy/
You can search on google for more specific documentation on what you want to do.


text:
Q: Unable To Show Data in PHP Using ASP.NET Web Service I've created a simple web service in ASP.NET and want that service to be consumed in a PHP application. The web service is as follows:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public List<Customer> GetCustomers(int id)
{
   id = Convert.ToInt32(HttpContext.Current.Request.QueryString["id"]);

   List<Customer> lst = null;
   using (var context = new DemoEntities())
   {
      lst = (from c in context.Customer
             where c.CustomerID == id
             select c).ToList();
   }

   return lst;
}

In the above web service, a customer id is passed to retrieve customer details. So to consume this service in PHP, I've tried to do the following using nuSoap library as follows and it works almost:
<?php
    require_once("lib/nusoap.php"); //Using the nuSoap library

    $client   = new nuSoap_Client('http://localhost:1284/MyCustomers.asmx?wsdl', TRUE); //Passed the ASP.NET web service and an object created
    $result = $client->call('GetCustomers', array('id' => 1)); //Called the GetCustomers method and passed a default parameter

    foreach($result as $item) //Tried to iterate in a foreach loop
    {
      echo $item; //Here is the issue - The output returns or returned only the name 'Array'
    }
?>

I've done PHP programming a long time ago and trying to figure the issue searching google. I've even tried to access the array index with the web service property directly like the below but seems like missing something or may be not the correct way: Any idea would be appreciated
echo $item[1]->CustName;
echo $item[1]; //Even this

Right now, I am getting the Xml data as follows using the Soap web service:
<ArrayOfCustomer>
  <Customer>
    <CustomerID>2</CustomerID>
    <CustName>John</CustName>
    <CustAddress>On Earth</CustAddress>
    <CustLocation>On Earth</CustLocation>
    <CustSex>Male</CustSex>
    <CustType>3</CustType>
    <CustStatus>2</CustStatus>
    <CustDetails>Great guy - Always regular.</CustDetails>
  </Customer>
</ArrayOfCustomer>

Update 1: Used var_dump($item) and currently getting the array elements as follows:
array
  'Customer' =>
    array
      'CustomerID' => string '2' (length=1)
      'CustName' => string 'John' (length=7)
      'CustAddress' => string 'On Earth' (length=25)
      'CustLocation' => string 'On Earth' (length=10)
      'CustSex' => string 'Male' (length=4)
      'CustType' => string '3' (length=1)
      'CustStatus' => string '2' (length=1)
      'CustDetails' => string 'Great guy - Always regular.' (length=47)

But when tried with this $item->Customer->CustName, getting this error again - Trying to get property of non-object.
Update 2: Again used var_dump($item) and the result is as follows with PHP programming:
<?php
    require_once("lib/nusoap.php");

    $client   = new nuSoap_Client('http://localhost:1284/MyCustomers.asmx?wsdl', TRUE);
    $result = $client->call('GetAllCustomers'); //Without any parameter
    foreach($result as $item)
    {
       echo var_dump($item);
    }
?>

Output:
array
  'Customer' =>
    array
      0 =>
        array
          'CustomerID' => string '1' (length=1)
          'CustName' => string 'Jack' (length=7)
          'CustAddress' => string 'On Earth' (length=25)
          'CustLocation' => string 'On Earth' (length=10)
          'CustSex' => string 'Male' (length=4)
          'CustType' => string '3' (length=1)
          'CustStatus' => string '2' (length=1)
          'CustDetails' => string 'Regular Customer and always happy to cooperate.' (length=47)
      1 =>
        array
          'CustomerID' => string '2' (length=1)
          'CustName' => string 'John' (length=4)
          'CustAddress' => string 'On Earth' (length=7)
          'CustLocation' => string 'On Earth' (length=10)
          'CustSex' => string 'Male' (length=4)
          'CustType' => string '3' (length=1)
          'CustStatus' => string '2' (length=1)
          'CustDetails' => string 'Great guy - Always regular.' (length=25)

Again, tried to use two loops to get the values that's as follows but it only returns first two results and there are total 10 records in the database:
<?php
    require_once("lib/nusoap.php");

    $client   = new nuSoap_Client('http://localhost:1284/MyCustomers.asmx?wsdl', TRUE);
    $result = $client->call('GetAllCustomers');
    $count = count($result);

    foreach($result as $item)
    {
      for($i = 0; $i <= $count; $i++)
      {
         echo 'Name: ' . $item['Customer'][$i]['CustName'].'<br/>';
      }
    }
?>

Output:
Name: Jack //Returns only first two records though it should return all the records
Name: John

A: Simply do a var_dump($item); in php to see how they array structure is.. currently I do not know what the response object is, but for example you can access the keys as such: echo $item->Customer->CustName;
If it is an array response, not an object, then: $item['Customer']['CustName'];


text:
Q: How to change repeating interval of AlarmManager at runtime in Android I have written the following AlarmManager to start a Service which will download a file at specified interval:
    Calendar updateTime = Calendar.getInstance();
    updateTime.setTimeZone(TimeZone.getDefault());
    updateTime.set(Calendar.HOUR_OF_DAY, 7);
    Intent downloader = new Intent(mActivity, FileDownloadService.class);
    downloader.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(mActivity, 0, downloader, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

From the other part of the application, I get the value for repeating interval to run the Service. The value for repeating interval change on daily basis.
How can we change the AlarmManager interval at runtime as the above code will be executed only once?
For example, on day 1 I want the repeating interval to be 15 minutes and on day 2 I want the interval to be 2 hours.
How can I change the repeating interval dynamically?

A: Store the value 15 minutes inside your pending intent as an extra. When your code gets triggered by the alarm manager, get the current value, increment it as per your needs and reset the extra in the intent which holds the value.
Edit : Use alarmManager.set(int type, long triggerAtMillis, PendingIntent operation); at every new invocation of your code.


text:
Q: Reload model/update template on createRecord save I see this question is being ask all over again still don't find solution that works for such a trivial task.
This url displays a list of navigations tabs for workspaces.
http://localhost:4200/users/1/workspaces

Each of tab resolves to
http://localhost:4200/users/1/workspaces/:wid

Also on the I have a button that suppose to create a new workspace as well as new tab.
Here how controller for looks:
export default Ember.Controller.extend({

    actions: {
        newWorkspace: function () {
            this.get('currentModel').reload();
            var self = this;

            var onFail = function() {
                // deal with the failure here
            };

            var onSuccess = function(workspace) {
                self.transitionToRoute('dashboard.workspaces.workspace', workspace.id);
            };

            this.store.createRecord('workspace', {
                title: 'Rails is Omakase'
            }).save().then(onSuccess, onFail);

        }
    }
});

When I click on button I see in ember inspector new record indeed created as well as url redirected to id that represents newly created workspace.
My question is how to force model/template to reload. I have already killed 5h trying model.reload() etc. Everything seem not supported no longer. Please please help.
UPDATE
When adding onSuccess
model.pushObject(post);

throws Uncaught TypeError: internalModel.getRecord is not a function

A: I believe you should call this.store.find('workspace', workspace.id) for Ember Data 1.12.x or earlier. For 1.13 and 2.0 there are more complicated hooks that determine whether or not the browser should query the server again or use a cached value; in that case, call this.store.findRecord('workspace', workspace.id, { reload: true }).

A: I do not know if this help. I had a similar problem. My action was performed in the route. Refresh function took care of everything.


text:
Q: TECoreException: The server's error could not be parsed as XML. No SOAP fault found I am getting below error while trying to fetch versionControlClient object using TFS java SDK. Any leads what could cause this ?
we are using TFS-2010
com.microsoft.tfs.core.exceptions.TECoreException: The server's error could not be parsed as XML.  No SOAP fault found.
at com.microsoft.tfs.core.exceptions.mappers.TECoreExceptionMapper.map(TECoreExceptionMapper.java:105)
at com.microsoft.tfs.core.exceptions.mappers.LocationExceptionMapper.map(LocationExceptionMapper.java:32)
at com.microsoft.tfs.core.clients.framework.location.internal.LocationWebServiceProxy.connect(LocationWebServiceProxy.java:76)
at com.microsoft.tfs.core.clients.framework.location.LocationService.connect(LocationService.java:756)
at com.microsoft.tfs.core.clients.framework.location.LocationService.checkForServerUpdates(LocationService.java:841)
at com.microsoft.tfs.core.clients.framework.location.LocationService.findServiceDefinition(LocationService.java:174)
at com.microsoft.tfs.core.clients.framework.location.LocationService.locationForCurrentConnection(LocationService.java:532)
at com.microsoft.tfs.core.config.webservice.DefaultWebServiceFactory.getServerDataProviderEndpointPath(DefaultWebServiceFactory.java:523)
at com.microsoft.tfs.core.config.webservice.DefaultWebServiceFactory.newWebService(DefaultWebServiceFactory.java:252)
at com.microsoft.tfs.core.TFSConnection.getWebService(TFSConnection.java:891)
at com.microsoft.tfs.core.config.client.DefaultClientFactory$7.newClient(DefaultClientFactory.java:231)
at com.microsoft.tfs.core.config.client.DefaultClientFactory.newClient(DefaultClientFactory.java:91)
at com.microsoft.tfs.core.TFSConnection.getClient(TFSConnection.java:1495)
at com.microsoft.tfs.core.TFSTeamProjectCollection.getVersionControlClient(TFSTeamProjectCollection.java:377)
at com.blueoptima.connectors.scr.vcs.tfs.TFSExtractor.authenticate(TFSExtractor.java:389)
at com.blueoptima.connectors.scr.SCR.extract(SCR.java:360)
at com.blueoptima.connectors.BOpInfraExtractor.run(BOpInfraExtractor.java:201)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.microsoft.tfs.core.ws.runtime.exceptions.InvalidServerResponseException: The server's error could not be parsed as XML.  No SOAP fault found.
at com.microsoft.tfs.core.ws.runtime.client.SOAPService.examineBodyForFault(SOAPService.java:1094)
at com.microsoft.tfs.core.ws.runtime.client.SOAPService.executeSOAPRequestInternal(SOAPService.java:732)
at com.microsoft.tfs.core.ws.runtime.client.SOAPService.executeSOAPRequest(SOAPService.java:475)
at ms.ws._LocationWebServiceSoap12Service.connect(_LocationWebServiceSoap12Service.java:384)
at com.microsoft.tfs.core.clients.framework.location.internal.LocationWebServiceProxy.connect(LocationWebServiceProxy.java:70)
... 19 more
Caused by: com.microsoft.tfs.util.xml.XMLException: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
at com.microsoft.tfs.util.xml.DOMCreateUtils.parse(DOMCreateUtils.java:648)
at com.microsoft.tfs.util.xml.DOMCreateUtils.parseStream(DOMCreateUtils.java:451)
at com.microsoft.tfs.util.xml.DOMCreateUtils.parseStream(DOMCreateUtils.java:353)
at com.microsoft.tfs.core.ws.runtime.client.SOAPService.examineBodyForFault(SOAPService.java:1082)
... 23 more


text:
Q: Start x86_64 code on x86 (32bit) Linux, running on x86_64 CPU ?Is it possible to start an x86_64 code on i686 Linux (x86, 32-bit)? My CPU is modern Core 2 and it can run x86_64 64-bit code itself, but the OS is 32bit.
The code to start is pure mathematic, and it need almost no interaction with OS.
I want to measure, how fast will be my program in 64bit mode comparing with 32-bit mode. The program is to solve huge combinatoric problem and full size run is dozens of hours.
I can start 64bit code with qemu, but it will be not native execution and speed in qemu will be not related to real cpu speed.

A: You won't be able to run x86_64 programs on a 32bit kernel without some form of emulation. (The other way around works just fine though, with no emulation.)
To be able to run 64bit code on x86_64, you have to enter "long mode" which requires the appropriate page tables to be set up (among other things). A 32bit kernel won't have done any 64bit page tables or mappings. So userspace code can't enter 64bit mode. It might be possible with some kernel help, but a 32bit kernel is simply not prepared for that kind of thing.
And since you can run 32bit code just fine with a 64bit kernel, there is no real reason not to use a 64bit kernel these days, especially if you have some code that could benefit from 64bit mode (more registers in particular).
Why don't you just boot from a 64bit live-cd? Or install a 64bit distribution on a separate disk or partition?

A: Use vmware; it will work just fine running a 64-bit VM on a 32-bit host OS provided the CPU supports it.

A: There is a cycle-accurate simulator for x86/x86_64. By default it will emulate AMD's K8

PTLsim is a state of the art cycle accurate microprocessor simulator and virtual machine for the x86 and x86-64 instruction sets. PTLsim models a full out of order processor core, featuring extensive memory and branch speculation with replay, a highly configurable clustered microarchitecture with various issue queue designs, a full cache hierarchy and memory subsystem and supporting hardware.

Unfortunately it can't run an x86_64 code on 32-bit x86 (cite from FAQ)

Of course, the 32-bit version of PTLsim will lack x86-64 support

But the speed should correlate with real run and a lot of information is available.


text:
Q: How to plot a list of Points and LINESTRING? hello all is there a way to plot a list of LINESTRING and list of Points
for example I have
line_string = [LINESTRING (-1.15.12 9.9, -1.15.13 9.93), LINESTRING (-2.15.12 8.9, -2.15.13 8.93)]
point = [POINT (5.41 3.9), POINT (6.41 2.9)]

My goal is to have a map or graph where the it shows me where the points connect with the LINESTRING.
Thank you in advance
EDIT
Thank you all for you answers sadly when I plot it looks like. I think the issue is the fact that some LINESTRINGS have 4 points (LINESTRING (-1.15.12 9.9, -1.15.13 9.93, -5.15.13 5.53, -3.15.13 2.23)) and some have 3 points. Is there a way to plot these better?

A: You can access matplotlib easily using geopandas scripting layer.
from shapely.geometry import LineString, Point
import geopandas as gpd

line_strings = [LineString([(-1.15, 0.12), (9.9, -1.15), (0.13, 9.93)]),
                    LineString([(-2.15, 0.12), (8.9, -2.15), (0.13 , 8.93)])]
points = [Point(5.41, 3.9), Point (6.41, 2.9)]

geom = line_strings + points
gdf = gpd.GeoDataFrame(geometry=geom)

gdf.plot()

Edit, based upon your comment. You can make an interactive plot with Bokeh if you want to zoom in on certain areas.
from bokeh.plotting import figure, show

p = figure(title="interactive plot example", x_axis_label='x', y_axis_label='y')

for ls in line_strings:

    x, y = ls.coords.xy
    p.line(x, y, legend_label="lines", color="blue", line_width=2)

for point in points:

    p.circle(point.x, point.y, legend_label="points", size=5, color="red", alpha=0.5)

show(p)

A: *

*you can plot as layers

*have demonstrated in matplotlib and folium

*some of your geometry is invalid

import shapely.wkt
import geopandas as gpd
import pandas as pd

# line_string = ["LINESTRING (-1.15.12 9.9, -1.15.13 9.93)", "LINESTRING (-2.15.12 8.9, -2.15.13 8.93)"]
# invalid geometry - modified
line_string = ["LINESTRING (-1.15 9.9, -1.15 9.93)", "LINESTRING (-2.15 8.9, -2.15 8.93)"]
point = ["POINT (5.41 3.9)", "POINT (6.41 2.9)"]

gs_ls = gpd.GeoSeries(pd.Series(line_string).apply(shapely.wkt.loads))
gs_p = gpd.GeoSeries(pd.Series(point).apply(shapely.wkt.loads))

# matplotlib
ax = gs_ls.plot()
ax = gs_p.plot(ax=ax)

# folium
m = gs_ls.explore()
m = gs_p.explore(m=m)
m

using alternative geometry

*

*with respect to what it looks like.  Clearly geometry makes a difference

*have created 6 line strings as parts of boundary of Germany (4 points).  Then respective points as center of these line strings

*just 4 points does plot well.  Longer line strings are not necessary.

import geopandas as gpd
import shapely.geometry
import numpy as np

world = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))

# exteriod of germany
ls = world.loc[world["iso_a3"].isin(["DEU"])].exterior.values[0]

# generate a series of linestring segments from germany bounday
gs_l = gpd.GeoSeries(
    [
        shapely.geometry.LineString(list(ls.coords)[s : s + 4])
        for s in np.random.randint(0, len(list(ls.coords)) - 4, 6)
    ], crs="epsg:4326"
)

# folium
m = gs_l.explore(style_kwds={"weight":6}, height=400, width=400)
gs_l.centroid.explore(m=m, color="red", marker_kwds={"radius":10})

# matplotlib
ax = gs_l.plot()
ax = gs_l.centroid.plot(color="red", markersize=50, ax=ax)

m

A: I made a library which provides a very easy to way to plot well known text strings and shapely objects. The library is called WKTPlot, and it wraps around the Bokeh library automating a lot of what @matthew-borish mentioned in their solution. What this solution would look like using WKTPlot:
from shapely.geometry import LineString, Point
from wktplot import WKTPlot

line_strings = [
    LineString([(-1.15, 0.12), (9.9, -1.15), (0.13, 9.93)]),
    LineString([(-2.15, 0.12), (8.9, -2.15), (0.13 , 8.93)]),
]
points = [Point(5.41, 3.9), Point (6.41, 2.9)]

// Create plot object
plot = WKTPlot("test1", save_dir=".")

# Add shapes using Bokeh styling arguments
# - https://docs.bokeh.org/en/latest/docs/user_guide/styling.html
for line_string in line_strings:
    plot.add_shape(line_string, line_width=3)

for point in points:
    plot.add_shape(point, line_width=7)

# Save plot to disk [./test1.html]
plot.save()


text:
Q: Apply regular expression to the second word in "|" separated string in a interpretor Flume config My requirement is to apply regular expression to the data coming from kafka.
The data is as follow:
abc|def|mnq|xyz
abc1|def1|mnq1|xyz1
abc2|def2|mnq2|xyz2

I want to apply regular expression on the second word i.e (def) from the first sting using a flume interpretor.
Regular expression can be to filter words and decimal numbers.
Can someone help in this.

A: Following python code matches all the second words in all the lines:
import re

# used || to add multilines combine into one string
parent = """abc|def|mnq|xyz||
abc1|def1|mnq1|xyz1||
abc2|def2|mnq2|xyz2"""

pattern = re.compile("\w+\|(.*?)\|\w+", re.MULTILINE)
m = pattern.findall(parent)
print m

which outputs|
['def', 'def1', 'def2']

Note: escape '|' by '\'.


text:
Q: How can I set the bootstrap switcher by default to ON? I am using the Bootstrap Switcher (https://bttstrp.github.io/bootstrap-switch/examples.html)

<input  type="checkbox" checked="checked" data-on-color="info" >

By default it looks like this:

But I would like the switcher to be default switched to ON:

But even if I set it to checked, it is always OFF. I also tried:

<input  type="checkbox" data-on-color="info" checked>

But no change.
I also tried:

<input  type="checkbox" data-on-color="info" checked="true">

but no change

A: use: data-toggle="switch"
code: <input type="checkbox" data-toggle="switch" checked>
test: https://jsfiddle.net/u38tq2r9/


text:
Q: how to (long,lat) convert to physical coordinates Please see example below:
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
def test():
    fig = plt.figure()
    pj = ccrs.Orthographic(central_longitude=0, central_latitude=0)
    ax = fig.add_subplot(111, projection=pj, position=[0,0,1,1])
    ax.set_global()
    trans = ccrs.PlateCarree()
    c = np.array([[0, 90], [90, 0], [ 0, -90], [-90, 0]])
    x = pj.transform_points(trans, c[...,0], c[...,1])
    s = ax.transData.transform(x[...,:2])
    ax.plot(s.T[0], s.T[1], marker="o", transform=None, clip_on=False)

I do not understand why it fails in longitude direction, or how this could be fixed.


text:
Q: Set Select2 Dropdown value on other Select2 Dropdown change event I am trying to Set Select2 Dropdown  value on other Select2 Dropdown change event ..
These are My Dropdowns

        @Html.DropDownList(Model.deptProp, new SelectList(Bmsa.UI.Utility.Utility.GetAllDepartments(Model.countryCode), "Value", "Text", Model.deptId), new { onchange = "Getarrnds();" })

and

                @Html.DropDownList(Model.cmnlSctnProp, new SelectList(Bmsa.UI.Utility.Utility.GetCmnlSection(Model.countryCode, Model.deptId, Model.arrndsId, Model.communeId), "Value", "Text", Model.cmnlSctnId))

Script

this is parsed HTML for both dropdowns
Select below

Select below

I have Tried following but these are not working
 $("select[name$=cmnlSctnId]").change(function () {
            $("select[name$=deptId]").select2("val","Ouest").val('Ouest').trigger("change");

$("select[name$=deptId]").select2("val","Ouest").val('2').trigger("change");

$("select[name$=deptId]").select2("val", "Ouest");

            $("select[name$=deptId]").val("2").trigger("change");
 $('select[name$=deptId]').select2('data', { id: 100, a_key: 'Lorem Ipsum' });
 $('select').select2().select2('val', $('.select2 option:eq(3)').val());

        });

.. How can I check where I am missing something ?

A: You need to attach click event as follows and use  val method to set value
For E.x
var e1 = $("select[name$=deptId]").select2();

var e2 = $("select[name$=cmnlSctnId]").select2();

e1.on("click", function () { alert("test"); e2.val("2").trigger("change"); });

Please check the JSFiddle for select2 selection
https://jsfiddle.net/6ncs0vvh/


text:
Q: To choose between linear or generalised mixed effects model, what is the most important thing to consider? Linear mixed effects models are for continuous variables.
Generalised ones are for non continuous, e.g., binomial.
We have a task in which subjects can get each item correct or incorrect. I'd say that is binomial at the level of subject at least.
Other member of the teams says the most important thing to make this decision is the research question, which is "how many items out of 0 they will get correct at each test", and suggested to treat the variable as continuous and use a linear model.
Also, we got many 0s (almost 80% in the last of 3 tests), so maybe we shouldn't even use binomial but zero inflated binomial. This would be important if we decide to use the brms package for R. Meanwhile, we will use lme4.
What do you think?

A:
Linear mixed effects models are for continuous variables. Generalised ones are for non continuous, e.g., binomial.

This is not true. See the wiki page for generalized linear models. E.g., the gamma and exponential distribution are generalized linaer models and both are continuous. The difference is that you allow for other distribution than the normal distribution with generalized linear models.

We have a task in which subjects can get each item correct or incorrect. I'd say that is binomial at the level of subject at least.

Yes that is binomial data.

Other member of the teams says the most important thing to make this decision is the research question, which is "how many items out of N they will get correct at each test", and suggested to treat the variable as continuous and use a linear model.

I assume that you have fixed number of $n_i$ trials for each subject $i$. In that case it is a fraction that can have value ${0, 1/n_i, 2/n_i, \dots, 1}$. So you should use the binomial distribution as Dimitris Rizopoulos writes.

Also, we got many 0s (almost 80% in the last of 3 tests), so maybe we shouldn't even use binomial but zero inflated binomial. This would be important if we decide to use the brms package for R.

As far as I gather, you have some number of subjects, $k$, who each make some number of guesses, $n_1,\dots,n_k$. Then you model $E(y_i/n_i)$ where $y_i$ is the number of correct guesses from subject $i$. Assuming that you have no covaraites then the model with random effects could be
$$g(E(y_i/n_i)) = \mu + \epsilon_i,\qquad \epsilon_i\sim N(0,\sigma^2)$$
where $g$ is a link function (e.g., logit), $\mu$ is logit of the probability of a subject guessing correct when the random effect is zero, and $\epsilon_i$ is the random effect of subject $i$. Notice that this model easily yield "a lot of zeroes" if the $\mu$ is sufficiently small and you use the logit link function. Hence, a lot zeroes may not be good argument to use a zero inflated binomial in this case.

A: The number of successes out of N trials is a Binomial distribution. Hence, it seems that you should go for a mixed-effects logistic regression.


text:
Q: Passing Json object from angular to springboot in POST method I am new to Full stack development with Angular and Springboot.
I am trying to implement Cart functionality for my app.
My Spring boot controller is :
@RestController
@RequestMapping("cart")
@Slf4j
public class CartController {

    @Autowired
    ICartService cartService;

    @ApiOperation(value = "To add item to cart on with Book id and quantity from user")
    @PostMapping("/addToCart/{token}")
    public ResponseEntity<Response> addBookToCart(@PathVariable String token,@RequestBody CartDTO cartDto) {
        log.info("Cart dto: " + cartDto);
        Response response = cartService.addToCart(token,cartDto);
        return new ResponseEntity<Response>(response, HttpStatus.OK);
    }
}

And my CartDTO.java is:
public @Data class CartDTO {

    private long bookId;

    private int quantity;
}

In Angular, this is what my Cart Service looks it :
export class CartService {

   headeroption = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };
  constructor(private http: HttpClient) {
  }

  public addToCart(id:any) {

    let cartObj = {
      "bookId" : id,
      "quantity" : 2
    }
    var token = localStorage.getItem("ACCESS_TOKEN")

    return this.http.post("http://localhost:8080/cart/addToCart/"+token,cartObj,this.headeroption)
  }
}

But on executing public addToCart(id:any) method, in spring controller I am getting response with value as '0' :
Cart dto: CartDTO(bookId=0, quantity=0)

Can some tell me why I am not getting the required data in my controller?


text:
Q: parallel operations with audio stream c# I record sound in c#(wpf) and when data from sound card is available it calls this event:
void myWaveIn_DataAvailable(object sender, WaveInEventArgs e)
    {
        for (int index = 0; index < e.BytesRecorded; index += 2)//Here I convert in a loop the stream into floating number samples
        {

            short sample = (short)((e.Buffer[index + 1] << 8) |
                                    e.Buffer[index + 0]);
            samples32Queue.Enqueue(sample/32768f);
        }
        //***Do some Processing with data inside Queue
    }

As you can see I push every sample from the recorded buffer to a queue that is declared like that:
Queue<float> samples32Queue = new Queue<float>();

As you can see inside the event after the for loop I want to do some processing on the Queue. I worry that while processing the data, a new samples will come from the sound card and my processing will got lost.

*

*What is the right approach to make that?

*Is the processing that I call from the event is a static method/non-static?

A: Given the fact you can buffer the samples and process them later, consider using BlockingCollection. BlockingCollection is an excellent solution for producer-consumer pattern, which to my understanding, is your case. On one side you have myWaveIn_DataAvailable() method as a producer adding samples to the collection, and on the other end you have another consuming thread (it doesn't have to be another thread, though) collecting the samples and processing them. There are various ways the consumer can be implemented, and they are well documented in MSDN.
EDIT:
See the following example, I did not test it but it should give you a start point:
class ProducerConsumerExample
{
    BlockingCollection<float> samples32Collection;
    Thread consumer;
    public ProducerConsumerExample()
    {
        samples32Collection = new BlockingCollection<float>();
        consumer = new Thread(() => LaunchConsumer());
        consumer.Start();   //you don't have to luanch the consumer here...
    }
    void Terminate()    //Call this to terminate the consumer
    {
        consumer.Abort();
    }
    void myWaveIn_DataAvailable(object sender, WaveInEventArgs e)
    {
        for (int index = 0; index < e.BytesRecorded; index += 2)//Here I convert in a loop the stream into floating number samples
        {

            short sample = (short)((e.Buffer[index + 1] << 8) |
                                    e.Buffer[index + 0]);
            samples32Collection.Add(sample / 32768f);
        }
    }

    void LaunchConsumer()
    {
        while (true /* insert your abort condition here*/)
        {
            try
            {
                var sample = samples32Collection.Take();   //this thread will wait here until the producer add new item(s) to the collection
                Process(sample);    //in the meanwhile, more samples could be added to the collection
                                    //but they will not be processed until this thread is done with Process(sample)
            }
            catch (InvalidOperationException) { }
        }
    }
}


text:
Q: include anchor links or add multiple url in (event.url) at angular2+ It works fine though on regular links - /press/media, but not with anchor links - /press/media#152. how will I include both regular and anchor links or add multiple url with the existing code below?
in app.component.ts
 this.router.events
    .subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.headerFooter = (event.url !== '/press/media')
      }
    });

hope someone can help me.


text:
Q: Why are internal class attribute variables not visible in aspx inline markup? I am working on learning asp.net a little, and have found that the 'internal' keyword modified attribute members of a different class from the codebehind but in the same project as an aspx file are not visible from that aspx inline markup.  Is there a reason for that scoping separation?  Relatedly, assuming the server hosting the asp.net website code will be reasonably secured, is there a security risk with marking things like, as an example, database connection string credential literals with the public modifier?

A: internal means "visible within the same assembly". In ASP.NET, the markup and the codebehind may not be in the same assembly.


text:
Q: Is this function O(N) or O(logn)? the for loop iterates through only half of the array but it checks both ends each time this is just an array and it traverses the array checking if the nums[i] is greater than both nums[i - 1] and nums[i+1]
for (int i = 1; i < nums.size() / 2; ++i) {
    if (nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) {
        return i;
    }

    if (nums[nums.size() - i - 1] > nums[nums.size() - i] &&
        nums[nums.size() - i - 1] > nums[nums.size() - i - 2]) {
        return nums.size() - i - 1;
    }
}


text:
Q: Telerik RadListBox - how to default select some items? I'm using a Telerik RadListBox (multi-select) in a Silverlight/C# application. First they wanted all items in the list to be selected by default. Ok, no problem:
RadListBox.SelectAllCommand.Execute(null, listboxname);
But now, one of the four items needs to be not selected by default, the other three selected. I've searched and searched for a code sample, fruitlessly. How can I accomplish this seemingly simple task?

A: Since the SelectedItems property of a RadListBox is of type IList, it is possible to still add items to that list instead of explicitly setting SelectedItems equal to another list.
For example, this will select all names not equal to 'Bobby' by default.
XAML:
<Grid>
    <telerik:RadListBox x:Name="ListBox"
                        SelectionMode="Multiple"/>
</Grid>

Code-Behind:
public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();
        IList<string> names = new List<string>();
        names.Add("Alexander");
        names.Add("Bobby");
        names.Add("Chris");
        names.Add("Dean");

        ListBox.ItemsSource = names;

        foreach (var name in names.Where(x => x != "Bobby"))
        {
            ListBox.SelectedItems.Add(name);
        }
    }
}


text:
Q: Google Maps stopped working on WP site I have a Wordpress site where I embed Google maps into certain pages. They stopped working a couple of weeks ago and I can't figure out what has changed. I don't receive any errors in the Chrome console so its proving difficult to debug. Anyone have any ideas what may have changed on Google's end to make them stop working?
http://blackwoods.com.s110597.gridserver.com/restaurant-locations/duluth-mn/
Cheers

A: Try to upgrade the map type names, for example change G_MAP_TYPE to G_NORMAL_MAP. Check this out http://code.google.com/apis/maps/documentation/upgrade.html#MapTypeNames.

A: Figured it out... I had added a css declaration that was overly broad in targeting. I had a class like so:
#wrapper{max-width: 100%}

So the GMap imagery and icons were getting scaled inappropriately. To correct I simply targeted my GMap container div and added:
#wrapper .GMaps{max-width: none !important}

And that seems to have corrected the issues. Thank you for your help guys.


text:
Q: The Computer icon not functioning properly in Windows 7 When I left-click on the Computer icon on the desktop or in the Start menu (or right-click on the icon and then select Open), I'm immediately returned to the desktop. Speaking with MSDN tech support they tell me that my operating system is definitely hosed. And that I should do an "in-place upgrade" to re-establish a full operating system. So I tried.
It took about 10 hours but at the end asked me to reboot. I did so. And discovered that the operating system was gone. Fortunately I had made multiple backups on a secondary hard disk close onto external USB disks. I was quite fortunate. Not only was the operating system hosed but the entire partition table was gone as well.
I use Acronis for my backups and it asked where to restore my backups. There was no C: drive. I ended up having to reinstall the operating system Windows 7 Ultimate on a machine that was initially running XP Professional and had been upgraded to Vista Ultimate and then to Windows 7 Ultimate. So I did a fresh install onto the un-allocated space that had been my C: drive. It took a long time but it successfully restored my missing drive.
So the question still exists: what is causing my Computer icon to not function?

A:
what is causing my "computer" icon to not function?

I) Possible reasons:

*

*A) file associations for .lnk was broken or changed by an application
or by a user manipulation

*B) some registry keys are changed, deleted

*C) Some files including the registry hives was
located on a Hard Disk Bad sector

II) Here some fixes for the future if you have the same problem:
a) Rebuilding the Icon Cache Database

*

*Close all folder windows currently open.

*Launch Task Manager

*In the Process tab, right-click on the Explorer.exe process and select End Process.

*Click the End process button when asked for confirmation.

*From the File menu of Task Manager, select New Task

*Type CMD.EXE, and click OK

*In the Command Prompt window, type these commands:
CD /d %userprofile%\AppData\Local
DEL IconCache.db /a
EXIT

*In Task Manager, click File, select New Task. Type EXPLORER.EXE, and click OK.
b) File Association Fixes for Windows 7
http://www.winhelponline.com/blog/file-asso-fixes-for-windows-7/
Check for LNK hyperlink to download a zip file a .reg to merge (write) in the W7 registry
c) Fix broken desktop shortcuts and common system maintenance tasks
http://support.microsoft.com/mats/system_maintenance_for_windows/en-us
III) Comments:
a)

Speaking with MSDN tech support they tell me that my operating system
  is definitely hosed. And that I should do an "in-place upgrade" to
  reestablish a full operating system.

All this for a broken desktop icon? I'm little bit astonished by the advice you received to say the less...
b) Running a CHKDSK is sometimes the best way to recover from strange behaviour in Windows
I suggest you to check the S.M.A.R.T. values of the hard disk before running this command.
If the s.m.a.r.t. are not in «Good» state, chkdsk may kill a near to fail HD.
Hope this help. Let us know. :)
EDIT: the solution founded to solved this problem: «I created a new admin account, added some desktop icons and changed some minor stuff in folder options (single click, show all in folder, etc.) and the "Computer"is working like a champ! »

A: Check the link of your computer icon (right click, properties, link)
When you find e.g. ...scandisc.exe or other programs from your profile
then it is a trojan.

A: The Computer icon is not a .lnk file, but a built-in icon, so answers pertaining to .lnk files probably won't help.
It sounds like the program is crashing. The Computer icon will launch a new explorer.exe process. For whatever reason, it is not allowing it to be created, or it is launching but the window is not drawing. I would check, first, to ensure that you can launch folder windows through other methods. Try pressing Win+E, which should open an Explorer windows. You can also try clicking the Library icon in the taskbar (if it is pinned), or pressing Win+R to open the run dialog box, and then type explorer.exe and hit Enter. If none of these methods successfully open a program window, then it seems that explorer.exe is crashing or failing to load, for some reason, when opened as a child process in Windows (explorer.exe also functions as the main process that runs the Windows desktop).
To gain more information, I would then open up the Event Viewer (hit the Win key and type "Event viewer", and then hit Enter) and under Windows Logs, and check under the categories "Application" and "System". Try and see if there are any events marked as errors reported that seem to correspond to attempts to launch "Computer" from the desktop. If there is, this should help give you more information.
From there, you can try and deduce your next course of action.
P.S.: If it appears that explorer.exe is crashing, then you may have a corrupted file, and so restoring the binary may help. The Windows rep's suggestion of doing an in-place upgrade would have been a proper solution for this.
Considering your other issues when trying to do the upgrade, with your hard disk, it is possible that you have a corruption on the physical disk itself, which just so happens to be where it's trying to load data from when you attempt to launch 'Computer'. Run chkdsk on drive C: and see if it shows any errors. Choose to repair any if it does.
And keep on saving backups!


text:
Q: Why is this a complete sentence? "Another organization, the International Writing Program at the University of Iowa, offers writers from around the world a three-month residency in which to share not only stories and poems but also the experience of navigating a new environment."
Specifically, I am having problems with the bolded "to", which I feel should be replaced by "they". Can someone clarify why this is a full sentence - I am having difficulty visualizing it.


text:
Q: Dependence of the energy of an electron on distance from the nucleus I was going through an article given to me by my teacher which gave info about the influence of the positive nucleus on the electrons in the 's orbital', 'p orbital' and 'd orbital' respectively.
Here I am quoting the part of the article which I didn't understand.

Despite the shielding of the outer electrons from the nucleus by the inner shell electrons, the attractive force experienced by the outer shell electrons increases with increase of nuclear charge. In other words, the energy of interaction between, the nucleus and electron (that is orbital energy) decreases (that is more negative) with the increase of the atomic number (Z).

Now after reading the article further I came across this paragraph..

The energy of electrons in s orbital will be lower (more negative) than that of p orbital electron which will have less energy than that of d orbital electron and so on.

Aren't both the above paras contradicting?
First, it says that as the electron is away from nucleus, the nucleus's influence decreases. (like it should) Then why is electron more negative? (see brackets in first para above).
Does it mean that as the electron moves away then it has less positive charge and the negative charge dominates?
But in the second para it says that the electron in s orbital (which is near nucleus) is more negative? I mean what's going on in both of these paras?
All in all I want to know,

*

*Is electron near nucleus more negative/less negative and has lower energy/higher energy?
OR

*

*Is electron away from nucleus more negative/less negative and has lower energy/higher energy?
And why?
Please help me. I did genuine efforts to understand all this and surfed internet for many hours but couldn't get it.

Reference for the text quoted above: NCERT Class XI Chemistry Book, chapter 2, §2.6.3 (Energies of orbitals), also available as ark:/13960/t0tr17s5t.

A: The two statements are independent and not at all contradictory. Specifically:

*

*For all subshells (but keeping the subshell fixed), as you increase the nuclear charge $Z$, the energy becomes more negative.

*For a fixed nuclear charge $Z$, as you look at the different subshells of the same atom, the $s$-shell electrons will be more tightly bound (have a more negative energy) than the $p$-shell electrons.

The only way to glean a contradiction from this is to compare apples with oranges.

A: Let me break it down for you .The statements quoted in that article talk about two types of energies:
The one which is due to the nucleus of an atom, and the other which is the energy lost by the electron when it starts coming towards a nucleus.
When an electron is away from a nucleus it has zero influence over it(by the nucleus of an atom) , so when it gets attracted by a nucleus, in starts loosing energy and therefore it's energy becomes negative .So we can say that the electrons which are more close to the nucleus have more negative energy relative to other electrons away from the nucleus. Similar thing happens in case of s, p and d subshell. The electrons present in s subshell are more close to the nucleus then the ones present in p or d subshell. The electrons present in the s subshell decrease the nuclear factor on the electrons present in the outer shells in such a way that electrons present in the S subshell have relatively more energy then the electrons present in the outer shell.


text:
Q: How to use useRef with Typescript/Formik? I am passing a ref property into my custom FieldInput that I use for Formik validation of my form. However, it gives a few Typescript errors. For instance, in my function:
    const handleSubmitForm = (
    values: FormValues,
    helpers: FormikHelpers<FormValues>,
  ) => {

    setShowFlatList(true);
    Keyboard.dismiss();
    helpers.resetForm();
    if (fieldRef && fieldRef.current){
          fieldRef.current.blur();}
    helpers.resetForm();
  };

I get an error on fieldRef.current that Object is possibly 'undefined'.. I thought adding the if condition would fix it but it didn't. Also, when I submit the form, I get a warning that
Warning: An unhandled error was caught from submitForm()
Error: "fieldRef.current.blur is not a function. (In 'fieldRef.current.blur()', 'fieldRef.current.blur' is undefined)" in handleSubmitForm

Similarly, in my custom FieldInput component where I use  ref={fieldRef}, I get an error that:
Type '{ ref: MutableRefObject<undefined>; setFieldTouched: (field: string, isTouched?: boolean | undefined, shouldValidate?: boolean | undefined) => void; handleChange: { ...; }; ... 4 more ...; placeholderText: string; }' is not assignable to type 'IntrinsicAttributes & FieldInputProps & { children?: ReactNode; }'.
  Property 'ref' does not exist on type 'IntrinsicAttributes & FieldInputProps & { children?: ReactNode; }'.ts(2322)

How can I fix these?
Here's a codesandbox:
https://snack.expo.io/@nhammad/jealous-beef-jerky-fix

A: If you look into current generic types of your forwardRef method, first parameter is unknown. Just change your signature method of input to
export const FieldInput = React.forwardRef<Input, FieldInputProps>(...)

Typescript will automatically resolve correct type based on forwardRef method return type.


text:
Q: Make HTML map element visible HTML has supported image maps since time immemorial. You know, this sort of thing
<img src="url/to/your/image.jpg" alt="" usemap="#Map" />
<map name="Map" id="Map">
  <area href="#" shape="poly" coords="381,90,386,64,421,32,462,19,501,32,535,62,540,83" />
  <area href="#" shape="poly" coords="509,115,511,127,492,132,483,119,487,112" />
  <area href="#" shape="poly" coords="425,113,433,108,449,118,444,128,429,128" />
</map>

I have some data in a database that determines the source for an image and defines named sets of area coordinates. This is stored as a string of JSON which parses into an object graph, and knockout renders it all into a web page complete with click handlers that return the correct identifier for each area.
All this works just fine, and I mention it only to provide operational context.
When the user clicks an area, I'd like to toggle its visibility. For example, imagine indicating one or more affected regions for an injury on an anatomical diagram, or the bent bits of the car in an insurance claim app, that sort of thing.
The problem is making an area visible. Areas do not render. So I need to draw over the image. I know it can be done; google maps does it.
I don't know where to start or what to search for. This is the first time I've ever needed to draw directly - normally I supply elements and let the browser render as it will.
So, how about some search terms, key words and perhaps even links to video tutorials? In particular I need to overlay the image so I need to draw in the same coordinate space. While you're all busy downvoting this question I'll be researching "canvas" and "drawing over images".

A: From responses to other related questions it appears the HTML committee has been squabbling about image maps for canvas for five years.
Short version: you can't.
Long version: Use a canvas, set the image as its background and do your own hit testing.

A: You can "highlight" mapped portions of your img like this:

*

*Exactly overlay a canvas element of the same size using CSS

*Tell canvas not to respond to mouse/touch events: pointer-events:none

*When a mapped area is clicked, tell canvas to draw that area in a low-opacity fill using path commands:
context.beginPath();
context.moveTo(381,90);
context.lineTo(386,64);
context.lineTo(421,32);
context.lineTo(462,19);
context.lineTo(501,32);
context.lineTo(535,62);
context.lineTo(540,83);
context.closePath();
// fill the path area with a low-opacity red (or color of you choosing)
context.globalAlpha=0.15;
context.fillStyle='red';
context.fill();   // this fills the path
context.globalAlpha=1.00;  // just resetting to default opacity

That allows you to keep your existing code that uses img.
Alternatively, if your design permits significant refactoring, you can draw the image on canvas and use context.isPointInPath to hit-test each path versus the mouse-click position. Then fill the hit path with the low-opacity fill.
[ Addition: Saving area coordinates for later use in hit-testing ]
Warning: untested code, might need tweaking
For easy re-use of each areas coordinates, you can put each set of coordinates in an object and put those objects in an array:
var areas=[];
// first area coordinates
arrays.push([ {x:381,y:90}, {x:386,y:64}, ... etc ]);
// second area coordinates
arrays.push([ {x:509,y:115}, {x:511,y:127}, ... etc ]);
...

Then use those saved area coordinates to do your hit-testing:
function isMouseInArea(mouseX,mouseY){

    var index;  // index of any "hit" area. leave it initially null
    for(var i=0;i<areas.length;i++){

        // create a path from this area's coordinates
        defineAreaPath(areas[i]);

        // test if the mouse is inside this area
        if(ctx.isPointInPath(mouseX,mouseY)){
            index=i;
        }

    }
    // return any "hit" index of areas[] or return null if no hits
    return(index);
}

// utility function to define a path from the supplied coordinates
function defineAreaPath(pts){
    // create a path from this area's coordinates
    ctx.beginPath();
    ctx.moveTo(pts[0].x,pts[0].y);
    for(var i=1;i<pts.length;i++){
        ctx.lineTo(pts[i].x,pts[i].y);
    }
    ctx.closePath();
}

And you can use the isMouseInArea function like this:
var index=isMouseInArea(mouseX,mouseY)
if( index ){
    // draw the area path that was "hit" by the mouse
    defineAreaPath(areas[index]);
    // fill that path with low-opacity fill
    ctx.globalAlpha=0.15;
    ctx.fillStyle='red';
    ctx.fill();
    ctx.globalAlpha=1.00;
}


text:
Q: How can I push 1903 to1909 windows update through Intune on hybrid env? Using hybrid env, would like to use inTune function to push updates 1903 to 1909.
Would like to push for upto 50 machines together.

A: You can configure policies to assign the Windows updates, if that's how you are hoping to manage this.
From Create and assign Windows 10 feature updates:

*

*Sign in to the Microsoft Endpoint Manager admin center.

*Select Devices > Windows > Windows 10 Feature updates > Create.

*Under Basics, specify a name, a description (optional), and for Feature update to deploy, select the version of Windows with the feature set you want, and then select Next.

*Under Assignments, choose + Select groups to include and then assign the feature update deployment to one or more groups. Select Next to continue.

*Under Review + create, review the settings and select Create when ready to save the Windows 10 feature updates policy.
You can also review the policy overview.
Let me know if this helps and is what you are looking for.


text:
Q: How to install python cairo? I am new to python3. I have created the virtual environment. I try to install the pycairo package using pip command. I need install python cairo. Please see the below info
pip install git+http://anongit.freedesktop.org/git/pycairo
Downloading/unpacking git+http://anongit.freedesktop.org/git/pycairo
  Cloning http://anongit.freedesktop.org/git/pycairo to /tmp/pip-0c_foz-build
  Running setup.py egg_info for package from git+http://anongit.freedesktop.org/git/pycairo
    cairo >= 1.10.2  Successful

Installing collected packages: pycairo
  Running setup.py install for pycairo
    cairo >= 1.10.2  Successful
    building 'cairo._cairo' extension
    gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/cairo -I/usr/include/glib-2.0 -I/usr/lib/i386-linux-gnu/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng12 -I/usr/include/python3.2mu -c src/cairomodule.c -o build/temp.linux-i686-3.2/src/cairomodule.o
    src/cairomodule.c:22:20: fatal error: Python.h: No such file or directory
    compilation terminated.
    error: command 'gcc' failed with exit status 1
    Complete output from command /home/nyros/Desktop/NewWeb/venv/bin/python3 -c "import setuptools;__file__='/tmp/pip-0c_foz-build/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-lo0egc-record/install-record.txt --single-version-externally-managed --install-headers /home/nyros/Desktop/NewWeb/venv/include/site/python3.2:
    cairo >= 1.10.2  Successful

creating py3cairo.pc

creating src/config.h

running install

running build

running build_ext

building 'cairo._cairo' extension

creating build

creating build/temp.linux-i686-3.2

creating build/temp.linux-i686-3.2/src

gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/cairo -I/usr/include/glib-2.0 -I/usr/lib/i386-linux-gnu/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng12 -I/usr/include/python3.2mu -c src/cairomodule.c -o build/temp.linux-i686-3.2/src/cairomodule.o

src/cairomodule.c:22:20: fatal error: Python.h: No such file or directory

compilation terminated.

error: command 'gcc' failed with exit status 1

----------------------------------------
Command /home/nyros/Desktop/NewWeb/venv/bin/python3 -c "import setuptools;__file__='/tmp/pip-0c_foz-build/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-lo0egc-record/install-record.txt --single-version-externally-managed --install-headers /home/nyros/Desktop/NewWeb/venv/include/site/python3.2 failed with error code 1 in /tmp/pip-0c_foz-build
Storing complete log in /home/nyros/.pip/pip.log

But I got the error. Please solve my problem. Thanks

A: I think this may solve your problem:
sudo apt-get install python3-dev
But I cannot guarantee that this will work 100% :-)


text:
Q: Animating a div's apearance on mouseover in jquery I wanted to animate a div on mouseover.
I just don't know how to make it fade in/appear slowly (I think we have to use the .animate function or something like that)
$("#logo").mouseover(function() { $("#nav").css('visibility','visible'); });

Will appreciate any help :)

A: $("#logo").mouseover(function() { $("#nav").fadeIn("slow"); });

Make sure your css has style for #nav as display:none;
Reference http://api.jquery.com/fadeIn/
SAMPLE DEMO

A: Try this:
$("#logo").mouseover(function() {
    $("#nav").fadeIn('slow');
});

Refer Site http://api.jquery.com/fadeIn/

A: You can use the fadeIn/fadeOut methods or the fadeToggle method which automatically fades in or out. Every method allows a duration parameter to set the animation time, but there also many more parameters to modify the fading.
Look at the API for fadeToggle to see the whole functionality (and how to use) :) . (fadeIn API, fadeOut API).

A: USe fadeIn()... try this.
$("#nav").hide();
$("#logo").mouseover(function() { $("#nav").fadeIn(600));

A: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sample</title>

Click Me

sample


text:
Q: How to disable selected days? I have booking form to reservastion hotels so I want to disabled selected days how can I do that ? I mean if I select 20 from first datepicker so 20 must be unselectable in second datepicker

function datePicker() {
  var dateFormat = "DD/MM/YY",
    from = $("#checkin,.checkin").datepicker({
      //numberOfMonths: 2,
      firstDay: 1,
      minDate: 0,
      ignoreReadonly: true,
      showButtonPanel: true,
      closeText: 'Temizle',
      onClose: function(dateText, inst) {
        if ($(window.event.srcElement).hasClass('ui-datepicker-close')) {
          document.getElementById(this.id).value = '';
          //$('.checkin,#checkin,#checkout,.checkout').val('');
        }
      },
      onSelect: function(selectedDate) {
        window.setTimeout($.proxy(function() {
          $(this).parents(".book-holiday").find("#checkout,.checkout").focus();
        }, this), 10);

        var date2 = $('#checkin,.checkin').datepicker('getDate');
        date2.setDate(date2.getDate() + 1);
        $('#checkout,.checkout').datepicker('setDate', date2);
        //sets minDate to dt1 date + 1
        $('#checkout,.checkout').datepicker('option', 'minDate', date2);
      },
      isTo1: true,
      beforeShow: function(input, inst) {

        $(this).datepicker("widget").addClass("main-datepicker");
        // controlDatepicker(".checkin,#checkin");
        /*setTimeout(function() {
            inst.dpDiv.css({
                top: $(".datepicker").offset().top + 35,
                left: $(".datepicker").offset().left
            });
        }, 0);*/
      }
    });
  $("#checkout,.checkout").datepicker({
    firstDay: 1,
    minDate: 0,
    ignoreReadonly: true,
    showButtonPanel: true,
    closeText: 'Temizle',
    onClose: function(dateText, inst) {
      if ($(window.event.srcElement).hasClass('ui-datepicker-close')) {
        document.getElementById(this.id).value = '';
        //$('.checkin,#checkin,#checkout,.checkout').val('');
      }
      var dt1 = $('#checkin.checkin').datepicker('getDate');
      console.log(dt1);
      var dt2 = $('#checkout,.checkout').datepicker('getDate');
      if (dt2 <= dt1) {
        var minDate = $('#checkin,.checkin').datepicker('option', 'minDate');
        $('#checkin,.checkout').datepicker('setDate', minDate);
      }
    },
    ignoreReadonly: true,
    isTo1: true,
    onSelect: function() {
      //$(this).parents(".book-holiday").find(".popover-wrapper").addClass("open");
    },
    beforeShow: function(input, inst) {
      /* $(this).datepicker("widget").addClass("main-datepicker");
       controlDatepicker(".checkin,#checkin");
       setTimeout(function() {
           inst.dpDiv.css({
               top: $(".datepicker").offset().top + 35,
               left: $(".datepicker").offset().left
           });
       }, 0);*/
    }

  });

}

datePicker();
<link href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet" /> From : <input type="text" class="checkin"> To: <input type="text" class="checkout">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

A: Try something like this:
$("#dt1").datepicker({
            dateFormat: "dd-M-yy",
            minDate: 0,
            onSelect: function (date) {
                var date2 = $('#dt1').datepicker('getDate');
                date2.setDate(date2.getDate() + 1);
                $('#dt2').datepicker('setDate', date2);
                //sets minDate to dt1 date + 1
                $('#dt2').datepicker('option', 'minDate', date2);
            }
        });
        $('#dt2').datepicker({
            dateFormat: "dd-M-yy",
            onClose: function () {
                var dt1 = $('#dt1').datepicker('getDate');
                console.log(dt1);
                var dt2 = $('#dt2').datepicker('getDate');
                if (dt2 <= dt1) {
                    var minDate = $('#dt2').datepicker('option', 'minDate');
                    $('#dt2').datepicker('setDate', minDate);
                }
            }
        });

Working Fiddle

A: Maybe you could try to store date and compare them when action is triggered? In that case you will not trigger any action when condition is not fulfilled.
Or you could use something iike that:
Jquery UI datepicker. Disable array of Dates


text:
Q: * What went wrong: A problem occurred evaluating project ':app'. > No such property: storeFile for class: java.io.File I am not using null safety now, how can I fix this problem on my build.gradle. I am trying to build my apk to appbuild and I am a beginner. am I open the null safety or am I have a chance to do it without null safety. Thanks, StackOverflow users. <3
def keystoreProperties = new Properties()
    def keystorePropertiesFile = rootProject.file('key.properties')
        if (keystorePropertiesFile.exists()){
        keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
    }

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 31

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.saka.bluetooth_controller"
        minSdkVersion 18
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    signingConfigs {
        release {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile keystorePropertiesFile['storeFile'] ? file(keystoreProperties['storeFile']) :null
            storePassword keystoreProperties['storePassword']
        }
    }
     buildTypes{
        release{
            signingConfig signingConfigs.release
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}


text:
Q: skip a video (in a loop) based on keypress in PsychoPy using MovieStim2 I play 3 videos using MovieStim2 in PsychoPy. I suspect this issue stems from not really understanding loops, though.
I want to skip to the next video when the participant presses a key. I understand how my code quits when the participant presses "q", but I'm not sure how to make it skip to the next video when they press "b", for example. Here is my current code:
vidNum = 1
for f in ['clip1.mpg', 'clip2.mpg', 'clip3.mpg']:
    clock.reset()
    #logfile.write("AfterForLoopTime,%s,Video %s\n" % (core.getTime(), vidNum))
# Create your movie stim.
    mov = visual.MovieStim2(win, videopath+f,
                       size=640,
                       # pos specifies the /center/ of the movie stim location
                       pos=[0, 0],
                       flipVert=False,
                       flipHoriz=False,
                       ) # loop=False - need to comment this to use a loop

# Start the movie stim by preparing it to play
    shouldflip = mov.play()
    logfile.write("AfterShouldflipLine58,%s, Video %s\n" % (clock.getTime(), vidNum))
    while mov.status != visual.FINISHED:
    # Only flip when a new frame should be displayed. Can significantly reduce
    # CPU usage. This only makes sense if the movie is the only /dynamic/ stim
    # displayed.
        if shouldflip:
        # Movie has already been drawn , so just draw text stim and flip
        #text.draw()
            win.flip()
        else:
        # Give the OS a break if a flip is not needed
            time.sleep(0.001)
    # Drawn movie stim again. Updating of movie stim frames as necessary
    # is handled internally.
        shouldflip = mov.draw()

    # Check for action keys.....
        for key in event.getKeys():
            if key in ['escape', 'q']:
                win.close()
                core.quit()

I tried adding code similar to the last chunk which quits after q:
            elif key in ['b']:
                break

but I realize that I really want to break out of this loop:
for f in ['clip1.mpg', 'clip2.mpg', 'clip3.mpg']:

However, this doesn't seem to work either
for f in ['clip1.mpg', 'clip2.mpg', 'clip3.mpg']:
    for key in event.getKeys():
        if key in ['b']:
           break

A: The loop you actually want to break is:
while mov.status != visual.FINISHED:

The easiest way I can think of is to just set your movie status to -1 (or visual.FINISHED) if the user hits the key.
For example:
if key in ['b']:
    mov.status = -1

This will break you out of your current video from what I can tell.


text:
Q: how to use DateAdd in while I create a function to get date of the next four weeks.For do this I use belowe code . but i does'nt complie and get error .
    create function GetNextDays()
returns @somedays table
(

dayDate date
)
as
begin
declare @today date=getdate()
declare @index int=0
while @index<3
    begin
    insert @somedays(dayDate) values(@today)
    set @index=@index+1;
     DATEADD(DD,7,CAST(@today AS DATE))
    end
return
end

I getting this ERROR:

Incorrect syntax near 'DATEADD'.

A: You shouldn't use a loop for this at all. You should be using a numbers or tally table. I put this in a cte here for you to see. I have a view on my system that I can use for this type of thing without the need for loops.
WITH
    E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
    E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
    E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
    cteTally(N) AS
    (
        SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
    )

select DATEADD(day, N, cast(getdate() as DATE))
from cteTally
where N <= 3

A: you shoud use set befor DateADD. see belowe code:
   alter function GetNextDays()
returns @somedays table
(

dayDate date
)
as
begin
declare @today date=getdate()
declare @index int=0
while @index<3
    begin
    insert @somedays(dayDate) values(@today)
    set @index=@index+1;
    set @today= DATEADD(DD,7,cast(@today as date))
    end
return
end

chnage this Line:
DATEADD(DD,7,CAST(@today AS DATE))

with :
set @today= DATEADD(DD,7,cast(@today as date))