text:
Q: Should I implement a checksum process for the data transmited through serial port using Pyserial? This is my first question on StackOverflow and I'm still learning English. So I implore you your tolerance.
I'm working on a project where I need to receive data from USB serial port using Python (Pyserial library especifically). An arduino sends me the data through a serial cable and then I receive it from a COM port.
I'm currently implementing a basic checksum process to verify that the transmited data arrive complete. From the arduino I add the value of the data I am transmiting and set to checksum field, wich will be transmited too. Then, on the computer, I perfomr the same operation over the data and verify that the sum is equal to the value of the checksum field.
My question is. Should I worry about this or that task is already performed by USB protocol?
If someone could give me some reference, it would be very helpful for me.
This is how currently I am calculating the checksum:
{
    s1: 425.2,
    s2: 426.4,
    s3: 78.2,
    s4: 785.2,
    chksum: 1715
}

A: The USB does not correct the serial data. It is just a bus that the CPU uses to talk to the serial port with. You idea of adding some checksum to the protocol that you use to talk between the Arduino and PC is good and sound idea.
A very common hardware protocol used by serial ports is the RS232. It contains some support for error detection using a parity bit. If the parity bit isn't correct the received byte will just be thrown away. So I don't think it would be much help in you case.


text:
Q: Store argv[] into two arrays divided by a special string (C) I want to read the arguments from command line and store them into two arrays. The separation between the arrays will be denoted by "cut".
Example: a.out andy bob charlie ned cut amy sophie anna
array1 will be {andy, bob, charlie, ned}
array2 will be {amy, sophie, anna}
I found the argc of the word "cut". Then I ran a loop from 0 to that index for the first array. I am having trouble with the second array.
int cutindex, i;

for(i=1; i<argc; i++) {
  if(strcmp("cut", argv[i]) == 0){
    cutindex = i;
  }
}

char argv1[10];
for(i=0; i<cutindex-1; i++) {
  argv1[i] = argv[i+1];
}

char argv2[10];
for(i=0; i<argc-cutindex-1; i++) {
  argv2[i] = argv[cutindex+1];
}

For the second array, I am getting a repetition of the first value (amy) for the entire array. What am I doing wrong?
Firstly, is there a better (more efficient) way to do this?

A: There are a couple problems that were pointed out in the comments:

*

*In the third loop, the code uses cutindex + 1 to index into the argv array. But the loop doesn't change cutindex, so the first argument after "cut" ("amy" in the example) is repeated for the entire array.

*The output arrays argv1 and argv2 should be arrays of pointers.
One solution to the first problem is to use a separate index for each array. That way you can increment each index as needed, and don't need to attempt to compute indexes mathematically.
The added benefit is that when the code is finished, the final value of each output index is the count of elements in the corresponding output array.
Another added benefit is that you can limit the number of elements written to the array. Note that in the code below, any arguments after the first 10 are silently dropped. In real code, you might want to alert the user that they entered too many arguments.
#include <stdio.h>
#include <string.h>
#define MAX_ARG 10

int main(int argc, char *argv[])
{
    char *argv1[MAX_ARG];   // first array of arguments
    int n1 = 0;             // index into first array

    char *argv2[MAX_ARG];   // second array of arguments
    int n2 = 0;             // index into second array

    // copy pointers into the first array until "cut" is found
    int i;
    for (i = 1; i < argc; i++)
    {
        if (strcmp("cut", argv[i]) == 0)
            break;
        if (n1 < MAX_ARG)
            argv1[n1++] = argv[i];
    }

    // copy any remaining pointers into the second array
    for (i++; i < argc; i++)
    {
        if (n2 < MAX_ARG)
            argv2[n2++] = argv[i];
    }

    // print the arrays
    for (int i = 0; i < n1; i++)
        printf("argv1[%d] = '%s'\n", i, argv1[i]);
    putchar('\n');
    for (int i = 0; i < n2; i++)
        printf("argv2[%d] = '%s'\n", i, argv2[i]);
}

When run with the command line
./a.out andy bob charlie ned cut amy sophie anna

the output of this code is
argv1[0] = 'andy'
argv1[1] = 'bob'
argv1[2] = 'charlie'
argv1[3] = 'ned'

argv2[0] = 'amy'
argv2[1] = 'sophie'
argv2[2] = 'anna'

redpajama_set_name: RedPajamaStackExchange


text:
Q: href="#" redirects to 404 page in angularjs 2 I have a html theme which uses href="#" for opening sidebar menu and also uses the hash href='#' for tab switching - but in angularjs 2 I am unable to use it, the moment I click on it to open side-Menu or for Tab Switch - The browser page is changed and generally goes to 404 Error else refreshes the page itself
Currently I am studying the HashLocationStrategy in the API docs, but no luck yet. Do let me know how you solved this issue
update: hashLocationStrategy is not the solution I looking for

A: Looks like it is this issue https://github.com/angular/angular/issues/6595 you are running into.


text:
Q: Is this function a contraction mapping? I have real valued function defined by $g(t)=t-d(t)$ where $d(t)$ is a function such that $0 <d (t)\leq h $ and $d^\prime (t)\leq m <1.$ From these data one can clearly prove that $g(t)$ is a bijective and strictly increasing function. Now can one find any relation between the distances between the elements in the domain and codomain. I am clueless. Any hint would be of great help. Thanks in advance.

A: In order for $g(t)$ to be a contraction, you'd need there to exist some $k$ in $(0,1)$ such that, for any choice of $x$ and $y$ in $\mathbb{R}$, you get $|g(x)-g(y)| = |x-y - (d(x)-d(y))| \leq k|x-y|$.
With this in mind, here's a hint: can you find a function $d(t)$ satisfying the conditions such that $d(t)$ gets arbitrarily small as $t$ gets large? In particular, if you can get  $d(t)\rightarrow 0$ as $t\rightarrow \infty$, then you can show that for large enough $x$ and $y$, the quantity $\frac{|g(x)-g(y)|}{|x-y|}$ gets as close to $1$ as you like (and in particular, would eventually get bigger than any choice of $k$, so $g$ would not be a contraction).


text:
Q: Reordering a productlist block in Magento I'm a bit of a Magento noob. I have the following code in the Page Layout section of my home page:
<reference name="content">
    <block type="catalog/product_list" name="featured" template="catalog/product/list.phtml">
        <action method="setCategoryId"><category_id>8</category_id></action>
    </block>
</reference>

How do I change what attribute the products in this block are ordered by?

A: The order of a product list is generally controlled by the toolbar block Mage_Catalog_Block_Product_List_Toolbar. But if you want to be able to influence the way the product collection is ordered from the layout, you can do the following:
Rewrite the block Mage_Catalog_Block_Product_List and add a function to it:
public function setOrder($attribute, $direction)
{
    $collection = $this->_getProductCollection();
    $collection->clear()->setOrder($attribute, $direction);
    $this->_productCollection = $collection;
}

in the layout update add an action node, e.g.
<reference name="content">
    <block type="catalog/product_list" name="featured" template="catalog/product/list.phtml">
        <action method="setCategoryId"><category_id>8</category_id></action>
        <action method="setOrder"><attribute>name</attribute><direction>desc</direction></action>
</block>


text:
Q: ESports Match Predictor (Machine Learning) I think I'm starting to get the hang of some of the basics for machine learning, I've already completed three tutorial projects for stock price predicting, wine rating predictor, and a money ball (mlb) project. Now I am looking to do something a little more advanced with a personal project, but I can't seem to find information on how I would go about it.
I watch quite a bit of ESports and I found a game that has an extensive API with statistics of every rated match played, and I wanted to see if I could put together a match predictor.
The game is a 3v3 game were the users pick an Avatar (about 50ish in total) and battle each other on a specific map (about 10 in total). I think the important details to accomplish this would be the Avatars on each team, the position/role that the avatar plays, the map that was played, the player's personal rank, and what the final score was.
I pulled down 500k matches to train my data on and I created my "match objects" look like this -
{
  "map": "SomeMap",
  "team1score": 1,
  "team2score": 4
  "team1": [
    {"avatar": "whatever1", "position": "role1", "playerRank": 14},
    {"avatar": "whatever2", "position": "role2", "playerRank": 10},
    {"avatar": "whatever3", "position": "role4", "playerRank": 11},
  ],
  "team2": [
    {"avatar": "whatever4", "position": "role2", "playerRank": 11},
    {"avatar": "whatever5", "position": "role3", "playerRank": 12},
    {"avatar": "whatever6", "position": "role1", "playerRank": 11},
  ]
}

In the object above, there is the map, the team score, the avatars on each team, the role of each avatar, and the person's online rank.
I think where I am struggling is that there are more dimensions than what I did in the previous projects. How I originally started to code this was using a flat table like -
avatar1, avatar1_rank, avatar1_tier, avatar2, avatar2_rank, avatar2_tier, etc

but I quickly discovered in doing that, it was giving weight to where "on the team" the avatar was (index 1, index 2, or index 3) when it shouldn't matter where on the team the avatar is, just that he is on the team. Ordering alphabetically doesn't solve this either as there are 50 or so avatars to choose from, so avatars are pretty much just as likely to be in position 1 as position 3. So essentially I am looking to do an analysis on two teams of players, where the stats for the players are given, and the players could appear in any order on the team (1-3).
So my questions is - does anyone have any code or know of any similar sample projects?
Thank you all.

A: Let's approach this from an architectural perspective. Your main problem is..

but I quickly discovered in doing that, it was giving weight to where "on the team" the avatar was (index 1, index 2, or index 3) when it shouldn't matter where on the team the avatar is, just that he is on the team.

There are two potential solutions for this I can think of right away
Let's assume avatars A, B, C, D, E, ..
Prior Encoding (which I would recommend)
You could encode your teams into a single configuration specific value, which you would then hand over instead.
So you would map (A, B, C) and (A, C, B) and (B, A, C) and (B, C, A) and (C, A, B) and (C, B, A) to for example "Team A". This value would then carry the information that avatars A, B, and C have been on the team. This encoding would have to be done for each possible team. A simple look up table for the encoding will do. Obviously this encoding could also be left with another auxiliary model or layer for that matter.
Then you can just go ahead an train your model as usual.
Augmentation Interpretation
You could also take the stand that your model might as well just find out that the position does not influence the effect of a certain avatar. To support this learning, you would hand over samples with each potential configuration of the team (see possible combinations above) to the model while training - and at the same time keeping all other input values and the ground truth constant. This increases the training effort, does not necessarily mean that your model might do the job as well as you would like and is a pain for your data pipeline.

A: I've very loosely followed some "machine learning for League of Legends match prediction." The game you're describing sounds similar.
Encoding Problems: Relational vs. Non-Relational
The core problem is that you have relational data, and mainstream machine learning usually operates on non-relational data (or: "a flat table").
This:
"team1": [
    {"avatar": "whatever1", "position": "role1", "playerRank": 14},
    {"avatar": "whatever2", "position": "role2", "playerRank": 10},
    {"avatar": "whatever3", "position": "role4", "playerRank": 11},
]

... implies a JOIN happened behind-the-scenes to select the players that were present in a match.
We first have to transform from a relational representation into a flat feature vector. Some of these can be treated as categorical variables, and a one-hot encoding can represent the presence/absence of an avatar, role, or map:
import pandas as pd
import numpy as np

# Categorical variables
maps = ["Map1", "Map2", "Map3"]
avatars = ["A1", "A2", "A3", "A4", "A5", "A6"]
roles = ["ADC", "Top", "Support", "Mid", "Jungle"]

# Create variables for each team, using "Team 1" and "Team 2"
t1_avatars = ["t1_" + a for a in avatars]
t2_avatars = ["t2_" + a for a in avatars]
t1_roles = ["t1_" + r for r in roles]
t2_roles = ["t2_" + r for r in roles]

# Possible one-hot-encoding for categorical variables
n_columns = sum(len(l) for l in (maps, t1_avatars, t2_avatars, t1_roles, t2_roles))
df = pd.DataFrame(
    np.zeros((1, n_columns)),
    columns=maps + t1_avatars + t2_avatars + t1_roles + t2_roles,
)

   Map1  Map2  Map3  t1_A1  ...  t2_Top  t2_Support  t2_Mid  t2_Jungle
0   0.0   0.0   0.0    0.0  ...     0.0         0.0     0.0        0.0

And for the data here, the non-zero columns might look like this:
   Map1  t1_A1  t1_A2  t1_A3  t2_A4  t2_A5  t2_A6  t1_ADC  t1_Top  t1_Jungle  t2_ADC  t2_Top  t2_Support
0     1      1      1      1      1      1      1       1       1          1       1       1           1

For numeric features you might try simple summary statistics, like the sum of player ranks or average player ranks. Most summary statistics are invariant under permutation (i.e. sum(1, 2, 3) == sum(3, 2, 1)) so the feature is independent of the order you observe players in:
>>> sum(p['playerRank'] for p in data['team1'])
35
>>> sum(p['playerRank'] for p in data['team2'])
34

Existing Approaches
I'll discuss two cases. Neither addresses this problem.

*

*(arxiv) Using Machine Learning to Predict Game Outcomes Based on Player-Champion Experience in League of Legends

*(Medium) Using Machine Learning to Understand League of Legends
The Medium post describes using numeric features (total team deaths, total team kills, total minions cleared) prior to 10 minutes. i.e.: it avoids relational features.
The arxiv paper uses feature engineering to estimate "how good a player is at playing a champion." I suspect they ran into this same problem, because they suggest in section 3.2:

"For each match, we derived additional features to better reflect each team's overall player-champion experience. For both teams, we added the team's average, median, coefficient of excess kurtosis (i.e., how normal the distribution is), coefficient of skewness, standard deviation, and variance of the player's champion win rate and of their champion mastery points. The final training dataset contained 44 features per match (2 features per player for 10 players and 12 features per team)."

That's a little vague. I suspect this paper used an arbitrary order, so the vector of player skills might be:
[1.0, 0.5, 0.3, 1.2, 1.1]

... even though there are 120 valid ways to permute this sequence.
Or they might be assuming players always appear in a fixed order based on the role they played: [Top, Jungle, Mid, Support, Bottom]. There are five roles in LoL, and ranked queue/tournaments often display players in this order.

Side note: I recently answered a question about training neural networks on problems with interchangeable objects. The idea is to permute interchangeable variables at learning time, and sample from possible permutations at prediction time. However: the complexity is factorial in the number of variables.

Does anything handle relational features directly?
It's an open research problem!
Flattening from a relational to non-relational representation is lossy. If you want to get things working with statistical learning methods: aggregate, aggregate, aggregate. There's evidence that you can approximate with feature engineering and aggregation (e.g. Perlich and Provost 2006)
For something more specific:

*

*An Introduction to Lifted Probabilistic Inference by Guy Van den Broeck, Kristian Kersting, Sriraam Natarajan, and David Poole; is a recent treatment of advances on this topic.

*I maintain a project called srlearn (for: statistical-relational-learn) that tries to work with relational data directly—but it has some major caveats like not handling continuous features.


text:
Q: OpenGL weird rotation result with mouse So I'm working on a 3d painting application. I managed to make a basic renderer and model loader.
I created a camera system where I can use it to navigate around the scene(mouse/keyboard) but that's not what I want, so I made that camera static and now I'm trying to rotate/pan/zoom the model itself. I managed to implement panning and zooming. for panning i change the x/y position according to the mouse and for zooming I add or substract from the z-axis according to the mouse scroll.
But now I want to be able to rotate the 3d model with the mouse. Example: When i hold right mouse button and move the mouse up the model should rotate on it's x-axis(pitch) and if i move the mouse to the left/right it should rotate on y-axis(yaw). And I just couldn't do it.
The code bellow I get xpos/ypos of the cursor on the screen, calculate the offset and "trying to rotate the cube". The only problem is that i can't rotate the cuber normally if i move the mouse up the model rotate on the x-axis and y-axis with a little tilt and vice-versa.
This is the code in my rendering loop:
    shader.use();
    glm::mat4 projection = glm::perspective(glm::radians(45.0f),
    (float)SCR_WIDTH/(float)SCR_HEIGHT, 0.01f, 100.0f);
    shader.setMat4f("projection", projection);

    glm::mat4 view = camera.getViewMatrix();
    shader.setMat4f("view", view);

    glm::mat4 modelm = glm::mat4(1.0f);
    modelm = glm::translate(modelm, object_translation);
    // Should rotate cube according to mouse movement
    //modelm = glm::rotate(modelm, glm::radians(angle), glm::vec3(0.0f));
    shader.setMat4f("model", modelm);

    renderer.draw(model, shader);

This is the call where i handle the mouse movement callback:
void mouseCallback(GLFWwindow* window, double xpos, double ypos)
{
if (is_rotating)
{
    if (is_first_mouse)
    {
        lastX = xpos;
        lastY = ypos;
        is_first_mouse = false;
    }

    // xpos and ypos are the cursor coords i get those with the
    mouse_callback
    double xoffset = xpos - lastX;
    double yoffset = lastY - ypos;

    lastX = xpos;
    lastY = ypos;

    object_rotation.y += xoffset; // If i use yoffset the rotation flips
    object_rotation.x += yoffset;

    rotation_angle += (xoffset + yoffset) * 0.25f;
}
}

Mouse panning works fine too can't say the same for the rotation.

A: I fixed it. After some research and asking i was told that u can only do one rotation at a time and i was trying to do both x/y-axis in the same time. Once i seperate the two rotations. object will now rotate on x-axis first then y-axis the problem was solved.
The code should be like this:
    shader.use();
    glm::mat4 projection = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH/(float)SCR_HEIGHT, 0.01f, 100.0f);
    shader.setMat4f("projection", projection);

    glm::mat4 view = camera.getViewMatrix();
    shader.setMat4f("view", view);

    glm::mat4 modelm = glm::mat4(1.0f);
    modelm = glm::scale(modelm, glm::vec3(1.0f));
    modelm = glm::translate(modelm, glm::vec3(0.0f, 0.0f, -5.0f));
    // Handle x-axis rotation
    modelm = glm::rotate(modelm, glm::radians(object_orientation_angle_x), glm::vec3(object_rotation_x, 0.0f, 0.0f));
    // Handle y-axis rotation
    modelm = glm::rotate(modelm, glm::radians(object_orientation_angle_y), glm::vec3(0.0f, object_rotation_y, 0.0f));
    shader.setMat4f("model", modelm);

    renderer.draw(model, shader);

A: You are storing your rotation as euler angle inside object_rotation.
I advised you to use:
glm::mat4 rotation = glm::eulerAngleYX(object_rotation.y, object_rotation.x); // pitch then yaw

or
glm::mat4 rotation = glm::eulerAngleXY(object_rotation.x, object_rotation.y); // yaw then roll

In your case both should do the job, I advised you in the future to store thoose informations inside your camera (eye, up, center) instead of your object, everything become more simpler.


text:
Q: How to get data from url link itself I have created a verification link which is being sent as an email to anyone who is registring to my site.
I want to be able to take data from url itself for example if the link is
http://localhost/verify.php?email=zeeshanahmed95@gmail.com?&activate=XacSwLp4xPuMm0yHE5i7h5kK8xBw0hN5

I want to extract data from URL from the part which is email and activate and store it in a variable in PHP.

A: PHP has a built in $_GET variable set which should suit you fine.  Just comment if you need help.
$_GET['email']
$_GET['activate']

A: If the URL is just a string you have in data, then you can use parse_str...
$strURL = 'http://localhost/verify.php?email=zeeshanahmed95@gmail.com?&activate=XacSwLp4xPuMm0yHE5i7h5kK8xBw0hN5'
$arrVariables = array();
parse_str($strURL, $arrVariables);
echo $arrVariables['email'];


text:
Q: cURL bypassing same origin policy So I am writing a script for cURL, and the script emulates my browser in everywhere way. But I am still getting a session is invalid error. I was looking through the chrome console and saw two errors saying
"SecurityError: Blocked a frame with origin "http://localhost" from accessing a frame with origin "http://edugen.wileyplus.com". Protocols, domains, and ports must match"
"Uncaught SecurityError: Blocked a frame with origin "http://edugen.wileyplus.com" from accessing a frame with origin "http://localhost". Protocols, domains, and ports must match"
I looked up this error and I got some information on how it has to do with chrome no longer allowing frames or something, but I doubt it's that because the console references these two lines of code.
var win = self;
    while ( typeof(win.isLTIRoot) == 'undefined' && win.parent != null && win.parent != self && win.parent != win )

and this one
function setSTNOnLoadListener(wnd) {
    setSTNFrameOnLoadListener(wnd, wnd.document.getElementsByTagName('frame'));
    setSTNFrameOnLoadListener(wnd, wnd.document.getElementsByTagName('iframe'));
}

So what strategy should I use with cURL and what exactly is the problem.
Edit: More detail and curl code
So I am trying to log into a website and get to the mainframe. The whole process is tedious as I have to follow 9 location headers and everything goes fine but when I finally reach the webpage i get the error "your session is invalid".
here is the curl code for the last page for the mainframe.
$ch = curl_init();

// Set some options - we are passing in a useragent too here
curl_setopt_array($ch, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_FOLLOWLOCATION => FALSE,  // Setting cURL to follow 'location' HTTP headers
    CURLOPT_URL => $url9,
    CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0",
    CURLOPT_STDERR => $verbose = fopen('php://temp', 'rw+'),
    CURLOPT_VERBOSE => TRUE,
    CURLOPT_HTTPHEADER => array(
                                'Host: edugen.wileyplus.com',
                                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                                'Accept-Language: en-US,en;q=0.5'
                            ),
    CURLOPT_CAINFO => dirname(__FILE__)."\cacert.pem",
    CURLOPT_HEADER => TRUE,
    CURLOPT_COOKIEJAR => $ckfile,
    CURLOPT_COOKIEFILE => $ckfile
));
 if( ! $tenth_page = curl_exec($ch))
            {
                trigger_error(curl_error($ch));
            }
$urlEndpoint = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
echo "Verbose information:\n<pre>", !rewind($verbose), htmlspecialchars(stream_get_contents($verbose)), "</pre>\n";

curl_close($ch);

$tenth_page = str_replace("src=\"","src=\"http://edugen.wileyplus.com",$tenth_page);

echo $tenth_page;

A: I expect they have deployed some security to prevent their page being loaded within an iFrame from a different domain.
The other common mistake when developing is when your dev site is referenced as localhost - if you are making ajax calls then you should ensure you alias your dev site to be the same domain as the sites you are calling if they have any cross origin security set.


text:
Q: How to add a second player to this number guessing game for python? Hi i am unsure on how to add a second player for this number guessing game whereby after player 1 makes a guess, then player 2 makes a guess. like between every guess. I am only able to make it so that the player 2 guesses after player 1 guesses finish all of his choices(code below) if anyone is able to tell me if what i am looking for is possible or if there is any advice, it would be greatly appreciated. thanks in advance.
def main():
    import random
    n = random.randint(1, 99)
    chances = 5
    guess = int(input("Player 1 please enter an integer from 1 to 99, you have 5 chances: "))
    while n != "guess":
        chances -=1
        if chances ==0:
            print("out of chances")
            break
        if guess < n:
            print("guess is low")
            guess = int(input("Enter an integer from 1 to 99: "))
        elif guess > n:
            print ("guess is high")
            guess = int(input("Enter an integer from 1 to 99: "))
        else:
            print("you guessed it")
            break

        import random
    n1 = random.randint(1, 99)
    chances1 = 0
    guess1 = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances "))
    while n1 != "guess":
        chances1 +=1
        if chances1 ==5:
            print("out of chances")
            break
        if guess1 < n1:
            print("guess is low")
            guess1 = int(input("Enter an integer from 1 to 99: "))
        elif guess > n1:
            print ("guess is high")
            guess1 = int(input("Enter an integer from 1 to 99: "))
        else:
            print("you guessed it")
            break
    retry=input("would you like to play again? (please choose either 'yes' or 'no')")
    if retry == "yes":
        main()
    else:
        print("Okay. have a nice day! :D ")
main()

A: to achieve this I would use a while loop and a variable to detect which players turn it is. Like this:
import random

random_number = random.randint(1, 99)

player_chances = 5
current_player = 1

while player_chances > 0:
    if current_player == 1:
        guess = int(input("Player 1 please enter an integer from 1 to 99, {} chances left. ".format(player_chances)))

        player_chances -= 1
        current_player = 2

        if guess < random_number:
            print("->guess is too low")
        elif guess > random_number:
            print("->guess is too high")
        else:
            print("CONGRATULATIONS! You guessed it! Player 1 wins!")
            break

    else:
        guess = int(input("Player 2 please enter an integer from 1 to 99, {} chances left. ".format(player_chances)))

        player_chances -= 1
        current_player = 1

        if guess < random_number:
            print("->guess is too low")
        elif guess > random_number:
            print("->guess is too high")
        else:
            print("CONGRATULATIONS! You guessed it! Player 1 wins!")
            break

print("####")
print("Out of chances! The number was {}.".format(random_number))
print("####")

A: To make this possible in an efficient way I would have created a player class as such:
class Player:
    def __init__(self,name):
        self.name = name
        self.getNumberOfTrys = 0
        self.guess = 0

    def getNumberOfTrys(self):
        return self.getNumberOfTrys

    def getPlayerName(self):
        return self.name

    def play(self):
        try:
            self.guess = int(input("Enter an integer from 1 to 99: "))
            self.getNumberOfTrys+=1
            return self.guess
        except Exception as error:
            print(error)
            return None

this class is responsible to create the player with the number of tries,his guess and his name.
the logic will be going through the list of players (you can add as much as you want) and perform the game logic as follows:
import random
p1 = Player("Player 1")
p2 = Player("Player 2")
players = []
players.append(p1)
players.append(p2)
n1 = random.randint(1, 99)
NUMBER_OF_TRIES = 5
print(n1)
while players:
    for player in players:
        print(player.getPlayerName() + " turn, you have " + str(NUMBER_OF_TRIES - player.getNumberOfTries) + " turns left")
        guess = player.play()
        if guess < n1:
            print("guess is low")
        elif guess > n1:
            print ("guess is high")
        else:
            print(player.getPlayerName()," you guessed it")
            players.clear()
            break
        if player.getNumberOfTries == NUMBER_OF_TRIES:
            print(player.getPlayerName(), " out of chances")
            players.remove(player)

Basically, create a list of players then go through each one and apply the game logic (getting input, comparing and checking number of tries)
after a player loses, we should remove him from the list and if a player wins we can clear the list and thus exiting the game.
Here is the full code:
class Player:
    def __init__(self,name):
        self.name = name
        self.getNumberOfTries = 0
        self.guess = 0

    def getNumberOfTries(self):
        return self.getNumberOfTries

    def getPlayerName(self):
        return self.name

    def play(self):
        try:
            self.guess = int(input("Enter an integer from 1 to 99: "))
            self.getNumberOfTries+=1
            return self.guess
        except Exception as error:
            print(error)
            return None

import random
p1 = Player("Player 1")
p2 = Player("Player 2")
players = []
players.append(p1) #addding player
players.append(p2)
n1 = random.randint(1, 99)
NUMBER_OF_TRIES = 5
print(n1) #for debug
while players:
    for player in players:
        print(player.getPlayerName() + " turn, you have " + str(NUMBER_OF_TRIES - player.getNumberOfTries) + " turns left")
        guess = player.play()
        if guess < n1:
            print("guess is low")
        elif guess > n1:
            print ("guess is high")
        else:
            print(player.getPlayerName()," you guessed it")
            players.clear() # exit game
            break #exit loop
        if player.getNumberOfTries == NUMBER_OF_TRIES:
            print(player.getPlayerName(), " out of chances")
            players.remove(player)

Hope I got your question right, and excuse me If there is any errors or typos, I just created something fast that you can be inspired by. I highly suggest you get into OOP, it very simple and it can make your life much easier :)
All the best!


text:
Q: How to Call Web Service Using SOAP Request with example?     public static string CallWebService()
    {
        var _url = "xxxxx";
        var _action = "xxxx";
        XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
        HttpWebRequest webRequest = CreateWebRequest(_url, _action);
        webRequest.Credentials = new NetworkCredential("xxxx", "xxxx");
        InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
        IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
        asyncResult.AsyncWaitHandle.WaitOne();
        string soapResult;
        using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
        {
            using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
            {
                soapResult = rd.ReadToEnd();
            }
            return soapResult;
        }
    }

    private static HttpWebRequest CreateWebRequest(string url, string action)
    {
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Headers.Add("SOAPAction", action);
        webRequest.ContentType = "text/xml;charset=\"utf-8\"";
        webRequest.Accept = "text/xml";
        webRequest.Method = "POST";
        return webRequest;
    }

    private static XmlDocument CreateSoapEnvelope()
    {
        XmlDocument soapEnvelopeDocument = new XmlDocument();
        soapEnvelopeDocument.LoadXml(@"<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/1999/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/1999/XMLSchema""><SOAP-ENV:Body><HelloWorld xmlns=""http://tempuri.org/"" SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/""><int1 xsi:type=""xsd:integer"">12</int1><int2 xsi:type=""xsd:integer"">32</int2></HelloWorld></SOAP-ENV:Body></SOAP-ENV:Envelope>");
        return soapEnvelopeDocument;
    }

    private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
    {
        using (Stream stream = webRequest.GetRequestStream())
        {
            soapEnvelopeXml.Save(stream);
        }
    }

Trying to create a C# client (will be developed as a Windows service) that sends SOAP requests to a web service (and gets the results).
  I am using ASP.net with C#  using basic authentication webRequest.Credentials = new NetworkCredential("xxxx", "xxxx");


text:
Q: Issue in handling Timers I have developed an application such that it reads the Voltages from an RPS which is connected to PLC. My program should run continuously for more than 10 hours. But its getting stuck in the middle (It's working for 3 hours and it is also getting stuck within an hour). If any one have some idea please help me out where am I facing Issue.

A: check out the system power settings ... maybe the hard disk is set to sleep after 1 or 3 hours ... or maybe the systems goes on a stand by ... otherwise check the event log for errors.


text:
Q: adjust elements in html during window resizing for website So i'm Trying to convert a non responsive html page into a responsive one
and it's a pretty simple page with an image some text on top of it and an email submit field below it.
So whenever I shrink my page the email submit field just starts to go up the page. The text field resizes (like going from all words in 2 lines to 4-5 lines ). The submit field overlap on top of the text field due to it requiring more space now (going form 2 lines to 4-5 lines). How can I adjust that in CSS so that my submit field remains always below the text field
Note scroll down to see the result.

#botText2 {
    position: absolute;
    z-index: 5;
    text-align: center;
    font-size: 20px;
    margin-top: 107%;
    padding-left: 6%;
    padding-right: 6%;
    color: rgba(4,45,72,1);
}

.subfield {
    position: absolute;
    z-index: 6;
    float: left;
    font-size: 20px;
    margin-top: 122%;
    padding-left: 38%;
    padding-right: 6%;

}
some 2-3 lines of text
<form class="subfield" action="/signup"  method="post">
  <input type="text" id="emailInput" name="email" placeholder="Enter Your Email here">
  <input type="submit" id="inputSubmit" value="Subscribe">
</form>

A: Add margin or padding to .subfield:
.subfield {
    padding-bottom: 20% /*for example*/
}

A: Don't absolutely position your elements, or you will only be able to achieve responsiveness through media queries. Allow your document to flow naturally, only interrupting this flow when absolutely necessary.
This allows the browser to determine the sizing/positioning for best results. By using percentages as opposed to fixed values will allow for a bit more fluidity, but dependent on the parent.
You can see below by commenting out most of your positioning, the browser gives the desired results as default behavior. So my answer would simply be to understand that less can certainly be more in many cases.

#botText2 {
  /* z-index: 5; */
  text-align: center;
  font-size: 20px;
  /* margin-top: 107%; */
  /* padding-left: 6%; */
  /* padding-right: 6%; */
  color: rgba(4, 45, 72, 1);
}

.subfield {
  /* position: absolute; */
  /* z-index: 6; */
  /* float: left; */
  font-size: 20px;
  /* margin-top: 122%; */
  /* padding-left: 38%; */
  /* padding-right: 6%; */
}
some 2-3 lines of text
<form class="subfield" action="/signup" method="post">
  <input type="text" id="emailInput" name="email" placeholder="Enter Your Email here">
  <input type="submit" id="inputSubmit" value="Subscribe">
</form>


text:
Q: req.cookies returns undefined but cookies are set I am using cookie-parser in my express app. When the root page is requested I set a random number on the cookie using res.cookie(name, value) and it sets it fine (I checked on my browser console). But when I try to log req.cookie it always returns undefined.
Here's my code:
routes.js
var express = require('express')
var router = express.Router()

var movieTrailer = require('movie-trailer');

var Promise = require('bluebird');
var logs = require('log-switch');
var fs = require('fs');
//var cookieParser = require('cookie-parser');

//Setup x-ray for scraping
var Xray = require('x-ray');
var x = Xray();

var debug = false;

router.get('/', (req, res) => {
  console.log('Page requested!');
  console.log('Cookies: ', req.headers.cookies); // For some reason this returns undefined

  var scrapeMovies = function(){
    return new Promise((resolve, reject) =>{
      fs.readFile('moviesRT.json', (err,data) =>{
        var movies = JSON.parse(data);
        resolve(movies);
      });
    });
  };

scrapeMovies().then(
    movies => {
      var randomInt = Math.floor(Math.random() * movies.length);
      res.cookie('randomInt', randomInt);
      var randomMovie = movies[randomInt];
      movieTrailer(randomMovie.title, (err, url) =>{
        console.log('Requesting trailer: ', randomMovie.title);
        if(err) throw err;
        var embedUrl = url.replace('watch?v=','embed/');
        console.log('Video ID: ', url.slice(32,url.length));
        randomMovie.trailerURL = embedUrl; //Add the embed URL to the randomMovie object before rendering it
        res.render('main',randomMovie,
        (err, html) =>
        {
          if(err) throw err;
          console.log('Rendering...');
          res.send(html);
          console.log("Done!");
        });
      });
    });

});

module.exports = router;

app.js
const express = require('express');

//Define app and settings
const app = express();
const exphbs = require('express-handlebars');
var cookieParser = require('cookie-parser');
const port = 3000;

var routes = require('./routes');

var debug = true;

app.use('/', routes);
app.use(express.static('public'));
app.use(cookieParser());
//app.use(cookieParser());

//View engine
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');

app.listen(port, function () {
  console.log(`Server Starts on ${port}`);
  if(!debug) logs.disable(); //Disable logging if debug variable is false
});

A: This solved my problem:
Basically when you are sending a request to the server from client-side, make sure you add withCredentials: true. For example
{
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }),
    'withCredentials':true
  };

A: This happened to me, when I sent a PUT request from the client-side (Angular) without passing the body object.
I was doing this (second argument missing):
requestBranchEditPermission() {
  return this.http.put<IPutProfile>(`${this.api}/some-endpoint`, this.options).toPromise();
}

instead of this:
requestBranchEditPermission() {
  return this.http.put<IPutProfile>(`${this.api}/some-endpoint`, {}, this.options).toPromise();
}

A: You either want to check req.headers.cookie which will be set by express.
Or if you want to use the the parsed result of the cookie-parse middleware that is stored inreq.cookies then your problem is the order in which you register your routes and the middleware.
app.use('/', routes);
app.use(express.static('public'));
app.use(cookieParser());

The parsing of the cookie is done after the routes in routes have ben executed.
You need to move the cookieParser()  before the route where you want to use it.
app.use(cookieParser());
app.use('/', routes);
app.use(express.static('public'));

A: You will need to read the cookies as req.cookies['cookie-name'] and set the cookies as resInit.cookie('cookie-name', 'cookie-value')

A: This worked for me
in the frontend add credentials : 'include' as an option to your fetch API
A more elaborated code below for a get request
fetch('url', {credentials: 'include'})
.then(res => res.json())
.then(data => //do something with the data)
.catch(err => console.log(err.message));


text:
Q: Can the amount of "ranging" iBeacon devices affect the Ranging Quality? Short Explanation of the situation:

*

*You have one (iOS-)iBeacon device advertising its UUID ("advertising Beacon")

*You have, lets say, 10'000 Devices ranging (beacon ranging!) to see whether they are close to the (single) advertising iBeacon ("listening device")

In my unterstanding this is an unicast operation, so the "listening" Devices (App) are not affected by the amount of other listening devices.
But this is just theoretical, does anybody knows if there could be any other way of determining this without having to organise 10k Devices? Are there any limits?

A: Generally, it is true that thousands of mobile phones in the vicinity of  one beacon are not affected by one another for the reason you say.  When scanning, the phones' Bluetooth chips are in receive only mode.
In practice, however, phones are often transmitting as well for at least two reasons:

*

*Both iOS and Android devices doing BLE scanning will transmit a scan request packet to the beacon when it is first detected, which will cause the beacon to reply with a scan response packet if it is built to do so. (Some but not all hardware beacons send a scan response.  Software beacons typically do.)
See more here

*Phones sometimes run other apps that themselves may be using BLE advertising in the background or even establishing BLE connections or data exchange with other phones or other BLE devices in the vicinity (e.g. a user wearing a smart watch).
The above caveats generally do not affect your use case much.  Bluetooth traffic causes collisions that will affect detections, but this only reduces detection rates, it does not stop detections.  In practice, detections still happen even with many hundreds of beacons transmitting in a short range to many hundreds of phones.  I have seen this work for hundreds of conference attendees in the same room each  wearing a personal beacon transmitter.
I also set up a beacon-based indoor back system at the Consumer Electronics Show.  Thousands of people were in BLE range of transmitting beacon during keynote speeches, and many of them had the conference app that was scanning for these beacons.  While I have no stats on detection rates, it generally detected the beacons just fine.


text:
Q: Is it possible to check if a specific process is sleeping or running? I've created the following script on Ubuntu that can pause and start a specific process:
#!/bin/bash

loopProcess () {
   COUNTER=0
   while [  true ]; do
      echo $COUNTER
      sleep 1
      let COUNTER=COUNTER+1
   done
}

loopProcess &
pidLoopProcess="$!"

while [  true ]; do
   read -p "" state
   if [ "$state" == 'a'  ]; then
      echo "Process is running"
      kill -CONT "$pidLoopProcess"
   elif [ "$state" == 'b'  ]; then
      echo "Process is sleeping"
      kill -STOP "$pidLoopProcess"
   fi
done

Demonstration of how it works:

I'd like to know if it's possible to check when a specific process is running or sleeping using the command line. The pseudocode would be something like this:
if [ "$(StatePID $pidLoopProcess)" == 'sleeping'  ]; then
    ## do something
fi

I know that with this script I could just declare some global variables and use them as flags... But I want to know if there's a command line tool that does that for me. Is there? Is it possible?

A: On Linux, you can use this to get the status of a process with a given PID:
ps -o stat= $pid

That returns T when a process is stopped. So, assuming you are on a Linux system, you could do something like this:
if [ "$(ps -o stat= $pid)" = "T" ]; then
    echo stopped
else
    echo not stopped
fi

A full list of process state codes is given in man ps:
PROCESS STATE CODES
       Here are the different values that the s, stat and state output specifiers
       (header "STAT" or "S") will display to describe the state of a process:

               D    uninterruptible sleep (usually IO)
               I    Idle kernel thread
               R    running or runnable (on run queue)
               S    interruptible sleep (waiting for an event to complete)
               T    stopped by job control signal
               t    stopped by debugger during the tracing
               W    paging (not valid since the 2.6.xx kernel)
               X    dead (should never be seen)
               Z    defunct ("zombie") process, terminated but not reaped by its parent

   For BSD formats and when the stat keyword is used, additional characters may be
   displayed:

           <    high-priority (not nice to other users)
           N    low-priority (nice to other users)
           L    has pages locked into memory (for real-time and custom IO)
           s    is a session leader
           l    is multi-threaded (using CLONE_THREAD, like NPTL pthreads do)
           +    is in the foreground process group


text:
Q: How to write a HashMap to a txt file? I have a HashMap containing some data that I want to write to a file and reload the contents of the file to form the same HashMap.
HashMap is as follows:
    HashMap<Long, List<DataPoint>> hashMap = new HashMap<Long, List<DataPoint>>();

And DataPoint class is as follows:
public class DataPoint {

private int time;
private int songId;

public DataPoint(int songId, int time) {
    this.songId = songId;
    this.time = time;
}

public int getTime() {
    return time;
}

public int getSongId() {
    return songId;
}
 }

Help is much appreciated.
Thanks

A: Change DataPoint to implement java.io.Serializable and use ObjectOutputStream.writeObject /  ObjectInputStream.readObject. All Java SE collection implementations are Serializable

A: Make your data point class as serializable and after use the below code to read and write your map from a text file `    File f = new File("myfile.txt");
    HashMap> hashMap = new HashMap>();
List<DataPoint> list = new ArrayList<DataPoint>();
list.add(new DataPoint(1, 1));
list.add(new DataPoint(2, 2));
hashMap.put(1L, list);

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
oos.writeObject(hashMap);

oos.flush();
oos.close();

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
HashMap<Long, List<DataPoint>> returnedMap = (HashMap<Long, List<DataPoint>>) ois.readObject();
ois.close();
// Use returned object.
System.out.println(returnedMap.get(1L).size());`


text:
Q: Подключение эквайринг банка тинькофф v2 Ребят всем привет, столкнулся с проблемой подключения эквайринга от тиньков банка, а именно 2 версии, в документации у них висит 1 версия через cURL, просят отправлять запросы на https://securepay.tinkoff.ru/v2/Init с помощью json, в ответ должна приходить ссылка на которую человек переходит чтобы делать оплату, но ничего не приходит, тех поддержка динамит и говорит что нужно ознакомиться с документацией... перерыл всю документацию и перепроверил массивы, толку 0... бьюсь с этим 3 день, в бэкенде опыт у меня не большой, но вроде все в порядке... может кто чем подсказать, буду очень благодарен... есть документация https://oplata.tinkoff.ru/landing/develop/documentation/Init, в ней указано какой массив должен приходить на адрес, собственно он вроде как такой и идет, но что то все равно не так... собственно есть 3 файла, два испольнительных(debug.php и TinkoffMerchantAPI.php) и один куда ты вбиваешь массив и данные своего магазина (index.php)
вот собственно файлы
index.php
      <?php

     /**
      * File index.php. Demo for using TinkoffMerchantAPI library.
      *
      * PHP version 5.3
      *
      * @category Tinkoff
      * @package  Tinkoff
      * @author   Shuyskiy Sergey <s.shuyskiy@tinkoff.ru>
      * @license  http://opensource.org/licenses/MIT MIT license
      * @link     http://tinkoff.ru
      */
     function __autoload($className)
     {
         include $className.'.php';
     }
     //spl_autoload('TinkoffMerchantAPI');
     $api = new TinkoffMerchantAPI(
         '1502455205939DEMO',//'Test',
         'k2gk471x6g61qflb',//'password',
         'https://securepay.tinkoff.ru/v2/Init'
     );
     ?>
     <!doctype html>

         <meta charset="UTF-8">
         <link rel="stylesheet" href="main.css"/>
         <title>Testing Merchant API</title>

Тестирование MerchantAPI

     <?php if (true) : ?>

Метод Init:

                 <?php
                 $params = array(
                     'TerminalKey' => '1502455205939DEMO',
                     'Amount' => 100,
                     'OrderId' => '66239',//'669',
                     'Description' => '123',
                     'Language' => 'ru',
                     'DATA' => array('Email' => '@test.ru', 'Phone' => '         +78985643434'),
                     'Receipt' => array('Email' => '@test.ru', 'Phone' => '         +78985643434','Taxation' => 'usn_income',
                     'Items' => [array(
                      'Name' => 'tov1',
                      'Price' => 10000,
                      'Quantity' => 1.00,
                      'Amount' => 10000,
                      'Tax' => 'none'
                      )])
                 );
                 $params1 = json_encode($params);
                 echo $params1;
                 $api->init($params1);

                 echo 'Params:';
     //                Debug::trace($params);
                 ?>

Response: <?php echo $api->         response ?>

                 <?php if ($api->error) : ?>
                     <?php echo $api->error ?>
                 <?php else: ?>

Status: <?php echo $api->         status ?>

                         PaymentUrl:
                         <a href="<?php echo $api->paymentUrl ?>" target="_blank"         ><?php echo $api->paymentUrl ?>

PaymentId: <?php echo $api         ->paymentId ?>

                 <?php endif; ?>

     <?php endif; ?>

     <?php if (false) : ?>

Метод GetState:

                 <?php
                 $params = array(
                     'PaymentId' => '147161',
                 );
                 $api->getState($params);
                 ?>

Response: <?php echo $api->         response ?>

                 <?php if ($api->error) : ?>

<?php echo $api->error ?>

                 <?php else: ?>

Status: <?php echo $api->         status ?>

PaymentId: <?php echo $api         ->paymentId ?>

OrderId: <?php echo $api->         orderId ?>

                 <?php endif; ?>

     <?php endif; ?>

     <?php if (false) : ?>

Метод Confirm:

                 <?php
                 $params = array(
                     'PaymentId' => '147161',
                 );
                 $api->confirm($params);
                 //    echo 'Params:';
                 //    Debug::trace($params);
                 ?>

Response: <?php echo $api->         response ?>

                 <?php if ($api->error) : ?>
                     <?php echo $api->error ?>
                 <?php else: ?>

Status: <?php echo $api->         status ?>

PaymentId: <?php echo $api         ->paymentId ?>

                 <?php endif; ?>

     <?php endif; ?>

     <?php if (false) : ?>

Метод Resend

Response: <?php echo $api->         resend() ?>

Count: <?php echo $api->Count          ?>

     <?php endif; ?>

     <?php if (false) : ?>

Метод AddCustomer

                 <?php
                 $params = array(
                     'CustomerKey' => '4',
                 );
                 $api->addCustomer($params);
                 ?>

Response: <?php echo $api->         response ?>

                 <?php if ($api->error) : ?>

<?php echo $api->error ?>

                 <?php else: ?>

CustomerKey: <?php echo $         api->customerKey ?>

                 <?php endif; ?>

     <?php endif; ?>

     <?php if (false) : ?>

Метод GetCustomer

                 <?php
                 $params = array(
                     'CustomerKey' => '4',
                 );
                 $api->getCustomer($params);
                 ?>

Response: <?php echo $api->         response ?>

                 <?php if ($api->error) : ?>

<?php echo $api->error ?>

                 <?php else: ?>

CustomerKey: <?php echo $         api->customerKey ?>

                 <?php endif; ?>

     <?php endif; ?>

     <?php if (false) : ?>

Метод RemoveCustomer

                 <?php
                 $params = array(
                     'CustomerKey' => '4',
                 );
                 $api->removeCustomer($params);
                 ?>

Response: <?php echo $api->         response ?>

                 <?php if ($api->error) : ?>

<?php echo $api->error ?>

                 <?php else: ?>

CustomerKey: <?php echo $         api->customerKey ?>

                 <?php endif; ?>

     <?php endif; ?>

     <?php if (true) : ?>

Метод GetCardList

                 <?php
                 $params = array(
                     'CustomerKey' => '5',
                 );
                 $api->getCardList($params);
                 ?>

Response: <?php echo $api->         response ?>

                 <?php if ($api->error) : ?>

<?php echo $api->error ?>

                 <?php else: ?>

CustomerKey: <?php echo $         api->customerKey ?>

                 <?php endif; ?>

     <?php endif; ?>

     <?php if (true) : ?>

Метод RemoveCard

                 <?php
                 $params = array(
                     'CardId' => '10804',
                     'CustomerKey' => '5',
                 );
                 $api->removeCard($params);
                 ?>

Response: <?php echo $api->         response ?>

                 <?php if ($api->error) : ?>

<?php echo $api->error ?>

                 <?php else: ?>

CustomerKey: <?php echo $         api->customerKey ?>

                 <?php endif; ?>

     <?php endif; ?>

TinkoffMerchantAPI.php - внизу идет отправка через cURL
     <?php

     /**
      * File TinkoffMerchantAPI
      *
      * PHP version 5.3
      *
      * @category Tinkoff
      * @package  Tinkoff
      * @author   Shuyskiy Sergey <s.shuyskiy@tinkoff.ru>
      * @license  http://opensource.org/licenses/MIT MIT license
      * @link     http://tinkoff.ru
      */
     //namespace Tinkoff;

     //use HttpException;

     /**
      * Class TinkoffMerchantAPI
      *
      * @category Tinkoff
      * @package  Tinkoff
      * @author   Shuyskiy Sergey <s.shuyskiy@tinkoff.ru>
      * @license  http://opensource.org/licenses/MIT MIT license
      * @link     http://tinkoff.ru
      * @property integer     orderId
      * @property integer     Count
      * @property bool|string error
      * @property bool|string response
      * @property bool|string customerKey
      * @property bool|string status
      * @property bool|string paymentUrl
      * @property bool|string paymentId
      */
     class TinkoffMerchantAPI
     {
         private $_api_url;
         private $_terminalKey;
         private $_secretKey;
         private $_paymentId;
         private $_status;
         private $_error;
         private $_response;
         private $_paymentUrl;

         /**
          * Constructor
          *
          * @param string $terminalKey Your Terminal name
          * @param string $secretKey   Secret key for terminal
          * @param string $api_url     Url for API
          */
         public function __construct($terminalKey, $secretKey, $api_url)
         {
             $this->_api_url = $api_url;
             $this->_terminalKey = $terminalKey;
             $this->_secretKey = $secretKey;
         }

         /**
          * Get class property or json key value
          *
          * @param mixed $name Name for property or json key
          *
          * @return bool|string
          */
         public function __get($name)
         {
             switch ($name) {
             case 'paymentId':
                 return $this->_paymentId;
             case 'status':
                 return $this->_status;
             case 'error':
                 return $this->_error;
             case 'paymentUrl':
                 return $this->_paymentUrl;
             case 'response':
                 return htmlentities($this->_response);
             default:
                 if ($this->_response) {
                     if ($json = json_decode($this->_response, true)) {
                         foreach ($json as $key => $value) {
                             if (strtolower($name) == strtolower($key)) {
                                 return $json[$key];
                             }
                         }
                     }
                 }

                 return false;
             }
         }

         /**
          * Initialize the payment
          *
          * @param mixed $args mixed You could use associative array or url          params string
          *
          * @return bool
          */
         public function init($args)
         {
             return $this->buildQuery('Init', $args);
         }

         /**
          * Get state of payment
          *
          * @param mixed $args Can be associative array or string
          *
          * @return mixed
          */
         public function getState($args)
         {
             return $this->buildQuery('GetState', $args);
         }

         /**
          * Confirm 2-staged payment
          *
          * @param mixed $args Can be associative array or string
          *
          * @return mixed
          */
         public function confirm($args)
         {
             return $this->buildQuery('Confirm', $args);
         }

         /**
          * Performs recursive (re) payment - direct debiting of funds from the
          * account of the Buyer's credit card.
          *
          * @param mixed $args Can be associative array or string
          *
          * @return mixed
          */
         public function charge($args)
         {
             return $this->buildQuery('Charge', $args);
         }

         /**
          * Registers in the terminal buyer Seller. (Init do it automatically)
          *
          * @param mixed $args Can be associative array or string
          *
          * @return mixed
          */
         public function addCustomer($args)
         {
             return $this->buildQuery('AddCustomer', $args);
         }

         /**
          * Returns the data stored for the terminal buyer Seller.
          *
          * @param mixed $args Can be associative array or string
          *
          * @return mixed
          */
         public function getCustomer($args)
         {
             return $this->buildQuery('GetCustomer', $args);
         }

         /**
          * Deletes the data of the buyer.
          *
          * @param mixed $args Can be associative array or string
          *
          * @return mixed
          */
         public function removeCustomer($args)
         {
             return $this->buildQuery('RemoveCustomer', $args);
         }

         /**
          * Returns a list of bounded card from the buyer.
          *
          * @param mixed $args Can be associative array or string
          *
          * @return mixed
          */
         public function getCardList($args)
         {
             return $this->buildQuery('GetCardList', $args);
         }

         /**
          * Removes the customer's bounded card.
          *
          * @param mixed $args Can be associative array or string
          *
          * @return mixed
          */
         public function removeCard($args)
         {
             return $this->buildQuery('RemoveCard', $args);
         }

         /**
          * The method is designed to send all unsent notification
          *
          * @return mixed
          */
         public function resend()
         {
             return $this->buildQuery('Resend', array());
         }

         /**
          * Builds a query string and call sendRequest method.
          * Could be used to custom API call method.
          *
          * @param string $path API method name
          * @param mixed  $args query params
          *
          * @return mixed
          * @throws HttpException
          */
         public function buildQuery($path, $args)
         {
             $url = $this->_api_url;
             if (is_array($args)) {
                 if (! array_key_exists('TerminalKey', $args)) {
                     $args['TerminalKey'] = $this->_terminalKey;
                 }
                 if (! array_key_exists('Token', $args)) {
                     $args['Token'] = $this->_genToken($args);
                 }
             }
             $url = $this->_combineUrl($url, $path);

             return $this->_sendRequest($url, $args);
         }

         /**
          * Generates token
          *
          * @param array $args array of query params
          *
          * @return string
          */
         private function _genToken($args)
         {
             $token = '';
             $args['Password'] = $this->_secretKey;
             ksort($args);
             foreach ($args as $arg) {
                 $token .= $arg;
             }
             $token = hash('sha256', $token);

             return $token;
         }

         /**
          * Combines parts of URL. Simply gets all parameters and puts '/'          between
          *
          * @return string
          */
         private function _combineUrl()
         {
             $args = func_get_args();
             $url = '';
             foreach ($args as $arg) {
                 if (is_string($arg)) {
                     if ($arg[strlen($arg) - 1] !== '/') {
                         $arg .= '/';
                     }
                     $url .= $arg;

                 } else {
                     continue;
                 }
             }

             return $url;

         }

         /**
          * Main method. Call API with params
          *
          * @param string $api_url API Url
          * @param array  $args    API params
          *
          * @return mixed
          * @throws HttpException
          */
         private function _sendRequest($api_url, $args)
         {

             $this->_error = '';
             //todo add string $args support
             //$proxy = 'http://192.168.5.22:8080';
             //$proxyAuth = '';
             if (is_array($args)) {
                 $args = http_build_query($args);

             }
             Debug::trace($args);

             if ($curl = curl_init()) {
                 curl_setopt($curl, CURLOPT_URL, $api_url);
                 curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type:          application/json; charset=UTF-8"));
                 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
                 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                 curl_setopt($curl, CURLOPT_POST, 1);
                 curl_setopt($curl, CURLOPT_POSTFIELDS, $args);

                 $out = curl_exec($curl);
                 var_dump($out);

                 $this->_response = $out;
                 $json = json_decode($out);

                 if ($json) {
                     if (@$json->ErrorCode !== "0") {
                         $this->_error = @$json->Details;
                     } else {
                         $this->_paymentUrl = @$json->PaymentURL;
                         $this->_paymentId = @$json->PaymentId;
                         $this->_status = @$json->Status;
                     }
                 }

                 curl_close($curl);

                 return $out;

             } else {
                 throw new HttpException(
                     'Can not create connection to ' . $api_url . ' with args '
                     . $args, 404
                 );
             }
         }
     }

и Debug.php
    <?php

    class Debug {
        private static $logfile = 'log.txt';
        public static function trace($arg = null, $die = false){
            if (!$arg) $arg = '';
            $arg = print_r($arg, true);
            echo '
' . $arg . '
';
            if ($die) die();
        }

        public static function log($arg = null, $die = false)
        {
            if (!$arg) return false;
            if ( ! is_string($arg)) {
                $arg = print_r($arg, true);
            }
            file_put_contents(self::$logfile, $arg);
            if ($die) die();
            return true;
        }
    }

A: index.php:
Отправка на https://securepay.tinkoff.ru/v2/
JSON-конвертация: $api->Init(json_encode($params));

A: Просто используйте PHP Class - https://neatek.ru/php-class-tinkoff-back-payment

*

*Создаете файл tinkoff.params.php, желательно подключить базу через PDO.
<?php
use NeatekTinkoff\NeatekTinkoff\NeatekTinkoff;
require_once 'tinkoff.class.php';
$tinkoff = new NeatekTinkoff(
    array(
        array(
            'TerminalKey' => '', // Терминал
            'Password'    => '', // Пароль
        ),
        array(
            // Подключение к БД через PDO
            'db_name' => '',
            'db_host' => '',
            'db_user' => '',
            'db_pass' => '',
        ),
    )
);

*Создаете index.php для перекидывания на платёж, только уберите SetRecurrent() если не нужны рекуррентные платежи.
<?php
require_once 'tinkoff.params.php';
$tinkoff->AddMainInfo(
    array(
        'OrderId'     => 1, // Не будет работать при подключении к БД, будет автоматически ставиться свой номер заказа из базы данных, рекомендуется всегда оставлять значение = 1 при использовании PDO DB
        'Description' => 'Описание заказа до 250 символов', // Описание заказа
        'Language'    => 'ru', // Язык интерфейса Тинькофф
    )
);
$tinkoff->SetRecurrent(); // Указать что рекуррентный платёж, можно не указывать
$tinkoff->AddItem(
    array(
        'Name'     => 'Название товара 128 символов', // Максимум 128 символов
        'Price'    => 100, // В копейках
        "Quantity" => (float) 1.00, // Вес или количество
        "Tax"      => "none", // В чеке НДС
    )
);
$tinkoff->SetOrderEmail('neatek@icloud.com'); // Обязательно указать емайл
//$tinkoff->SetOrderMobile('+79999999999'); // Установить мобильный телефон
$tinkoff->SetTaxation('usn_income'); // Тип налогообложения
//$tinkoff->DeleteItem(0); // Можно удалить товар по индексу
$tinkoff->Init(); // Инициализация заказа, и запись в БД если прописаны настройки
$tinkoff->doRedirect(); // Переадресация на оплату заказа
Далее пользователь оплачивает заказ, и после чего идёт от банка уведомление на наш скрипт, который ниже об успешном платеже.

*Обработка нотификаций (уведомлений)
<?php
require_once 'tinkoff.params.php';
$tinkoff->getResultResponse(); // Ответ на нотификации

*Рекуррентные платежи, можете указать что угодно здесь.
<?php
require_once 'tinkoff.params.php';
$recurrents = $tinkoff->getLatestForRecurrent();
if (!empty($recurrents)) {
    foreach ($recurrents as $column => $client) {
        /**
         * Params for Init *
         */
        $params = array(
            // Сумма всех Items.Amount
             'Amount'      => (string)$client['Amount'],
            // Номер заказа берется из DB
             'OrderId'     => (string)$client['order_id'],
            // из DB
             'Description' => $client['Description'],
        );
        $params['DATA'] = (object) array(
            'Email' => $client['Email'],
        );
        $params['Receipt'] = (object) array(
            // Береться из DB
             'Email'    => $client['Email'],
            // Налогообложение
             'Taxation' => 'usn_income',
            // С предметами в чеке, можно добавить что вам нужно
             'Items'    => array(
                (object) array(
                    'Name'     => 'Описание товара 128 символов',
                    'Price'    => $client['Amount'],
                    "Quantity" => 1.00,
                    // Amount = Price * Quantity
                    "Amount"   => $client['Amount'],
                    "Tax"      => "none",
                ),
            ),
        );

        /**
         * Charge - повторый платёж *
         */
        $tinkoff->Charge($tinkoff->Init($params, '[Automatic]'), $client);
    }
}


text:
Q: Difference between scatter-plot and a dotplot This question is now haunting me like anything, I am unable to understand , what is the difference between scatterplot and a dotplot? Is there any difference at all? or often people use them interchangeably. I have asked this question to several people , some say its same but some other say its different but no one able to explain any difference ? Sorry if this is a newbie question, but some one can explain this to me , I think that would be great help.
Thanks

A: A dot plot is just a bar chart that uses dots to represent individual quanta.
So if you wanted to plot the number of pets per household, you might have 10 households with 0 pets, 20 with 1 pet, 12 with 2 pets, etc. Over zero, you'd draw 10 dots; over one, you'd draw 20 dots, etc.
A scatter plot puts a point representing a single realization of a tuple of data. For example, if you measured people's height and weight, you could create a scatter plot where one axis represented height and one represented weight. Each point on a scatter plot represents one person.


text:
Q: Circuit-break L2 cache in Hibernate in case of redis connection issues I am using redisson-hibernate as Hibernate 2nd level Cache provider. If redis server becomes unavailable, while the application is running, the whole application goes down. I am trying to find a way to circuit-break the L2 cache in such a scenario.
In case redis is unavailable, hibernate should work as if L2 is disabled, and there should be some mechanism (or subsequent requests), which should check for redis availability after a specified amount of L2, and re-enables L2. Is there already a way to do this?
If not, how can I build such a mechanism? I could try running a quartz job, which checks for redis connectivity, kills and restarts the application by modifying the app config. But this approach is complicated and not very clean. Please suggest.

A: I had tried the scenario which you have mentioned in a SPRING BOOT application and all the requests (HTTP) started to pile up when I shutdown Redis. But, when I re-start Redis, the application is able to reconnect and processes as usual.
Hibernate & Redis connections load up based on the configuration available in the "application.properties" file.
spring.jpa.properties.hibernate.cache.auto_evict_collection_cache=false
spring.jpa.properties.hibernate.generate_statistics=false
spring.jpa.properties.hibernate.cache.use_second_level_cache=true
spring.jpa.properties.hibernate.cache.use_query_cache=true
spring.jpa.properties.hibernate.javax.cache.missing_cache_strategy=create
spring.jpa.properties.hibernate.cache.redisson.config=redisson.json
spring.jpa.properties.javax.persistence.sharedCache.mode=ENABLE_SELECTIVE

I couldn't find any parameters w.r.t Hibernate / Spring JPA in Hibernate or Spring docs which could automatically detect when L2 is down.
I am also eagerly awaiting for such mechanisms in Hibernate / Spring JPA as this scenario is valid test case which will we surely face mostly in LOAD/PROD environments.

A: A bit late here but I also face same sort of problems with hibernate and l2 cache management / eviction with any sub jcache api (caffeine, ehcache, hazelcast, infinispan, redisson....).
we have a very small database with 99,999% read and maybe once or twice a week one write.
we cache everything (entitis, queries, collections).
I tried many ways to make hibernate l2 cache auto evict entries :

*

*based on sub cache configuration size or time based eviction

*based on a custom scheduled task which tries to evict jpa cache, based on hibernate interceptors to evict chirurgically entities at max scheduled times

*tried with debezium to evict the cache on database level update detection....

I always face from time to time a failed to load entity with id xxx...
Tried many configurations, many java annotations (jpa or hibernate level), still struggling to find a working way of expiring the cache and make jpa/hibernate fallback to request directly to the database....
The only way I was able to barely fix this was by disabling hibernate query cache and create a spring cache for this (for every JpaRepo methods with aspect and custom implementation _(--)'/ )...
This with Debezium to evict only updated entities (from inside or outside the app scope) were the only working scenarios.
=> my cached queries and entities get quickly retrieved when in cache (spring and hibernate) and chirurgical eviction of entities in the debezium callback method make any databases modification immediately reflected in the application (all servers listen to debezium , get notified and expire their local cache).
This is frustrating as this is certainly a really common scenario in prod environment...


text:
Q: UITableView editing - select cell without cell highlighting I have images in my tableView cells, so I have set the cell selectionStyle to None, in order to avoid the cells highlighting when they're selected.
I'm now trying to implement editing into the tableView, allowing users to select multiple cells, filling in the checkmark cirle on the left of the cells. However, this doesn't seem to work with a selectionStyle of None - the circle just remains unfilled.
Is there any way to solve this?
Thanks?

A: If you can't select the cells directly you can place a uibutton in the cell and recognize in which cell the button that was tapped was.To do that you can set the button tag to equal the indexPath.row inside the cellForRowAtIndexPath method.
The code below prints the correct row number. Hope this helps.
  class MyTableViewCell: UITableViewCell {

        @IBOutlet weak var onButton: UIButton!

    }

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func buttonClicked(sender:UIButton) {

        let buttonRow = sender.tag
        print(buttonRow)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! MyTableViewCell

        cell.onButton.tag = indexPath.row
        cell.onButton.addTarget(self, action: #selector(ViewController.buttonClicked(sender:)), for: .touchUpInside)
        return cell
    }}


text:
Q: Any way to customize Chrome or Firefox Speed Dial thumbs? For a fun project, I've been implementing a small thumbnail page on a website that provides a specially catered view for the small site previews on New Tab pages. The end goal being to present the relevant information to the user before they ever need to visit the site. (Example: a weather site frequently visited, having a thumbnail page showing today's weather, so that the user can see the relevant information at a glance).

Opera this is by detecting
X-Purpose: preview

Likewise, Safari uses the same header, but requires additional JS to maintain a consistent thumbnail.
//On primary page
if (window.navigator.loadPurpose === 'preview') { /* go to thumbnail page */ }

//On thumbnail page
if (window.navigator.loadPurpose !== 'preview') { /* return to main page */ }

I'm curious if it's possible to duplicate this effect in Chrome or Firefox (the new speed dial available in the Aurora builds)?
Note: The X-Purpose: preview header in Chrome about 2 releases ago was a bug that was intended to be X-Purpose: instant and does not serve this purpose.

A: As far as I can tell, both Chrome and Firefox Speed-dial thumbnails are only populated when you visit a page - i.e. they're taken from the normal browsing context, with normal headers, rather than being independently queries in their own right.
You can test this a number of ways - I haven't spent long testing it, and you may have different version(s) of Firefox/Chrome than I do so you may see different results.

*

*In Chrome - pin a tab or two in Speed-dial and then empty your browser history. The thumbnails should disappear until you re-visit the pinned page.

*In Firefox - the above works, but you can also try out thumbnail generation directly using the moz-page-thumb:// URL protocol:
moz-page-thumb://thumbnail?url=http%3A%2F%2Fstackoverflow.com%2Fq%2F10369905%2F210865"
(please do test in whatever versions you're running as I'm curious about this question too - my research sofar is disappointing, but possibly in future ...)
Other references:

*

*Original bugzilla entry for adding thumbnails to FF Speed-dial

*Another bugzilla entry on fixing thumbnail protocol security issues

*Related Super User question

A: Try using the speed Dial addon on Firefox, works really well.
It has features like bookmarks back-up and you can add a large number of bookmarks customizing each bookmark-tab.
link to speed dial for firefox
link to speed dial for chrome


text:
Q: powershell - delete n lines after match in file my test file looks like this:
aa
xxxxx test1 vraarxxxerv
remove1
remove2
remove3
must stay 1
aaaaaa
aaa
aaaaa
aaaaaaaa
aa
test2
remove1 efsd
remove2 esf
remove3 gr rgsv
must stay 2
aaaaaa
aaa
aaaaa
aaaaaaaa
aa
xx test3
remove1 efsd
remove2 esf
remove3 gr rgsv
must stay 3
aaaaaa
aaa
aaaaa
aaaaaaaa
aa

idea is simple - look for lines contains string test1, test2 and test3 and remove 3 next lines
my code is
 $search =
'test1',
'test2',
'test3'

foreach ($item in $search) {
echo "."
$linenumber= Get-Content .\test.txt | select-string $item
$linenumber.LineNumber

Get-Content .\test.txt | Where-Object {
    -not ($_.ReadCount -ge $linenumber.LineNumber -and $_.ReadCount -le $linenumber.LineNumber+3)
} | Out-File -FilePath .\test.txt

}

but it just create empty test.txt file - what am I doing wrong..? I would like to have file where remove1 remove2 and remove3 lines are not existing - they are always different so I cannot look for "remove" text, they are just an examples. must stay 1,2,3 lines are just to be sure that it haven't deleted more lines as I need...

A: Try this:
$lines = Get-Content .\test.txt
$rem = @()
@("test1","test2","test3") | Foreach {
  $rem += $lines[(($lines | Select-String -Pattern "$_").LineNumber)..(($lines | Select-String -Pattern "$_").LineNumber+2)]
}
Compare-Object $lines $rem | Select-Object -ExpandProperty InputObject | Set-Content .\test.txt

A: You could use a switch statement and implement a little state machine to skip the lines you'd like to remove
    $state=0
    switch -File test.txt -Regex ($_) {
        'test[123]' {
            $state = 1
            Write-Output $_
            Continue
        }
        default {
            if ($state -eq 0) {Write-Output $_}
            elseif ($state -lt 4) {$state++}
            else {$state = 0; Write-Output $_}
        }
    }

Example
$state=0
@'
aa
xxxxx test1 vraarxxxerv
remove1
remove2
remove3
must stay 1
aaaaaa
aaa
aaaaa
aaaaaaaa
aa
test2
remove1 efsd
remove2 esf
remove3 gr rgsv
must stay 2
aaaaaa
aaa
aaaaa
aaaaaaaa
aa
xx test3
remove1 efsd
remove2 esf
remove3 gr rgsv
must stay 3
aaaaaa
aaa
aaaaa
aaaaaaaa
aa
'@ -split "`r`n" | % {
    switch -Regex ($_) {
        'test[123]' {
            $state = 1
            Write-Output $_
            Continue
        }
        default {
            if ($state -eq 0) {Write-Output $_}
            elseif ($state -lt 4) {$state++}
            else {$state = 0; Write-Output $_}
        }
    }
}

returns
aa
xxxxx test1 vraarxxxerv
must stay 1
aaaaaa
aaa
aaaaa
aaaaaaaa
aa
test2
must stay 2
aaaaaa
aaa
aaaaa
aaaaaaaa
aa
xx test3
must stay 3
aaaaaa
aaa
aaaaa
aaaaaaaa
aa


text:
Q: Compactness argument for countable subgraphs and beyond I am interested whether there exists a certain generalization of so-called compactness argument in graph theory.
First let me define what I mean by "compactness argument"
Let $G = (V, E)$ be an infinite graph. Let $F$ be the collection of all it's $k$-colorings (we consider any colorings here, not just proper colorings). Now we want to specify for each finite subgraph of $G$ a collection of colorings we call "interesting colorings". Let $F'(G')$ be a collection of interesting colorings of a finite $G' \subset G$. We demand from $F'$ to have two properties

*

*$F'(G')$ is non empty for any $G'$, in other words every finite subgraph admits an interesting coloring

*If $G'' \subset G'$ and $f \in G'$ then $f$ restricted to $G''$ is in $F'(G')$.

If we have such a setting then one can prove that there exists a coloring $f$ of the whole $G$ such that for any finite subgraph $G'$, $f$ restricted to $G'$ is in $F'(G')$.
The proof of this statement can be done using Tychonoff's theorem using compactness of space $\{1, \ldots, k\}^{|G|}$ I am interested in a question whether a similar theorem remains true if we replace the word "finite" with the word "countable" in the theorem's text.


text:
Q: How to just get plain text and line breaks using XSL With this input
<?xml version="1.0" encoding="UTF-8"?> <data>
This is a senstence
this is another sentence

my H2

some paragraph

another paragraph

 </data>

I need to apply XSL style sheet to obtain just the plain text, honor the line breaks, and remove preceeding white space. So, after searching online for a few samples, I tried this, but it does not work for me. Sorry, Im not familiar with XSL and thought I'd ask.
Attempted XSL, but it does not work. Any ideas?
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" encoding="UTF-8"/>
    <xsl:strip-space elements="*" />

        <xsl:template match ="@* | node()">
            <xsl:copy>
                <xsl:apply-templates select="@* | node()"/>
            </xsl:copy>
        </xsl:template>

        <xsl:template match="h1|h2">
            <xsl:text>
            </xsl:text>
            <xsl:copy>
                <xsl:apply-templates select="@* | node()"/>
            </xsl:copy>
        </xsl:template>
</xsl:stylesheet>

This is the output after applying XSL.
As you can see, its all one line, not carriage returns.
This is a sentence this is another sentence m H2some paragraphTanother paragraph

This is the output I'd like to get. Text within H1|H2|H3 should have a line break before and after.
This is a sentence
this is another sentence

my H2

some paragraph
another paragraph

A: You need a xml:space="preserve" attribute to maintain the carriage return within xml:text, and you need a carriage return before and after the content of h1 and h2 tags:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" encoding="UTF-8"/>
  <xsl:strip-space elements="*" />

  <xsl:template match ="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="h1|h2">
    <xsl:text xml:space="preserve">
</xsl:text>
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
    <xsl:text xml:space="preserve">
</xsl:text>
  </xsl:template>
</xsl:stylesheet>

The initial text (This is a senstence, this is another sentence) is output correctly on separate lines in my case (using Visual Studio 2012 to execute the XSLT).
You write that only h tags should have the carriage return added - in your sample some paragraph and another paragraph are in p tags, so no carriage returns are added and they are output on the same line.


text:
Q: Is it possible to publish a visual studio c# project with ClickOnce, in just one .exe? Is it possible to publish a visual studio c# project with ClickOnce, in just one .exe?
I could not find a way to do it. My project has additional files it uses
like: it calls external exe, it links to dlls, etc. And all these files I want
to somehow embed in on .exe, rather than have an exe + additional files next to it.
Edit: the image explains even better what I need.

A: Yes, you can add external dlls, resources, exe, and so on in your ClickOnce setup. Look at these photos. Sorry for the language.

If you want to publish it on IIS, you will need a host. Those files (application files,setup.exe and so on) will be stored in IIS. You only need to provide a 'publish.htm' or 'setup.exe' to users. 'publish.htm'/'setup.exe' will connect to your IIS. And if you use ClickOnce, your application will be updated more easily.
Otherwise, you just need VSInstaller in VS2010 or InstallShield Limited Edition in VS2012/2013. It will produce one .exe file.

A: You can add external exe in your installation. In your Setup and Deployment wizard Select the Application Folder and choose Add File then select your exe.
For prerequisites read this article.


text:
Q: Problem understanding Pickups & delivery array using OR-TOOLS So, I've been trying to understand what is the problem with the following experiment, but wasn't able to find the issue..
So, below is the code I am using (note that there is a duplicate node, as that node is both a pick and a delivery node):
"""Capacited Vehicles Routing Problem (CVRP)."""

from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp

def create_data_model():
    """Stores the data for the problem."""
    data = {}
    data['distance_matrix'] = [
        [  0, 220, 460, 460, 700, 280, 610],
        [220,   0, 570, 570, 670, 500, 500],
        [460, 570,   0,   0, 350, 550, 450],
        [460, 570,   0,   0, 350, 550, 450],
        [700, 670, 350, 350,   0, 850, 250],
        [280, 500, 550, 550, 850,   0, 830],
        [610, 500, 450, 450, 250, 830,   0]
    ]
    data['pickups_deliveries'] = [
        [1, 2], #1,2
        [3, 6], #3,4
        [4, 5], #5,6
    ]
    data['demands'] = [
        0,  # departs empty
        1,  # load in 1
        -1, # unload in 2
        1,  # load in 3 (duplicate of 2)
        1,  # load in 4
        -1, # unload in 5
        -1] # unload in 5
    data['vehicle_capacities'] = [1]
    data['num_vehicles'] = 1
    data['depot'] = 0
    return data

def print_solution(data, manager, routing, solution):
    """Prints solution on console."""
    print(f'Objective: {solution.ObjectiveValue()}')
    total_distance = 0
    total_load = 0
    for vehicle_id in range(data['num_vehicles']):
        index = routing.Start(vehicle_id)
        plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
        route_distance = 0
        route_load = 0
        while not routing.IsEnd(index):
            node_index = manager.IndexToNode(index)
            route_load += data['demands'][node_index]
            plan_output += ' {0} Load({1}) -> '.format(node_index, route_load)
            previous_index = index
            index = solution.Value(routing.NextVar(index))
            route_distance += routing.GetArcCostForVehicle(
                previous_index, index, vehicle_id)
        plan_output += ' {0} Load({1})\n'.format(manager.IndexToNode(index),
            route_load)
        plan_output += 'Distance of the route: {}m\n'.format(route_distance)
        plan_output += 'Load of the route: {}\n'.format(route_load)
        print(plan_output)
        total_distance += route_distance
        total_load += route_load
    print('Total distance of all routes: {}m'.format(total_distance))
    print('Total load of all routes: {}'.format(total_load))

def main():
    """Solve the CVRP problem."""
    # Instantiate the data problem.
    data = create_data_model()

    # Create the routing index manager.
    manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
                                           data['num_vehicles'], data['depot'])

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)

    # Create and register a transit callback.
    def distance_callback(from_index, to_index):
        """Returns the distance between the two nodes."""
        # Convert from routing variable Index to distance matrix NodeIndex.
        from_node = manager.IndexToNode(from_index)
        to_node = manager.IndexToNode(to_index)
        return data['distance_matrix'][from_node][to_node]

    transit_callback_index = routing.RegisterTransitCallback(distance_callback)

    # Define cost of each arc.
    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

    # Add Capacity constraint.
    def demand_callback(from_index):
        """Returns the demand of the node."""
        # Convert from routing variable Index to demands NodeIndex.
        from_node = manager.IndexToNode(from_index)
        return data['demands'][from_node]

    demand_callback_index = routing.RegisterUnaryTransitCallback(demand_callback)

    routing.AddDimensionWithVehicleCapacity(
        demand_callback_index,
        0,  # null capacity slack
        data['vehicle_capacities'],  # vehicle maximum capacities
        True,  # start cumul to zero
        'Capacity')

    # Add Distance constraint.
    dimension_name = 'Distance'
    routing.AddDimension(
        transit_callback_index,
        0,  # no slack
        3000,  # vehicle maximum travel distance
        True,  # start cumul to zero
        dimension_name)
    distance_dimension = routing.GetDimensionOrDie(dimension_name)
    distance_dimension.SetGlobalSpanCostCoefficient(100)

    # Define Transportation Requests.
    for request in data['pickups_deliveries']:
        pickup_index = manager.NodeToIndex(request[0])
        delivery_index = manager.NodeToIndex(request[1])
        routing.AddPickupAndDelivery(pickup_index, delivery_index)
        routing.solver().Add(
            routing.VehicleVar(pickup_index) == routing.VehicleVar(
                delivery_index))
        routing.solver().Add(
            distance_dimension.CumulVar(pickup_index) <=
            distance_dimension.CumulVar(delivery_index))

    # Setting first solution heuristic.
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.first_solution_strategy = (routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
    search_parameters.local_search_metaheuristic = (routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
    search_parameters.time_limit.FromSeconds(1)

    # Solve the problem.
    solution = routing.SolveWithParameters(search_parameters)
    # Print solution on console.
    if solution:
        print_solution(data, manager, routing, solution)

if __name__ == '__main__':
    main()

When run, the algorithm returns:
Objective: 264620
Route for vehicle 0:
 0 Load(0) ->  1 Load(1) ->  2 Load(0) ->  3 Load(1) ->  6 Load(0) ->  4 Load(1) ->  5 Load(0) ->  0 Load(0)
Distance of the route: 2620m
Load of the route: 0

Total distance of all routes: 2620m
Total load of all routes: 0

which is fine. Now, If I only change the order of the pickups_deliveries from nodes 4->5 to 5->4 (just reversing they roles), say from this
data['pickups_deliveries'] = [
        [1, 2], #1,2
        [3, 6], #3,4
        [4, 5], #5,6
    ]

to this
data['pickups_deliveries'] = [
        [1, 2], #1,2
        [3, 6], #3,4
        [5, 4], #5,6
    ]

and change the demands accordingly from this:
data['demands'] = [
        0,  # departs empty
        1,  # load in 1
        -1, # unload in 2
        1,  # load in 3 (duplicate of 2)
        1,  # load in 4
        -1, # unload in 5
        -1] # unload in 6

to this:
data['demands'] = [
        0,  # departs empty
        1,  # load in 1
        -1, # unload in 2
        1,  # load in 3 (duplicate of 2)
        -1, # unload in 4
        1,  # load in 5
        -1] # unload in 6

the algorithm is unable to find a solution. When the only thing that has been changed is the order of the last segment. What am I doing wrong here? Any help would be very much appreciated!
Thanks in advance!
PD: A posible solution would be:

*

*Depart at (0),

*load in 1 ---> unload in 2,

*load in 3(same node as 2) ---> unload in 6

*load in 5---> unload in 4

A: If you look at the original solution we can see

Distance of the route: 2620m

And we have
 routing.AddDimension(
        transit_callback_index,
        0,  # no slack
        3000,  # vehicle maximum travel distance

So I'm pretty sure increasing the limit could help here, so let's increase it to 3500
and you'll get:
./plop.py
Objective: 346430
Route for vehicle 0:
 0 Load(0) ->  5 Load(1) ->  4 Load(0) ->  1 Load(1) ->  2 Load(0) ->  3 Load(1) ->  6 Load(0) ->  0 Load(0)
Distance of the route: 3430m
Load of the route: 0

Total distance of all routes: 3430m
Total load of all routes: 0

notice the:

Distance of the route: 3430m

ps: next time, please keep import statement
pps: your snippet didn't work since you've added some float in the distance matrix, please use only int matrix or in your callback round it using return int(data[...][][])


text:
Q: What's the difference between these thre way to stop a Jenkins pipeline? What's the difference between these thre way to stop a Jenkins pipeline?

*

*BUILD ID URL/stop

*BUILD ID URL/term

*BUILD ID URL/kill
Are there any pipeline examples?


text:
Q: Upgrade Problem in Linux Headers I was upgrading my ubuntu, when it stop when the upgrade was config linux headers. Can I restart the PC?
2014-03-28 14:19:32 configure lightdm:amd64 1.8.5-0ubuntu1
2014-03-28 14:19:32 status unpacked lightdm:amd64 1.8.5-0ubuntu1
2014-03-28 14:19:32 status unpacked lightdm:amd64 1.8.5-0ubuntu1
2014-03-28 14:19:32 status unpacked lightdm:amd64 1.8.5-0ubuntu1
2014-03-28 14:19:32 status unpacked lightdm:amd64 1.8.5-0ubuntu1
2014-03-28 14:19:32 status unpacked lightdm:amd64 1.8.5-0ubuntu1
2014-03-28 14:19:32 status unpacked lightdm:amd64 1.8.5-0ubuntu1
2014-03-28 14:19:32 status unpacked lightdm:amd64 1.8.5-0ubuntu1
2014-03-28 14:19:32 status unpacked lightdm:amd64 1.8.5-0ubuntu1
2014-03-28 14:19:33 status unpacked lightdm:amd64 1.8.5-0ubuntu1
2014-03-28 14:19:33 status unpacked lightdm:amd64 1.8.5-0ubuntu1
2014-03-28 14:19:33 status unpacked lightdm:amd64 1.8.5-0ubuntu1
2014-03-28 14:19:33 status unpacked lightdm:amd64 1.8.5-0ubuntu1
2014-03-28 14:19:33 status unpacked lightdm:amd64 1.8.5-0ubuntu1
2014-03-28 14:19:33 status unpacked lightdm:amd64 1.8.5-0ubuntu1
2014-03-28 14:19:33 status half-configured lightdm:amd64 1.8.5-0ubuntu1
2014-03-28 14:19:35 status installed lightdm:amd64 1.8.5-0ubuntu1
2014-03-28 14:19:35 configure linux-image-3.11.0-18-generic:amd64 3.11.0-18.32 <none>
2014-03-28 14:19:35 status unpacked linux-image-3.11.0-18-generic:amd64 3.11.0-18.32
2014-03-28 14:19:36 status half-configured linux-image-3.11.0-18-generic:amd64 3.11.0-18.32

https://imageshack.com/i/jwbcpjp

A: After you posted the screenshot, I see the situation. Yes, it is stuck. The process of upgrading did call update-initramfs and it got stuck.
Close the software-center, terminate it if Ubuntu asks to. Then, without reboot, open Terminal, and run 'sudo apt-get dist-upgrade' there. I think it will run, or at least give some more info.
If you reboot now, you may get stuck on boot. It is solvable, but better don't until you update it all fine.
P.S. But before doing this check one more thing!!! Check you don't have some message window open and buried under all others - the software-center may be just waiting for you to answer in that window, and the window has no icon on the left bar.


text:
Q: OpenCV Histogram Backprojection Alternative I start with creating an initial mask of an object in an image. Using this mask, a histogram is created which is then used to process subsequent images.
I use the calcBackProject function to find pixels in the image that belong to the histogram. The problem I am having is that too much of the image is being accepted because certain objects are similar to the color of the initial object. Is there any alternative to calcBackProject? In my application, I can't afford to get objects that do not belong. All of this assumes that I have a perfect initial mask.

A: There are many ways to track an object, and it can be very difficult.  Within OpenCV you may want to try the meanshift/camshift tracker to see if these are any better.  If not then you may have to stray out of the opencv world and try tracking-learning-detection frameworks.
Meanshift/Camshift/etc in OpenCV
http://docs.opencv.org/modules/video/doc/video.html
http://docs.opencv.org/trunk/doc/py_tutorials/py_video/py_meanshift/py_meanshift.html
Tracking-Learning-Detection in C++:
STRUCK: http://www.samhare.net/research/struck (uses opencv)
Tracking-Learning-Detection in Matlab:
Preditor: http://personal.ee.surrey.ac.uk/Personal/Z.Kalal/tld.html


text:
Q: how to use angular-cli options after create project I use this command for create myProject :
ng new myProject

Instead of :
ng new myProject --routing

So , I dont have app-routing.modules.ts file in myProject/src/app/
How can I alter myProject with angular-cli,to add some options that I forget them?

A: You can use this command to generate routing module

ng generate module app-routing --flat --module=app


text:
Q: How to get the current index of for loop with jijna2? Let's say that I have a code like:
{% for x in posts %}

We are in item: {{ x }}</>
{% else %}

And I want to get the current index of the for loop to run an if loop, something like(logically):
{% for x in posts %}
 {% if x.index = 0 %}

We are in the first item!

 {% else %}

We are in item: {{ x }}</>
 {% endif %}
{% endfor %}

How to do it inside jijna2? (I use Python with Flask).

A: You can use loop.index inside the loop.
{% for x in posts %}

We are in item number: {{ loop.index }}</>
{% else %}

Flask Template docs

A: You can use several loop related variables for that
http://jinja.pocoo.org/docs/dev/templates/#list-of-control-structures