text:
Q: How do I write messages when sending Outlook email using Python? I want to write messages in Outlook using Python:

Hi everyone,
Please help follow up with the following opportunities:
[Insert html table]
Best,
XXX

I have tried but the formatting looks off, e.g. the sentence "Please help follow up with the following opportunities" does not appear on a separate line
def Emailer(text, subject, recipient):
    import win32com.client as win32
    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.To = recipient
    mail.Subject = subject
    mail.HtmlBody = text
    mail.Display(True)

table = dummy.to_html()

Emailer('Hi everyone, \n\nPlease help follow up the following opportunities:'+table+'Best,\nXXX','PSE','XXX@gmail.com')

A: Turns out I need to use html syntax:
Emailer('Hi everyone,
Please help follow up the following opportunities:'+table+'Best,
XXX','PSE','XXX@gmail.com')


text:
Q: Games for which a "convexity argument" work? A few days ago I was reading a text which introduced a simple cooperative game, played by Alice and Bob, whose analysis began by showing a pure strategy was the best.
They did this by first imagining that they employed a mixed strategy and pointed out that definitionally this is just a weighted-average of pure strategies. Thus, the win-probability of the mixed strategy is just some weighted average of the win-probabilities of the pure strategies. Since it's an average, there must be some pure strategy whose win-probability was at least as large as this average so, without loss of generality, we can assume the optimal strategy for the game is a pure one.
Upon first inspection, I felt this argument was extremely wide-reaching but after speaking with some friends I now think that it may apply to any cooperative game with finite moves. This is because the set of pure strategies can be seen as a set of points in a kind of "Game space" or parameter space of one's choices and then the set of mixed-strategies will be the convex hull of these points and then the payoff, being a linear combination of the deterministic payoffs, is a linear function of the parameters within the convex set. Such a function is maximised at a vertex of the this set and a vertex, we already said, is a deterministic strategy. For this reason (and a mysterious connection to centres of gravity of convex objects), I call this a "convexity argument".
Are these the only games for which this argument is valid? Are there more or are there actually fewer (i.e. my above argument assumes something about a general cooperative game which isn't true)?

A: I imagine when you say "a pure strategy was best", you mean it was best given some strategy profile of all other players, i.e., it was a best response.
What you are saying would seem to be generally true when talking about best responses: There is always a pure strategy that is a best response. However, this does not mean that a mixed strategy cannot be a best response as well. If at least two pure strategies give the highest payoff given the strategies of the other players, then mixing over these strategies gives the same payoff.
In game theory we are usually interested in equilibrium, that is, that not only one player best responds to others for a given strategy profile of the others, but that all players play mutual best responses.
Why is this important? Well, in some games no pure strategy equilibrium exists. Consider the matching pennies game. Both players can play Up or Down. Payoffs for player 1 are $\pi_1(u,u)=\pi_1(d,d)=1$ and $\pi_1(u,d)=\pi_1(d,u)=0$. Payoffs for player 2 are $\pi_2(u,u)=\pi_2(d,d)=0$ and $\pi_2(u,d)=\pi_2(d,u)=1$.
In this game, there is no pure strategy equilibrium. The only Nash equilibrium is in mixed strategies where both players play $u$ and $d$ with probability 0.5 each. Hence, by definition of a Nash equilibrium, both players have a best response that is in mixed strategies. This does not invalidate your claim above: There is also another best response for each player which is a pure strategy, but a pure strategy cannot be part of an equilibrium in this game, since this would make players too predictable.
So I think for equilibrium analysis your observation is of somewhat limited value. When you consider mixed strategy equilibria, your goal is to find a strategy profile so that all players are indifferent between their pure strategies, so they can mix these strategies without reducing their payoff. In other words, your observation does not guarantee that an equilibrium in pure strategies exists, only that a best response in pure strategies exists.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Losing data from Quick.db in my Discord Bot I have a bot game in Discord, so i've used 'express' library to set the bot online (I guess). First of all to be clear, I'm not a dev pro, only a person who learned watching tutorials in YT. So I've created a bot game, but sometimes, my bot get offline suddenly and the users from my game lost Items, Cash and stuff like that in the game. I noticed that is like the database lost time and get back to the database from minutes ago. Someone know what could be doing that? And how I can fix?
An simple exemple of command code I've use to make my database with quick.db
let money = await db.fetch(`money_${user.id}`)
let amount = 300

if(message.content === (`${PREFIX}daily`)) {
  db.add(`money_${user.id}`, amount)
  message.channel.send(`${username} received your daily reward ${amount} money!`)
}

PS: I've use Repl.it to make my codes, if that matters.
Thanks.

A: you can try QuickMongo. It is basically quick.db for mongodb
Test
QuickMongo
const { Database } = require("quickmongo");
const db = new Database("mongodb://localhost/quickmongo");

db.once("ready", () => {
    // Setting an object in the database:
    db.set("userInfo", { difficulty: "Easy" }).then(console.log);
    // -> { difficulty: 'Easy' }

    db.push("userInfo.items", "Sword").then(console.log);
    // -> { difficulty: 'Easy', items: ['Sword'] }

    db.add("userInfo.balance", 500).then(console.log);
    // -> { difficulty: 'Easy', items: ['Sword'], balance: 500 }

    // Repeating previous examples:
    db.push("userInfo.items", "Watch").then(console.log);
    // -> { difficulty: 'Easy', items: ['Sword', 'Watch'], balance: 500 }

    db.add("userInfo.balance", 500).then(console.log);
    // -> { difficulty: 'Easy', items: ['Sword', 'Watch'], balance: 1000 }

    // Fetching individual properties
    db.get("userInfo.balance").then(console.log);
    // -> 1000
    db.get("userInfo.items").then(console.log);
    // -> ['Sword', 'Watch']
})

QuickDB
const db = require('quick.db');

// Setting an object in the database:
db.set('userInfo', { difficulty: 'Easy' })
// -> { difficulty: 'Easy' }

// Pushing an element to an array (that doesn't exist yet) in an object:
db.push('userInfo.items', 'Sword')
// -> { difficulty: 'Easy', items: ['Sword'] }

// Adding to a number (that doesn't exist yet) in an object:
db.add('userInfo.balance', 500)
// -> { difficulty: 'Easy', items: ['Sword'], balance: 500 }

// Repeating previous examples:
db.push('userInfo.items', 'Watch')
// -> { difficulty: 'Easy', items: ['Sword', 'Watch'], balance: 500 }
db.add('userInfo.balance', 500)
// -> { difficulty: 'Easy', items: ['Sword', 'Watch'], balance: 1000 }

// Fetching individual properties
db.get('userInfo.balance') // -> 1000
db.get('userInfo.items') // ['Sword', 'Watch']

A: If you are using heroku or repl.it or others like it they tend to wipe local data daily you can use mongodb or json's in your case or switch your host

A: Use Repl.it Database for persistence! https://docs.repl.it/tutorials/11-using-the-replit-database

A: replit automatically deletes 'quickdb' files after a day or two use 'quickmongo' better and faster


text:
Q: ionic run -l-c not working with cordova localwebserver I have an application where I am using wkwebview engine with cordova-labs-local-webserver plugin, when the application launches then I see the splash screen and after that I see the white screen with the message saying cordovalocalwebserver tag src is not http://localhost:[port] but (xxx.xxx..:8100)
When I build the same using the xcode then everything works fine, I need to run ionic run in order to see the console outputs.


text:
Q: Exchanging rows and columns in I am looking for a way to somehow bring the information of different rows in to different/one column.
This is the problem:
Assume that I have 10 different sellers and 1000 buyers.
Currently this is how data structured (picture)

So for each sale, I have a row with the id of the seller and a buyer who bought something from him. What I want to have is to have 1 row for each seller and then in one/different columns I want to see the id of the buyer.
I am using snowflake and read about different ways but none of them really works.
I also have a timestamp column in this table and the only thing that I could think up until now is to
SELECT seller,
       rank()over(partition by seller order by purchase_date desc)

and after that I can use aggregation functions - this is not really a wise solution and not really practical when I have 10 -20 or more buyers.
What is the best approach for solving these types of problems?

A: You should be able to do this using listagg function as per the snowflake documentation
https://docs.snowflake.com/en/sql-reference/functions/listagg.html
--This will create a concatenated list of buyers seperated by a comma
select seller
       ,listagg(buyer,',') within group(order by buyer)
  from table
group by seller


text:
Q: Compare two fields to see if they match I'm trying to think of the best way to approach validating two emails fields for a form: I have an email field and a retype email field, and I want to compare them to see if they match. If not then display an error message saying so until the user enters in their email correctly for both fields.
I know there can be custom fields classes made to allow for custom validation but I'm using 2 separate fields, not one, and I'm not sure a custom class will work in this case since I'm not validating just one field.
I followed the example found here which involves adding custom validation to the form's submit function: https://docs.silverstripe.org/en/3/developer_guides/forms/validation/
However, I don't want to redirect anywhere -- I want to stay on the form.
I'd like to make this as simple as possible if I can help it.
Here is what I have so far. Other than the issue I mentioned, everything else works fine:
public function DemoForm() {
    $fieldsArr = array();

    $firstName = new TextField('first_name', 'First Name');
    $firstName->setAttribute('placeholder', 'First Name');

    array_push($fieldsArr, $firstName);

    $lastName = new TextField('last_name', 'Last Name');
    $lastName->setAttribute('placeholder', 'Last Name');

    array_push($fieldsArr,$lastName);

    $companytName = new TextField('company_name', 'Company Name');
    $companytName->setAttribute('placeholder', 'Company Name');

    array_push($fieldsArr,$companytName);

    $email = new EmailField('email', 'Email');
    $email->setAttribute('placeholder', 'Email');

    array_push($fieldsArr, $email);

    $retypeemail = new EmailField('retype_email', 'Retype Email');
    $retypeemail->setAttribute('placeholder', 'Retype Email');

    array_push($fieldsArr, $retypeemail);

    $fields = new FieldList($fieldsArr);

    $actions = new FieldList(
        new FormAction('submit', 'Submit')
    );

    $validator = new RequiredFields('first_name', 'last_name', 'email', "retype_email");

    return new Form($this, 'DemoForm', $fields, $actions, $validator);

}

public function submit($data, $form) {
    if($data['email'] != $data['retype_email']){
        $form->addErrorMessage('Email', 'The emails do not match.', 'bad');
        return $this->redirectBack();
    }
    else{
        $demoRequest = new DemoFormSubmission();

        $demoRequest->FirstName = $data['first_name'];
        $demoRequest->LastName = $data['last_name'];
        $demoRequest->EmailAddress =$data['email'];
        $demoRequest->CompanyName = $data['company_name'];

        $demoRequest->write();

        $email = new Email();

        $email->setTo('sara.dejaneiro@innismaggiore.com');
        $email->setFrom($data['email']);
        $email->setSubject("Demo request submission");

        $messageBody = "

First Name: {$data['first_name']}

Last Name: {$data['last_name']}

Email:  {$data['email']}

Company Name: {$data['company_name']}

    ";
        $email->setBody($messageBody);
        $email->send();

        return $this->redirect("demo-request-submission-thank-you-page");
    }
}

A: Given your reply to my comment, I think you would probably be best to either:

*

*Create your own form field that extends CompositeField and then add a custom validate function (as per https://docs.silverstripe.org/en/3/developer_guides/forms/validation/#form-validation)

*Creating a custom validator, by extending RequiredFields (https://github.com/silverstripe/silverstripe-framework/blob/3.6.2/forms/RequiredFields.php) and then overloading the PHP method (https://github.com/silverstripe/silverstripe-framework/blob/3.6.2/forms/RequiredFields.php#L82).
Number 2 might be the less fiddly approach. You can write your own custom logic and then if the validation fails simply return "false" and then SilverStripe will cancel form submission and return the user to the form with their data still in the form fields.


text:
Q: Return All Rows/Column Data from Data Set I'm designing an ASP.NET MVC 4 solution that will allow a user to import an Excel file, make specific modifications to it on the page, and export the file in the same format.  I'm trying to make a View called Grid that will display the contents of a large Data Set which contains all of the data from the Excel spreadsheet.
    public ActionResult Grid()
    {
        DataSet ds = TempData["DataSet"] as DataSet;
        string exampleCell = ds.Tables[0].Rows[3][2].ToString();
        return View();
    }

exampleCell is an example of how I am extracting single cells from the table.  I imagine I can iterate through all of the columns and rows in the Data Set and extract all of the data using this approach.  How, then, can I display all of the exampleCells on a single View?

A: You'd be far better off creating a Model for what you're iterating over. This will allow MVC to generate the Model when your user clicks Save on the client side.
So you'll have a class that will encapsulate the values in each row. Have another Model which will have an IEnumerable/IList of your first Model you created.
In your Controller method, convert the DataSet to these models, and then pass the model with the collection to your View. Populate your HTML grid/table by iterating through the enumerable.
If you want to save all of the user's changes in one shot, wrap your grid/table in a form, and use the same Model (with the IEnumerable) as a parameter for the POST method. That will populate the entire model back for you when it calls the server again.
That might be a little unwieldy to try and figure out what changed (unless you just want to do a single mass data dump again), so if you want to save each action, that'd be just as easy to do with single client side AJAX calls.


text:
Q: My if statement is not working, it always starts with 'user already exist' whenever i reload the page <?php
$con = mysqli_connect("localhost","root","","earhartdb");

    if(isset($_POST['reg'])){

        $FName = $_POST['txtFname'];
        $SName = $_POST['txtSname'];
        $LName = $_POST['txtLname'];
        $EMail = $_POST['txtEname'];
        $Username = $_POST['txtUsername'];
        $Pass = $_POST['txtPass'];
        $Conpass = $_POST['txtConpass'];
        $Gender = $_POST['gender'];

        $sql_user = "SELECT * FROM userstb WHERE Username = '$Username'";
        $sql_email = "SELECT * FROM userstb WHERE EMail = '$EMail'";
        $res_user = mysqli_query($con, $sql_user) or die(mysqli_error($con));
        $res_email = mysqli_query($con, $sql_email) or die(mysqli_error($con));

            if(mysqli_num_rows($res_user) > 0){
                echo '<script type="text/javascript"> alert("User already exist") </script>';
            }

            elseif(mysqli_num_rows($res_email) > 0){
                echo '<script type="text/javascript"> alert("Email already exist") </script>';
            }

            else{
                $sql = "INSERT INTO `userstb` (`FirstName`, `SecondName`, `LastName`, `Email`, `Gender`, `Username`, `Password`, `ConfirmPassword`)VALUES ('$FName','$SName','$LName','$EMail','$Gender','$Username','$Pass','$Conpass')";
                $result = mysqli_query($con,$sql) or die(mysqli_error($con));

                 echo '<script type="text/javascript"> alert("You are now registered") </script>';
                 exit();
            }
    }

?>

A: Many browsers will resend post parameters on reload. Try opening the page on an incognito tab.
Another way you can debug your code is by echoing the $Username and $res_user. This will allow you to see what is triggering the if statement.
If you determine that the problem is with the SQL database itself, I recommend that you run the queries directly through SQL to compare the results. Tools such as phpMyAdmin allow you easily browse an SQL database.


text:
Q: Solving $ \sin2x\sin x+ \cos^2x = \sin5x\sin 4x+ \cos^24x$
Solve the following equation over the real numbers:
  $$ \sin(2x)\sin(x)+ \cos^2(x) = \sin(5x)\sin(4x)+ \cos^2(4x) $$

What I've tried so far, to no avail, is using identities (product-to-sum and sum-to-product, as well as the double angle identity) in search of a more convenient form, like a product equaling $0$ or a polynomial through some notation. Alternate forms I've reached :
$$ \sin(5x)\sin(3x)=\sin(6x)\sin (3x)$$
$$\sin(x)(\sin(x)(2\cos(x)-1)- 4\cos(x)(1-2\sin^2(x))(\sin(5x)-\sin(4x) ))=0$$
Perhaps a helpful identity: $$ \cos^2(x)- \cos^2(4x)= \sin(5x)\sin(3x) $$

A: Use $\cos^2(a)+\sin^2(a)=1$ first on both sides then factorize.
$$\sin(x)[\sin(2x)-\sin(x)]=\sin(4x)[\sin(5x)-\sin(4x)]$$
Now use $\sin(A)−\sin(B)$ as a product on both sides and simplify (giving some roots $\sin(\frac{x}{2})=0$)
$$\sin(x)\cdot2\cos(\frac{3x}{2})\sin(\frac{x}{2})=\sin(4x)\cdot2\cos(\frac{9x}{2})\sin(\frac{x}{2})$$
then write \sin(C)\cos(D) as a difference of sines on both sides and simplify.
$$\frac{1}{2}\bigg[\sin(\frac{5x}{2})+\sin(\frac{-x}{2})\bigg]=\frac{1}{2}\bigg[\sin(\frac{17x}{2})+\sin(\frac{-x}{2})\bigg]$$
Write the difference of sines as a product and solve
$$\sin(\frac{5x}{2})-\sin(\frac{17x}{2})=0$$

A: Hint
By $\cos2y=2\cos^2y-1$ and
http://mathworld.wolfram.com/WernerFormulas.html and
http://mathworld.wolfram.com/ProsthaphaeresisFormulas.html,
$$\cos x-\cos3x+1+\cos2x=\cos x-\cos9x+1+\cos8x$$
$$\cos2x-\cos8x=\cos3x-\cos9x$$
$$2\sin5x\sin3x=2\sin3x\sin6x$$


text:
Q: Does REST supports protocol buffers This might be a very generic question, but considering the fact that REST is focused on accessing named resources through a single consistent interface; does it supports protocol buffers?

A: Yes, you can absolutely combine Protobuf and REST.
Protbuf specifies a way to encode data. REST specifies a way to interact with resources, but does not require any particular encoding for the resource bodies. If you create a RESTful HTTP-based API and use Protobuf to encode the entity-bodies (the technical term for the payload part of an HTTP request or response), then you are using both REST and Protobuf.

A: Back to the future, there is this Spring REST API with Protocol Buffers tutorial:
Generate the corresponding Java classes using:
protoc --java_out=java resources/baeldung.proto
Add the following dependency on your Maven's POM file:
<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java</artifactId>
    <version>3.0.0-beta-3</version>
</dependency>

Add the following converter to your @SpringBootApplication:
@Bean
ProtobufHttpMessageConverter protobufHttpMessageConverter() {
    return new ProtobufHttpMessageConverter();
}

The ProtobufHttpMessageConverter bean is used to convert responses returned by @RequestMapping annotated methods to protocol buffer messages.
What's important here is that we're operating with Protocol Buffer specific data – not with standard POJOs.


text:
Q: R 4.1.2 could not find X11 headers/libs after specifying --x-includes and --x-libraries I am trying to install a local R version on a ubuntu server. The server has X11 installed
➜  X11 pwd
/home/linuxbrew/.linuxbrew/include/X11
➜  X11 ls
ap_keysym.h   HookObjI.h    ResourceI.h   Xatom.h       Xos.h
CallbackI.h   HPkeysym.h    SelectionI.h  Xauth.h       Xos_r.h
...

and I can find the required headers for example IntrinsicI.h. However, when I configure R using the following command, it failed to recognize those headers even after I told R where they are.
➜  R-4.1.2 ./configure --prefix=$HOME/R \\
--x-includes=/home/linuxbrew/.linuxbrew/include/X11 \\
--x-libraries=/home/linuxbrew/.linuxbrew/lib

Does anyone have any idea why this happens?


text:
Q: C++ Calculating Shortest Path in a Directed Graph I am tasked with writing a program to maintain the representation of a simple network(weighted directed graph) and compute the best path between two given nodes upon request.
Currently, I am attempting to write a function to compute the simplest between two nodes, however, when attempting to run my program, I get two specific error
Severity    Code    Description Project File    Line    Suppression State
Error   C3863   array type 'bool [openNode]' is not assignable  P   127

and
Severity    Code    Description Project File    Line    Suppression State
Error   C3863   array type 'int [openNode]' is not assignable

I am unable to debug since these two primary errors are not allowing my program to run. Is there any particular reason for these errors?
Thanks in advance!
This is the node structure defined in Graph.h
struct GraphNode
{
    char ID;
    std::string name;
    int inNodes = 0;
    int outNodes = 0;
    std::vector<std::pair<GraphNode*, int>> connection;
    int  connections = 0;
};

And here is the particular code that causes the errors.
#include "Graph.h"

std::vector<GraphNode*> _graph;
int openNode = 0;

//Obligatory constructor
void Graph()
{

}

void shortestPath(char fromNode, char toNode)
{
    bool known[openNode];
    int distance[openNode];
    GraphNode*  previous[openNode];
    int numbChecked = 0;

    for (int i = 0; i < openNode; i++)
    {
        known[i] = false;
        distance[i] = 999999;
        previous[i] = nullptr;
    }

    distance[findNode(fromNode)] = 0;

    while (numbChecked < openNode)
    {
        int smallestUnknown = 9999999;
        int locationOfSmall = 0;
        for (int i = 0; i < openNode; i++)
        {
            if (known[i] == false && distance[i] < smallestUnknown)
            {
                smallestUnknown = distance[i];
                locationOfSmall = i;
            }
        }

        if (distance[locationOfSmall] == 0)
        {
            previous[locationOfSmall] = nullptr;
        }

        known[locationOfSmall] = true;
        numbChecked++;

        if (_graph[locationOfSmall]->outNodes > 0)
        {
            for (int i = 0; i < _graph[locationOfSmall]->outNodes; i++)
            {
                int newDistanceLocation = findNode(_graph[locationOfSmall]->connection[i].first->ID);
                if (known[newDistanceLocation] == false && (distance[locationOfSmall] + _graph[locationOfSmall]->connection[i].second) < distance[newDistanceLocation])
                {
                    distance[newDistanceLocation] = distance[locationOfSmall] + _graph[locationOfSmall]->connection[i].second;
                    previous[newDistanceLocation] = _graph[locationOfSmall];
                }
            }
        }
    }

    int destination = findNode(toNode);
    std::string output;
    std::string charTransfer;
    charTransfer = toNode;
    output = charTransfer;

    while (previous[destination] != nullptr)
    {
        destination = findNode(previous[destination]->ID);
        charTransfer = _graph[destination]->ID;
        output = charTransfer + "->" + output;
    }

    if (_graph[destination]->ID != fromNode)
    {
        std::cout << "The nodes are not connected." << std::endl;
    }
    else
    {
        std::cout << "The path is: " << output << std::endl;
        std::cout << "The distance is: " << distance[findNode(toNode)] << std::endl;
    }

}

Any change suggestions would be much appreciated!

A: You have invalid code at the beginning of your shortestPath function:
bool known[openNode];
int distance[openNode];
GraphNode*  previous[openNode];

You cannot use variables to create arrays on the stack (which is what you are trying to do there), because the compiler doesn't know the value of openNode at compile time (which is needed to determine the stack size).
Why don't you use a vector, like:
std::vector<bool> known(openNode, false);
std::vector<int> distance(openNode, 999999);
std::vector<GraphNode*>  previous(openNode, nullptr);

Using this method makes the for loop below obsolete aswell.


text:
Q: tf.keras 4x slower than Keras in my RL code I'm very new to Machine Learning.
I have found this example at Github: Code
I implemented the q_learning_keras function and chaned the Keras model to a tf.keras model.
With the Keras model 1000 Episodes take about 30 minutes.
With the tf.keras model 1000 Episodes take about 110 minutes.
Also the tf.keras variant need about 5-7% less cpu power.
I'm using Tensorflow version 1.13.1 and Keras version 2.2.4.
I'm runing the code on a virtual machine with 4 Cores @ 2.6 GHz.
Keras model:
model = Sequential()
model.add(InputLayer(batch_input_shape=(1, 5)))
model.add(Dense(10, activation='sigmoid'))
model.add(Dense(2, activation='linear'))
model.compile(loss='mse', optimizer='adam', metrics=['mae'])

tf.keras model:
model = tf.keras.models.Sequential([
        tf.keras.layers.InputLayer(batch_input_shape=(1, 5)),
        tf.keras.layers.Dense(10, activation='sigmoid'),
        tf.keras.layers.Dense(2, activation='linear')
        ])

The rest of the code is in both excatly the same, ase in the Github example linked above.
In the most over post I have found exactly the opposite problem, that Keras was slower then tf.keras. So I also hoped to get an increase in speed or at least to stay the same.
So I think, I have maybe make a mistake but I don't find it.
Edit:
Done some more resarch, with Tensorboard to see how the model look like.
The models look very similar at the most things. But the tf.keras model have some overhead. I don't know if this is normal for tf.keras model or if it comes from my way I build the model.
tf.keras model
keras model


text:
Q: How can I create a dictionary from two lists while keeping days together? I have a list of dates and a list of times. How can I create a dictionary with the key as the date and the times as the values using the next date as a key when the hours belong to a different next day (so when a time is less than the previous time)? Both lists are currently strings.
My list of dates:
['2019/07/27',
 '2019/07/29',]

My list of times:
['06:55:40',
 '06:55:41',
 '08:48:33',
 '08:48:33',
 '09:02:54',
 '09:02:54',
 '09:02:54',
 '10:02:19',
 '10:02:20',
 '07:34:52',
 '07:34:52',
 '07:35:03',
 '09:22:19',
 '09:22:19',
 '09:22:19',
 '09:22:23',
 '11:17:24',
 '11:17:27',
 '13:24:57',]

Expected output:
{'2019/07/27': ['06:55:40',
                '06:55:41',
                '08:48:33',
                '08:48:33',
                '09:02:54',
                '09:02:54',
                '09:02:54',
                '10:02:19',
                '10:02:20',],
 '2019/07/29': ['07:34:52',
                '07:34:52',
                '07:35:03',
                '09:22:19',
                '09:22:19',
                '09:22:19',
                '09:22:23',
                '11:17:24',
                '11:17:27',
                '13:24:57',]}

A: time_groups = []
grp = []
previous_time = None
for time in times:
    if previous_time is None or time > previous_time:
        grp.append(time)
    else:
        time_groups.append(grp)
        grp = []
    previous_time = time

output = {d:t for d,t in zip(dates,time_groups)}

A: You can do it with this function. It is easier if you convert them to datetime objects for comparison purposes:
from datetime import datetime as dt

def sort_dates(ds, ts):
    limit = dt.strptime("23:59:59", "%H:%M:%S").time()
    res = {}
    i = -1

    for time in ts:
        current = dt.strptime(time, "%H:%M:%S").time()
        if current < limit:
            i+=1
            res[ds[i]] = []
        res[d[i]].append(time)
        limit = current

    return res

d = ['2019/07/27', '2019/07/29']
t = ['06:55:40', '06:55:41', '08:48:33', '08:48:33', '09:02:54', '09:02:54', '09:02:54', '10:02:19', '10:02:20', '07:34:52', '07:34:52', '07:35:03', '09:22:19', '09:22:19', '09:22:19', '09:22:23', '11:17:24', '11:17:27', '13:24:57']
res = sort_dates(d, t)

A: My solution is below. I sliced the list of times.
i = 1
j = 0
length = len(times)
while i < length:
    if times[i-1] > times[i] or i is length-1: # i is the index of the start time on the next day
        dict[dates[j]] = times[:i]
        times = times[i:]
        j += 1
        i = 1
        length = len(times)
    else:
        i += 1


text:
Q: HTML elements that could trigger an HTTP request Given a web page, I would like to detect:

*

*Which elements in the page might trigger an http request?

*For those
elements, I would like to know what is the http method (POST,
GET, etc.) of the relevant request.

I'm assuming this is a tough question.. but are there any indicators that could hint for one option or another?

A: I would say any element having an attribute of type URI will be capable of trigerring an HTTP request, and also any element having an attribute if type script can trigger it through javascript.
We could filter that out from this list:
https://www.w3.org/TR/REC-html40/index/attributes.html
and based on the accepted answer for this question:
COMPLETE list of HTML tag attributes which have a URL value?
This gives you the list with attributes of type url (see my quoted answer below).
As for script type attributes, that includes onclick, onkeypress, etc which means, I believe you would be left with a hand full of elements which are not going to be able to trigger an http request if that.
Quoting the answer:
Check out the W3C's list of HTML attributes, there's a "type" column in there and just look for URI types.
And of course the HTML 5 version of that list is useful too
So for HTML4 we've got:

*

*

*<applet codebase=url>

*<area href=url>

*<base href=url>

*

*

*

*<form action=url>

*<frame longdesc=url> and <frame src=url>

*

* and

* and  and

*<input src=url> and <input usemap=url>

*

*<link href=url>

*<object classid=url> and <object codebase=url> and <object data=url> and <object usemap=url>

*<q cite=url>

*


text:
Q: Speed up a massive number of inserts into multiple databases I wrote a script that uses MyBatis to execute a massive number of inserts into multiple databases. The previous script didn't use MyBatis an was, more or less, twice as fast (25 min for a million records, 1 hour 10 minutes using MyBatis). I have tried different things, but I don't know exactly how to configure MyBatis to increase its performance. Some specific considerations about my problem and solution:

*

*The databases are in a VPC, so network time is important.

*I use guice to bind the mappers for each database. Connection information is set programmatically. The mappers are get then when I need to execute an insert.

*The rows that need to be inserted are not sorted, so they are enqueued by database. When a queue reaches a given size, a multirow insert is executed. Can I use something better with injected mappers?

*I use pooled connections. Does this mean that 3 connections are opened when the mapper is first used and then reused? If a given mapper is used only every few minutes, those idle connections are closed?

*Sometimes I get this error randomly:
org.apache.ibatis.transaction.TransactionException: Error configuring
AutoCommit.  Your driver may not support getAutoCommit() or
setAutoCommit(). Requested setting: false.
Cause:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 4,030,088 milliseconds ago.
The last packet sent successfully to the server was 0 milliseconds ago.

What can I do to increase the performance and to avoid the communication error?

A: 1、it seems that you need to change your connection pool param.
database such as mysql may close a connection when it's idle for a target time interval, but the connection pool may not be noticed ,so when your mapper use a closed connection , the CommunicationsException occurs.
(1)if you use c3p0 ,you can specify the idle_test_period to solve this problem.
(2) or you can specify jdbc Timeout Settings(Max Wait Time、Idle Timeout)
2、connection pool has minSize and maxSize property , when your idle connection num is greater then minSize, the exceed part will be closed.

A: I think you have to make optimization of mysql configuration to bulk insert : enter link description here
It look like mybatis try to set autocommit to false, and that's a good optimization.
And I think it's better to have an instance of mapper by database and create 3 datasources with guice.
Another way is to use sqlimport but it's a big break.


text:
Q: Open website in new tab How to open web link in new tab. If i specify Google
means on clicking the link, it opens in new new window and not in new tab. How to make the web link open in new tab?

I am using IE8 browser, i have set settings to open links from other programs in new tab but still it opens up in new window!!!

A: The behavior whether a page opens up in a new window or a new tab depends on the web browser. Actually there is always a new window opened but you can set your browser to open new windows in a new tab.

A: in an HTML anchor you can only specify a link to be in the same or in a new window. if this 'new window' is either a new tab or a real new window is pure browser settings.


text:
Q: why jms Client acknowledge is not working I am trying to retrieve messages from an ActiveMQ queue. I set the session to Session.CLIENT_ACKNOWLEDGE. When I receive the message from the server it is auto-acknowledged although I have not called acknowledge on the message. Below is sample code of what I am doing:
connection = connectionFactory.createConnection();
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
Destination destination = session.createQueue(queue);
consumer = session.createConsumer(destination);
connection.start();
Message message = consumer.receive(1);

The code snippet above works and I do get the message from the queue. The problem is that messages disappear from the queue although I have not acknowledged the message. Any pointers why this is happening. I have been debugging this issue almost all this afternoon with no luck. This is a Spring boot application.
I got the client_ack to work in jmsTemplate. Below is the code.
public Object retrieve() {
        return this.jmsTemplate.execute(session -> {
            session.recover();
            MessageConsumer consumer = session.createConsumer(
                    this.jmsTemplate.getDestinationResolver().resolveDestinationName(session, queue, false));
            try {
                Message received = consumer.receive(1);
                if (received != null) {
                    return this.messageConverter.fromMessage(received);
                }
            }
            catch (Exception e) {
                return null;
            }
            finally {
                consumer.close();
            }
            return null;
        }, true);
    }

The issue I am now seeing is that my app does not see these messages after it restarts. I tried running session.recover() but it is not making any difference. Thanks for your help.
The working code using jmsTemplate is as below:
public Object retrieve() {
        return this.jmsTemplate.execute(session -> {
            MessageConsumer consumer = session.createConsumer(
                    this.jmsTemplate.getDestinationResolver().resolveDestinationName(session, queue, false));
            try {
                Message received = consumer.receive(1);
                session.recover();
                if (received != null) {
                    return this.messageConverter.fromMessage(received);
                }
            }
            catch (Exception e) {
                return null;
            }
            finally {
                consumer.close();
            }
            return null;
        }, true);
    }

A: This appears to be a problem with the springframework Constants class. It uses introspection to get the integer value of CLIENT_ACKNOWLEDGE but always return a value of 1, so session is always AUTO_ACKNOWLEDGE

A: To anybody who might run into this issue, I did the following to resolve the issue:

*

*Set the session to non-transacted. This is the default and only option if you are using jmsTemplate. If you are creating your own consumer, you need to create the session as non-transacted when creating the jms connection

*If you are creating your own consumer, you need to set the session to CLIENT_ACKNOWLEDGE.

*Check the maximum number of redeliveries to the required value. This will differ depending on the product: ActiveMQ, IBM MQ, etc.

*call session.recover() after retrieving the message.

I updated the working code that is using jmsTemplate in the original post.


text:
Q: Why aren't C++ libraries showing up for me while trying to set uop VSCode for C++ (MacOS) hey im trying to set up vscode for c on my mac (MacOS Ventura 13.0, 1.4GHz intel core i5) following this Using Clang in Visual Studio Code guide but when get to the step with the helloworld.ccp file, i get an error for my #includes saying "cannot open source file '[library]'", this is happening for all of the #includes in the given code and ive tried following instructions to install the libraries thru vcpkg but these libraries arent on there. ive followed all previous instructions like installing Xcode
ive tried restarting vscode a number of times, insstalling these libraries from different websites, looking for extensions that might help and for other ways of setting up vscode that dont require this method. im pretty new to coding so its probably something small messing it up but i havent been able to figure it out.


text:
Q: Adding A Dynamic Link In Php I have been using the following to add a dynamic link on a page I am writing, it works ok and appears how it should on the page but I cant help but think that I am going a bit backwards with the way its written as it looks messy. What is the correct way to write it, as if I put it all in one line it doesn't work ?..
echo 'getFilename();
        echo '">';
              echo $filename->getFilename();
    echo '';

A: Try with
echo "getFilename()}\">{$filename->getFilename()}";

Here there is the documentation with a lot of examples of how to concatenate output.

A: Concatenation is your friend. Use a . to combine multiple string expression into one.
echo 'getFilename().'">'.$filename->getFilename()/'';

Even better way would be
$filename = $filename -> getFilename(); //cache the filename
echo "$filename";
  // ^ On this echo NOTICE that variables can be DIRECTLY placed inside Double qoutes.

A: I would go with this:
$fn = $filename->getFilename();
$link = $customerID . '/' . $fn;
echo ''.$fn.'';

A: I'd approach it like this:
$safe_customer_id = htmlspecialchars(urlencode($customerID));
$safe_filename = htmlspecialchars(urlencode($filename->getFilename()));
$safe_label = htmlspecialchars($filename->getFilename());
echo "$safe_label";

A: If you're using a template layer, it is even better to break out into PHP only when you need to:
<a href="./customer-files/<?php
    echo $customerID . '/' . $filename->getFilename()
?>">
    <?php echo $filename->getFilename() ?>

This way, your IDE will correctly highlight your HTML as well as your PHP. I've also ensured that all PHP is in single-line blobs, which is the best approach for templates (lengthy statements should be banished to a controller/script).


text:
Q: AIX: Howto setup a new /home directory on a new harddrive Our AIX 5.3 IntelliStation was running out of space in the /home directory and we needed to move the /home directory to a different location.
Fortunately, the IntelliStation we are using had a second harddrive "hdisk1" which was not used at all.
Please note: I am working as a software engineer, not as an admin. But since we don't have a dedicated AIX admin, I am feeling somehow responsible for this machine.
I am very confused with all this AIX specific stuff:

*

*Volume Groups

*Physical Volumes

*Logical Volumes

*Journaled Filesystems and Filesystem Logs

... and I need some help.

A: Meanwhile I found a solution for the topic mentioned. But I would like to let others know how I did that.
I found this great description from a guy whose name is "Ryan".
see: Ryan's AIX description
The only thing I had to change was: use jfs instead of jfs2 (for whatever reason).
Here is a summary of the commands I used to get this working:
1. mkvg -y homevg hdisk1                    # create a new volume group on the new/free  harddisk
2. mklv -t jfslog -y loghomevg homevg 1     # prepare log for the new filesystem
3. mklv -t jfs    -y    homelv homevg 64G   # prepare a 64G partition for the new /home
4. mkfs -o log=/dev/loghomevg  -V jfs /dev/homelv # create new jfs filesystem.
5. mkdir /home2                             # create a mountpoint for the new filesystem
6. chown bin:bin /home2                     # set ownership according to /home
7. mount -o log=/dev/loghomevg  /dev/homelv /home2 # mount the new filesystem

Note: in (4) you have to answer with "Yes". Afterwards it will take a while to complete.
After all that I copied the original content of the /home directory to /home2. I did so by using gnu tar, but other approaches should also work:
cd /home
gtar -cvpf - * | gtar -C /home2 -xpf -

you are done now!
finally you could unmount /home and use /home2 as the new /home directory, e.g. by modifying /etc/filesystems appropriately. Alternatively you could assign a new home directory to the users defined in /etc/passwd, e.g. use /home2/buildsys instead of /home/buildsys


text:
Q: Angular - Material Table, is it possible to edit rows by clicking a button? i have mat-table in that i need to edit table.  in table their is edit icon button ,if  i clicked on edit button the first 3 columns should  be editable and need to updated after editing.
edit should in same inline only not as mat-dialogue box . if we pressed on edit button name, age, phone-number should be editable . please help me in this
.html file

          <mat-table mat-stretch-tabs [dataSource]="dataSource" matSort matSortActive="name" matSortDirection="asc" matSortDisableClear>
           <ng-container matColumnDef="name">
             <mat-header-cell *matHeaderCellDef mat-sort-header >  Name <mat-icon>filter_list</mat-icon> </mat-header-cell>
              <mat-cell *matCellDef="let datalist " > {{datalist.name}} </mat-cell>
           </ng-container>

            <ng-container matColumnDef="description">
              <mat-header-cell *matHeaderCellDef mat-sort-header > Age <mat-icon>filter_list</mat-icon> </mat-header-cell>
              <mat-cell *matCellDef="let datalist" > {{datalist.age}} </mat-cell>
            </ng-container>
              <ng-container matColumnDef="databaseId">
                <mat-header-cell *matHeaderCellDef mat-sort-header >  <mat-icon>filter_list</mat-icon> </mat-header-cell>
                <mat-cell *matCellDef="let datalist" > {{datalist.phonenumber}} </mat-cell>
             </ng-container>

              <ng-container matColumnDef="isActive">
                  <mat-header-cell *matHeaderCellDef  > IsActive/InActive </mat-header-cell>
                  <mat-cell *matCellDef="let datalist" ><mat-slide-toggle color="primary" [checked]="datalist.isActive"></mat-slide-toggle></mat-cell>
              </ng-container>

              <ng-container matColumnDef="edit">
                <mat-header-cell *matHeaderCellDef > Edit </mat-header-cell>
                <mat-cell *matCellDef="let row">
                  <button mat-icon-button color="primary" >
                    <mat-icon>edit</mat-icon>
                  </button>
                </mat-cell>
              </ng-container>

              <ng-container matColumnDef="delete">
                <mat-header-cell *matHeaderCellDef > Delete </mat-header-cell>
                <mat-cell *matCellDef="let datalist">
                  <button mat-icon-button color="primary" (click)="clickEvent(datalist,datalist.principalId)"  [ngClass]="{'myClass':datalist.isClicked}">
                    <mat-icon>remove_circle</mat-icon>
                  </button>
                </mat-cell>
              </ng-container>

              <mat-header-row *matHeaderRowDef="displayedColumns" ></mat-header-row>
              <mat-row *matRowDef="let row; columns: displayedColumns;" (click)="onRowClicked(datalist)"></mat-row>
          </mat-table>

           <button class="mat-button menu-button">
              <mat-icon color="primary"> add_to_photos </mat-icon>
              Add Site
           </button>

            <button mat-button type="button"  class="close-button" (click)="cancel()">
              <mat-icon>block</mat-icon>
             CANCEL
            </button>
           <button (click)="delete()">Save</button>

A: This answer is not specific to mat-table, but try using PrimeNG for editable tables.
https://www.primefaces.org/primeng/#/table/edit


text:
Q: How can I send multiple checkbox values to firebase in swift? I have a problem to send multiple checkbox values to Firebase in Swift
I want to send values of 7 checkboxs (7 Days of the Week) to Realtime Database. if which one is select send true to firebase. if not select send notthing or false to firebase.
I knowhow to read and write data to firebase but i'm not sure But I don't know how to do this.
I'm using pod AIFlatSwitch to make chekckbox animation
@IBOutlet weak var bgM: AIFlatSwitch!
@IBOutlet weak var bgT: AIFlatSwitch!
@IBOutlet weak var bgW: AIFlatSwitch!
@IBOutlet weak var bgTh: AIFlatSwitch!
@IBOutlet weak var bgF: AIFlatSwitch!
@IBOutlet weak var bgSat: AIFlatSwitch!
@IBOutlet weak var bgSun: AIFlatSwitch!

override func viewDidLoad() {
    super.viewDidLoad()

    let action1 = UITapGestureRecognizer(target: self, action:  #selector (self.callActionEveryDay (_:)))
    self.bgeveryDay.addGestureRecognizer(action1)

    let action2 = UITapGestureRecognizer(target: self, action:  #selector (self.callActionM (_:)))
    self.bgM.addGestureRecognizer(action2)

    let action3 = UITapGestureRecognizer(target: self, action:  #selector (self.callActionT (_:)))
    self.bgT.addGestureRecognizer(action3)

    let action4 = UITapGestureRecognizer(target: self, action:  #selector (self.callActionW (_:)))
    self.bgW.addGestureRecognizer(action4)

    let action5 = UITapGestureRecognizer(target: self, action:  #selector (self.callActionTh (_:)))
    self.bgTh.addGestureRecognizer(action5)

    let action6 = UITapGestureRecognizer(target: self, action:  #selector (self.callActionF (_:)))
    self.bgF.addGestureRecognizer(action6)

    let action7 = UITapGestureRecognizer(target: self, action:  #selector (self.callActionSat (_:)))
    self.bgSat.addGestureRecognizer(action7)

    let action8 = UITapGestureRecognizer(target: self, action:  #selector (self.callActionSun (_:)))
    self.bgSun.addGestureRecognizer(action8)

}

//Action when click on each view

@objc func callActionM(_ sender:UITapGestureRecognizer){
    if bgM.isSelected == false {
        bgM.isSelected = true
        bgM.backgroundColor = UIColor(red: 75.0 / 255.0, green: 182.0 / 255.0, blue: 71.0 / 255.0, alpha: 1.0)
        mLabel.textColor = UIColor.white
    }else{
        bgM.isSelected = false
        bgM.backgroundColor = UIColor.white
        mLabel.textColor = UIColor.black
    }
}
@objc func callActionT(_ sender:UITapGestureRecognizer){
    if bgT.isSelected == false {
        bgT.isSelected = true
        bgT.backgroundColor = UIColor(red: 75.0 / 255.0, green: 182.0 / 255.0, blue: 71.0 / 255.0, alpha: 1.0)
        tLabel.textColor = UIColor.white
    }else{
        bgT.isSelected = false
        bgT.backgroundColor = UIColor.white
        tLabel.textColor = UIColor.black
    }
}
@objc func callActionW(_ sender:UITapGestureRecognizer){
    if bgW.isSelected == false {
        bgW.isSelected = true
        bgW.backgroundColor = UIColor(red: 75.0 / 255.0, green: 182.0 / 255.0, blue: 71.0 / 255.0, alpha: 1.0)
        wLabel.textColor = UIColor.white
    }else{
        bgW.isSelected = false
        bgW.backgroundColor = UIColor.white
        wLabel.textColor = UIColor.black
    }
}
@objc func callActionTh(_ sender:UITapGestureRecognizer){
    if bgTh.isSelected == false {
        bgTh.isSelected = true
        bgTh.backgroundColor = UIColor(red: 75.0 / 255.0, green: 182.0 / 255.0, blue: 71.0 / 255.0, alpha: 1.0)
        thLabel.textColor = UIColor.white
    }else{
        bgTh.isSelected = false
        bgTh.backgroundColor = UIColor.white
        thLabel.textColor = UIColor.black
    }
}
@objc func callActionF(_ sender:UITapGestureRecognizer){
    if bgF.isSelected == false {
        bgF.isSelected = true
        bgF.backgroundColor = UIColor(red: 75.0 / 255.0, green: 182.0 / 255.0, blue: 71.0 / 255.0, alpha: 1.0)
        fLabel.textColor = UIColor.white
    }else{
        bgF.isSelected = false
        bgF.backgroundColor = UIColor.white
        fLabel.textColor = UIColor.black
    }
}
@objc func callActionSat(_ sender:UITapGestureRecognizer){
    if bgSat.isSelected == false {
        bgSat.isSelected = true
        bgSat.backgroundColor = UIColor(red: 75.0 / 255.0, green: 182.0 / 255.0, blue: 71.0 / 255.0, alpha: 1.0)
        satLabel.textColor = UIColor.white
    }else{
        bgSat.isSelected = false
        bgSat.backgroundColor = UIColor.white
        satLabel.textColor = UIColor.black
    }
}
@objc func callActionSun(_ sender:UITapGestureRecognizer){
    if bgSun.isSelected == false {
        bgSun.isSelected = true
        bgSun.backgroundColor = UIColor(red: 75.0 / 255.0, green: 182.0 / 255.0, blue: 71.0 / 255.0, alpha: 1.0)
        sunLabel.textColor = UIColor.white
    }else{
        bgSun.isSelected = false
        bgSun.backgroundColor = UIColor.white
        sunLabel.textColor = UIColor.black
    }
}


text:
Q: Why does ofstream not trigger IN_CREATE I'm writing tests for an inotify library and I'm currently working on capturing the IN_CREATE event. I'm trying to use boost::filesystem::ofstream, which is essentially std::basic_ofstream, but I'm not getting the IN_CREATE event.
There are two threads in execution, the main thread, and one I create that processes events like so:
std::thread thread([&]()
{
    boost::asio::io_service::work(g_io_service);
    g_io_service.run();
}

Whenever an event is received, the library calls this function in the context of the above thread:
[&](event_type event, std::string const & path)
{
    std::lock_guard<std::mutex> lock(ready_mtx);
    events.push_back(event);
    condition.notify_all();
    ready = true;
}

What the test looks like (main  thread):
{
    boost::filesystem::ofstream file(path);
    file << "test";
}
{
    std::lock_guard<std::mutex> lock(ready_mtx);
    while (!ready)
        condition.wait(lock);
    REQUIRE(events[0] == event_type::FILE_CREATE);
}

I'm expecting an event for the creation and modification of the file, and the file is in fact being created when I look for it in the terminal, but I do not receive any event.
However, when I manually create the file with echo "test" > test.file I do receive the create and modify events.
Is there a reason for this behavior? Am I approaching this the wrong way?

A: I created the following without my library and it works just fine. I'm obviously doing something wrong in my own code. Thanks.
#include <atomic>
#include <condition_variable>
#include <fstream>
#include <functional>
#include <iostream>
#include <iterator>
#include <string>
#include <thread>

#include <linux/limits.h>
#include <sys/inotify.h>
#include <unistd.h>

std::mutex cout_mtx;
std::string path("/tmp/test-inotify");
std::string filename("test.file");

void print(std::string const & msg)
{
    std::lock_guard<std::mutex> lock(cout_mtx);
    std::cout << msg << std::endl;
}

void thread_fn(int fd, std::function<void(int, std::string const & name)> callback)
{
    std::string buffer;
    buffer.resize(64 * (sizeof(inotify_event) + NAME_MAX + 1));

    while (true)
    {
        int bytes_read = ::read(fd, &buffer[0], buffer.size());
        if (bytes_read == -1)
        {
            if (errno != EAGAIN)
            {
                print("Fatal error to call read");
                break;
            }

        }

        int offset = 0;
        inotify_event const * event = nullptr;
        for (; offset < bytes_read; offset += sizeof(inotify_event) + event->len)
        {
            event = reinterpret_cast<inotify_event const*>(&buffer[offset]);
            if (event->mask & IN_IGNORED)
            {
                // rewatch
                int wd = ::inotify_add_watch(fd, path.c_str(), IN_CREATE);
                if (wd == -1)
                {
                    print("Unable to rewatch directory");
                    break;
                }
            }

            std::string name;
            std::copy(&event->name[0], &event->name[event->len], std::back_inserter(name));

            int event_value = event->mask & 0xffff;
            callback(event_value, name);
        }
    }
}

int main()
{
    int fd = ::inotify_init1(IN_NONBLOCK);
    if (fd == -1)
    {
        print("inotifiy_init1 failed");
        return errno;
    }

    int wd = ::inotify_add_watch(fd, path.c_str(), IN_CREATE);
    if (wd == -1)
    {
        print("inotify_add_watch failed");
        return errno;
    }

    std::atomic<bool> ready;
    std::mutex ready_mtx;
    std::condition_variable condition;
    int first_event = -1;
    std::thread thread([&]()
    {
        thread_fn(fd,
            [&](int event, std::string const & name)
        {
            std::unique_lock<std::mutex> lock(ready_mtx);
            print(std::to_string(event));

            if (event == IN_CREATE)
            {
                first_event = event;
                print(name + " was created");
            }

            condition.notify_all();
            ready = true;
        });
    });

    {
        std::ofstream file(path + "/" + filename);
    }
    {
        std::unique_lock<std::mutex> lock(ready_mtx);

        while (!ready)
            condition.wait(lock);

        if (first_event == IN_CREATE)
            print("success");
        else
            print("failure");
    }

    thread.join();

    return 0;
}


text:
Q: MySQL return 1 row, PHP return 0 with prepared statement I'm getting a super wierd situation. If I run the query in phpMyAdmin, mysql return 1 row but in php I get 0 rows.
I don't understand what is going wrong. Can someone see where the code fails?
$username = strtolower(trim($_POST['username']));
$postpass =            trim($_POST['password']);
//$username = 'mike';

$sql = "SELECT `id`,`username`,`password`,`email`,`phone`
        FROM `users`
        WHERE LOWER(`username`) = ?";

$stmt = preparestmt($db,$sql,'s',array($username));
$res  = $stmt->get_result();

echo $stmt->num_rows.'<br>';

while(list($uid,$username,$password,$email,$phone) = $res->fetch_array(MYSQLI_NUM))
{
...

This is the preparestmt function:
function preparestmt($dbconnection,$sql,$types=null,$params=null)
{
    $stmt=$dbconnection->prepare($sql);

    if($types&&$params)
    {
        $bind_names[]=$types;
        for($i=0;$i<count($params);$i++)
        {
            $bind_name    = "bind{$i}";
            $$bind_name   = $params[$i];
            $bind_names[] = &$$bind_name;
        }
        $return=call_user_func_array(array($stmt,"bind_param"),$bind_names);
    }
    if($stmt->execute()->connect_error) sqlerror($dbconnection,$sql);
    return $stmt;
}

This is what a print_r retun on $stmt
mysqli_stmt Object
(
    [affected_rows] => -1
    [insert_id] => 0
    [num_rows] => 0
    [param_count] => 1
    [field_count] => 5
    [errno] => 0
    [error] =>
    [error_list] => Array
        (
        )

    [sqlstate] => 00000
    [id] => 1
)

This is the table in MySQL:
CREATE TABLE `users` (
    `id`         int(1)       UNSIGNED                   NOT NULL AUTO_INCREMENT COMMENT 'Unik räknare',
    `username`   varchar(250) COLLATE  utf8_general_ci   NOT NULL                COMMENT 'Användarnamn',
    `name`       varchar(250) COLLATE  utf8_general_ci   NOT NULL                COMMENT 'Namn',
    `familyname` varchar(250) COLLATE  utf8_general_ci   NOT NULL                COMMENT 'Efternamn',
    `password`   char(60)     COLLATE  latin1_general_cs NOT NULL                COMMENT 'Lösenord',
    `email`      varchar(250) COLLATE  utf8_general_ci       NULL                COMMENT 'E-post',
    `phone`      varchar(12)  COLLATE  utf8_general_ci       NULL                COMMENT 'Telefonnummer',
    PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;

INSERT INTO `users` (`id`, `username`, `name`, `familyname`, `password`, `email`, `phone`) VALUES
(1, 'Mike', 'Miky', 'Mark', '$2y$11$s9ooqquV123QCI4MLKAjUuH8OoYqW.F4f/UVfetBbFqe/hKVVXe9K', 'try.to@guess.it', '0100123456');

This is the query that return 1 row in phpMyAdmin
SELECT `id`,`username`,`password`,`email`,`phone`
FROM `users`
WHERE LOWER(`username`) = 'mike'

A: What I was trying to do but hade staered me blind to. Sorry for bothering you with stuff thats not a real problem. Changed $stmt->num_rows; to $res->num_rows;
$res  = $stmt->get_result();
$rows = $res->num_rows;


text:
Q: g++ fatal error no such file or directory So I am using the gvim editor to program in C++, however when I open a .cpp file on the editor then type :!g++ -std=C++17 file.cpp -o file I get this error:
See attached file below:

C:\Windows\system32\cmd.exe /c(g++ -std=c++17 file.cpp - o file)
g++: error: file.cpp: No such file or directory
g++: fatal error: no input files
compilation terminated

Now is this related to vim, or to my command?
Thanks in advance.

A: It seems that you're unfortunately using gcc-mingw that doesn't come with gnumake properly configured (:let $CXXFLAGS='-std=c++17 -Wall -Werror'+ make %< would have been enough otherwise). Thus you'll have a do a few things manually. And don't misspell the parameters to g++. And forget :!{compilername}, this is want we had to do 25 years ago with vi. Unlike vi, vim permits to integrate compilation.
" to do once
:let &makeprg='g++ -std=c++17 -Wall -Werror % -o %<'

" to execute each time to compile
:make
:copen

" to navigate the errors
:cc      " jump to error under cursor
:cnext   " jump to next error
:cprev   " jump to previous error
:cclose  " close the quickfix window

-> :h quickfix
This shouldn't execute g++ from the wrong directory. If this still does, run :cd %:h.
The execution should work with :./%.
And if you wish to have hot keys for that...
nnoremap <silent> <F7>   :<c-u>update<cr>:make<cr>
nnoremap <silent> <C-F5> :<c-u>./%<cr>

nnoremap <silent> <F3>   :<c-u>cnext<cr>
nnoremap <silent> <S-F3> :<c-u>cprev<cr>

Automatically opening the quickfix windows only if there are errors or executing the result only if there are no errors requires a little more work.


text:
Q: With MPI are user-defined datatypes useless when there is a contiguous array? In my program I send to the other processors some rows of a Matrix, I'm coding in C and I know that C is row-major.
The matrix is allocated as 1d array.
matrixInArrayB = malloc(height * width * sizeof(int));
matrixB = malloc(height * sizeof(int*));
for (int y = 0; y < height; y++) {
    matrixB[y] = &matrixInArrayB[y * width];
}

I send them in this way
MPI_Isend(&matrixB[0][0], width * height, MPI_INT, dest, tag,
          MPI_COMM_WORLD, &requestesForB[k]);

My doubt concern if I have to use some datatype ad-hoc to ensure the contiguity of the rows, like:
 int MPI_Type_contiguous(int count,
                      MPI_Datatype oldtype,
                      MPI_Datatype *newtype)

A: No, you don't need to define your own datatypes if you don't want to.  However, properly used, they can be very useful.

Let's say you have the following structure to describe your matrix, rather than an array of pointers to rows of data:
typedef struct {
    int      rows;
    int      cols;
    ssize_t  rowstep;
    ssize_t  colstep;
    int     *data;
} matrix;

where data element on row r, column c of matrix m is m.data[r*rowstep + c*colstep].  I've outlined an even better version of this structure in this answer.
Then, you can use MPI_Type_create_hvector() to create types corresponding to a row, a column, or main diagonal, of this particular type of matrix (specific size and step):
int  n = (m.rows <= m.cols) ? m.rows : m.cols; /* min(m.rows, m.cols) */

MPI_Type_create_hvector(m.rows, 1, m.rowstep * sizeof m.data[0],
                        MPI_INT, &row_vector_type);
MPI_Type_create_hvector(m.cols, 1, m.colstep * sizeof m.data[0],
                        MPI_INT, &col_vector_type);
MPI_Type_create_hvector(n, 1, (m.rowstep + m.colstep) * sizeof m.data[0],
                        MPI_INT, &diag_vector_type);

To refer to row r, you use m.data + r*m.rowstep.
To refer to column c, you use m.data + c*m.colstep.
To refer to the main diagonal, you use m.data.
The size field is always 1, because you send/receive individual rows or columns.
It is also possible to define datatypes corresponding to any continuous rectangular part of the matrix as well.
The MPI library will then gather the data on a send, and scatter the data on receive. The actual data items do not need to be consecutive in memory.

In the above example, one can use the same code to send and receive any row, column, or diagonal vector.  Using custom datatypes, one does not need to differentiate between them, aside from defining the types as shown above.
Simplifying code tends to yield more robust code, with fewer errors. (You could say that bugs are either of the off-by-one type, i.e. hard to spot but not complicated, or of the complicated type, where different aspects of the code interact in an unexpected or inadvertent way to cause the bug.)
So, I would say user-defined MPI datatypes are not useless even when the data is in a contiguous array, because they can be used to simplify the code, and thus make it more robust and easy to maintain.
Obviously, not all MPI code uses user-defined MPI datatypes well. Using user-defined datatypes whenever possible is definitely not the solution.
My point is, you determine the usefulness on a case-by-case basis, depending on whether you can make the code simpler, easier to read, and robust or not.


text:
Q: Android Studio Bumblebee | 2021.1.1 Patch 1 Generate Signed Bundle / APK wizard does not open I have upgraded to Android Studio Bumblebee | 2021.1.1 Patch 1, and noticed that after a number of successful builds on my stagingRelease apk the Generate Signed Bundle / APK wizard does not open
this the version of android studio i am using
Android Studio Bumblebee | 2021.1.1 Patch 1
Build #AI-211.7628.21.2111.8139111, built on February 1, 2022
Runtime version: 11.0.11+0-b60-7590822 x86_64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.
macOS 10.15.7
GC: G1 Young Generation, G1 Old Generation
Memory: 4096M
Cores: 12
Registry: external.system.auto.import.disabled=true, debugger.watches.in.variables=false
Non-Bundled Plugins: org.jetbrains.kotlin (211-1.6.10-release-923-AS7442.40)

none of the actions i have tried have rectified this issue
i have tried closing and reopening android studio
invalidating caches and restarting
what is the solution to this issue?


text:
Q: Error ITMS-90062: The value for key CFBundleShortVersionString must contain a higher version than that of the previously approved version I am trying to update my app for the first time and ran into this issue. I searched a lot but none of the solutions worked for me.

App Store Connect Operation Error
ERROR ITMS-90062: "This bundle is invalid. The value for key CFBundleShortVersionString [2020.0] in the Info.plist file must contain a higher version than that of the previously approved version [2020.0]. Please find more information about CFBundleShortVersionString at https://developer.apple.com/documentation/bundleresources/information_property_list/cfbundleshortversionstring"

And my info.plist file is :

General Window:

A: I think it was some issue on Apple's side. It resolved itself automatically after few hours.

A: What worked for me is to change it from 1.0 (.6) to 1.1 (.0) It's not really a new "Version" but incremental improvements and corrections. One thought is that when an app is accepted into the iTunes store then next upload must be to a higher VERSION.

A: TL;DR: If you have an app version that was approved for the official app store, you cannot upload a build with the same version to TestFlight.  You have to remove the app from official app store submission, or increase your TestFlight version #.
I figured out why this happened to me.

*

*I have an app in the app store with version 2010.

*I have been running an external beta test with version 2020, and build numbers in the range of 400-410

*In order to discover if my app would get rejected in the app store once I'm ready to actually release it in a few weeks, I submitted version 2020, build 407 for official app store review.  I expected it to be rejected for various reasons.  It was approved!  However, i'm not ready to release it since I still have more fixes I want to implement.  So, I let it sit there, waiting for me to do something with it.

*Then, I wanted to upload a newer build for my External beta, still version 2020, build 410, and I received this error.

*Thanks to user462990's answer, I realized that the error could be due to the fact that I have version 2020 currently approved and waiting to be launched into the official app store, so iTC didn't allow me to submit the same build # for a TestFlight external beta.
So, I selected "cancel this release" of the official approved version, and Viola!  I can now upload a build with the same build #.

A: You must always increase the version number when uploading updates, so change it from 1.0 to 1.1.

A: I'm having a similar issue today. I uploaded a new build a couple days ago with no issues. I found someone who posted a similar issue here: https://discussions.apple.com/thread/7297092. They were able to resolve it by changing the Info.plist values in their sub-projects, however, I tried doing that, and I still ran into the same issue.
I cannot find any information on why this is occurring or when this started, but I know that I uploaded a prerelease build to TestFlight with all of the same projects 5 days ago.
I currently increment my prerelease builds this:
1.10 (1) -> CFBundleVersionShortString (CFBundleVersion)
1.10 (2)
...
I was up to 1.10 (7), which I deployed 5 days ago. Now, I can't get anything to work 1.10 (8), 1.10 (9), 1.10 (1.10), etc. They all say "CFBundleShortVersionString [1.0] must be greater than previously approved version [1.3]"
1.3 is correct as the previous version available in the store, but clearly, 1.0 as the Bundle version is not.

A: I ran into this issue when going from version 1.141 to version 1.15.  Apple does not treat the version as a decimal number - they treat it as multiple integers separated by periods.  Thus in my case Apple considered 1.141 to be Major version 1, Minor version 141 and then my new version was Major version 1, Minor version 15.  Since 141 > 15 it fails.
Two options to deal with this:

*

*Use Apple's interpretation of version numbers, so you always increment the minor version by 1: 1.1, 1.2, ... 1.9, 1.10, 1.11.

*If you wish to use "hundreds" or "thousands" places (I do, as I try to encode the scope of the build in the precision - I use the thousands place for minor bug fix releases), then always pad them out with zeros: 1.10, 1.11, 1.20, 1.30
So in my case I went from 1.141 to 1.150 and I was able to upload.


text:
Q: Script cannot get calculate with element assigned to const I'm trying to modify a cart of a shopify store. It's using a bundle application, which overwrites the prices in the cart, hence I'm trying to get those overwrited prices and calculate with those, in order to be able to display how much the customers are saving with the discount. My code is like this:
<script>
          const original_price_for_product_range = document.getElementsByClassName("revy-line-item-price__old");
          const a = original_price_for_product_range[0].outerText;
          const c = a.replace("€","");
          const d = c.replace(",",".");
          const old_price_for_product = +d;

          const discounted_price_for_product_range = document.getElementsByClassName("revy-line-item-price__new");
          const b = discounted_price_for_product_range[0].outerText;
          const f = b.replace("€","");
          const g = f.replace(",",".");
          const new_price_for_product = +g
</script>

Basically I'm getting the old and new price by their class name and then getting the first element out of that array and converting it to a number, I can calculate with. (outer text to get the first price, then removing the € and then replacing , with . so I can convert the text to a number, which I can do calculations with).
My problem is that after getting the elements by their class name, ALL following process just WON'T run, getting "Uncaught ReferenceError: a is not defined at <anonymous>:1:1" errors.
I was expecting the code to get the array first element and convert it to number given the script's code, but it's not working. Can anyone help out with this?


text:
Q: How to easily duplicate a Windows Form in Visual Studio? How can I easily duplicate a C#/VB Form in Visual Studio? If I copy & paste in the Solution Explorer, it uses the same class internally and gets messed up. How do you do it?

A: I have been using another way of copying forms since vb6.

*

*File Menu / SE - Save CurrentForm.cs as - NewForm.cs

*Change its Name to NewForm in Properties window.

*In Solution Explorer - Add Existing Item - CurrentForm.cs

*Usually in MDI form (where CurrentForm is referred) - CurrentFormToolStripMenuItem_Click event - change reference back to CurrentForm (which is automatically changed to NewForm in step 1).

comments welcome.

A: I usually copy the files in windows explorer, open them up in Notepad/Wordpad and just change the one mention of the class name at the top. Include those files in your project, and you'll be good to go.

A: *

*Add a sub-folder to your project.

*Right-click on the sub-folder, and click Add Existing Item.

*Browse to the form you want to copy, and select its .cs file.  This will duplicate the original form (partial and resx and all) in the sub-folder.  The name will not conflict with the original, because the sub-folder will be included in its namespace.

*Right-click on the .cs file, click Refactor | Rename and enter the new name.  This will also rename the partial and the resx for you.

I'm generally averse to methods of doing this that involve opening up the files in notepad or whatever, since I always think a common task like this should have a built-in way of doing it in Visual Studio.  In this case, there is.

A: First of all, if you're duplicating a lot of forms with cut and paste, consider a common base class for your forms (or for a category of your forms) that implements shared/common functionality or look & feel elements.  You can also create a template for new forms that meet your needs and create new forms from that template.
Personally I just cut and paste then fix any lingering name errors.  Since I abstract out common functionality, I have not felt enough pain to look for a better way ;-)

A: *

*Copy and paste the form.

*Rename the pasted form .cs to match the new form class name.  This should auto rename other related files.

*Open up .cs file.  Change the class name and the name of the constructor(s) and destructor.

*Open up .Designer.cs file and change the class name.

Extra Credit:

*Consider abstracting common functionality from the form into common form or controls.

A: *

*Right-Click on Form -> Copy Class

*Right click on destination Folder and Paste Class

*Rename new Form and say yes to renaming all references to this class.

A: If you're working in VS 2019, take a few minutes to create an item template -- it's a perfect solution.  How to: Create item templates
Not sure if it applies to earlier versions of VS.

A: Secured way without problems is to make Template of your form
You can use it in the same project or any other project. and you can add it very easily, such as adding a new form . Here's a way how make Template
1- from File Menu click Export Template
2- Choose Template Type  (Choose item template ) and click next
3-Check Form that you want to make a template of it, and click next Twice
4-Rename your template and (put describe , choose icon image ,preview image if you want)
5-click finish
Now you can add new item and choose your template in any project

A: *

*Press "Ctrl" and drag your mouse to duplicate a existing form class file.

*Then exlude the existing form class file from the project.

*Rename the new form class file. Go to code behind, rename the class name
and its related reference together.

*Include back the previous existing form class file of project

*Done

A: Just rename the class the designer references.
But a better solution is to create a new instance of the same class at run time.
Or better yet, create a parent form that various implementations inherit from.

A: 1.Add a new folder to your project
2.Copy the form into that
3.Change the name in properties as well as change the file name
4.Check each form for their class name (they shouldn't be same)

A: (replicated this answer from my other post in case someone is looking for this solution here)
Using VS2013 just tested this and it appears reliable and consistent.  This is similar to some comments above but adds another method that's quicker.
(1st) In Windows File Explorer highlight and copy all 3 Form files (.vb or .cs, .designer, .resx)
(2nd) This can be accomplished 2 ways:
(2a-1) In File Explorer paste the 3 files into the project folder with your other forms
(2a-2) In VS Solution Explorer, turn 'Show All Files' on, Right Click on the pasted form & 'Include in Project'.  It should work without other changes.
Or, I think better:
(2b-1) In VS, click into Solution Explorer and paste w/Control-C. (For some reason the right-click context menu in Solution Explorer may not show a paste option, but it works from the keyboard.)  This method adds the form to the project directly without having to 'Include in Project' as above.  With this method you can add as many forms at a time as you like (all 3 files for each) in a single step.

A: Its Really Easy. "In Design mode FORM"  (form1.cs[Design])  copy the whole Form "ctrl A" then  ctrl C. All objects at once.   Then add a new windows form to the project. Change the size of the form to the size that you want then paste ctrl V all of the new objects will be copied to the new form. When they are all still picked double click on any of the objects.   NOT THE FORM!!!..... This will create the code on the Form side matching the objects you just pasted. if it doesn't you can double click on each object and it will create the code one at a time. I use a text box area to double click in and it works almost every time.
I use this method everyday WORKS GREAT.

A: *

*Save the all project

*Right click in the Solution Explorer (SE), "Copy"

*Right click on the project name in the SE (this is the first line), "Paste". It will create a "Copy of .....vb" form

*Right click on this new form in SE, "View code", and change its class name to the name, that you wanna use for the Form

*Left click on the new form in SE and rewrite its name for the one, that you used in the class name (and .vb in the end)

*Build - if it has no error, you win! :)

A: This process may take one or two minutes...

*

*Create a new project.

*Copy the form's files to the new project's folder.

*Include the form in the new project.

*Rename the form.

*Rename its class name in the code behind file.

*Rename constructor name in the code behind file.

*Rename class name in the designer file.

*Bring the changed form's files back in the folder of original project and include it.

A: Inherit the form!


text:
Q: How to convert json date from /Date.../ to actual datetime when being returned from jsonresult? I am querying my database and returning a jsonresult, and using that to populate a grid, and I see that my date being returned is /Date(1507477743793)/. I have looked around and have seen solutions when it comes to converting one variable but not when it comes to an array of objects (I think thats right)
EDIT
Sample data
FileAReportID:1
ReportAddress:"1 Main Street West"
ReportDate:"/Date(1507477743793)/"
ReporterName:"Beetle Bailey"

A: This number 1507477743793 is the timestamp from your server. to conver this in other format just try this:
let t = (new Date(1507477743793)).toUTCString();
console.log(t)

// output
and you get: 2017/12/6 05:32:30pm

A: You can create custom jsonresult
public class CustomJsonResult : JsonResult
{
    private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            // Using Json.NET serializer
            var isoConvert = new IsoDateTimeConverter();
            isoConvert.DateTimeFormat = _dateFormat;
            response.Write(JsonConvert.SerializeObject(Data, isoConvert));
        }
    }
}

Usage Example:
[HttpGet]
public ActionResult Index() {
    return new CustomJsonResult { Data = new {  }  };
}

You can also create custom  MediaTypeFormatter formatter and during serialization you can change the format of datetime.
Update
Json.Net supports multiple ways of formatting a date, if your  consuming it from an ajax call you may want to look into JavaScriptDateTimeConverter.
Serializing Dates in JSON


text:
Q: What is the formula for working out the volts, amps and watts of a DC Motor? Can anyone remind of the correct way of working out the volts amps and watts on a DC motor?
I know it is something like:
\$ V=I \times R \$
\$ I=\dfrac{V}{R} \$
\$ W=\dfrac{V}{I} \$
or something like that...
So, basically, to get the answer of one you multiply or divide the other two? I forget what order it goes in.

A: The power of a motor is the product of its speed and torque. The power output is greatest at about half way between the unloaded speed (maximum speed, no torque) and the stalled state (maximum torque, no speed).
The output power in watts is about (torque) x (rpm) / 9.57.
The efficiency of a motor η = Shaft Power Out/Electric Power In
Ref:http://www.me.ua.edu/me416/LECTURE%20MATERIALS/MotorEffic&PF-CM5.pdf
(vector) Input Power = V·I and Loss = I²R
If you can measure real power V*I but cannot measure HP, assume 87~90% for  η

A: Is your motor functioning?
Do you have any data belonging to the scooter model? (If yes, you may be able to find the motor used, and access the datasheet).
There are TWO major powers that are of concern with motors. THE FIRST is the input electrical power. This power, also known as Pin (because it's the input power), is:
P = VI, where P is in Watts, if V is volts and I is in Amperes.
The OTHER power is the motor output MECHANICAL power (that is, the mechanical rotational power the motor exerts). This is:
P = T*w, where T is torque (in N.m (Newton-Meters)), and w is angular velocity (in radians/sec). P is then in Watts. If you're American, you may want to use RPM and H.P.
In this case, use an online converter, or look at what torque/rotational units you need to use.
The two powers are not the same. The MECHANICAL power will always be LESS than the input electrical power (due to the second law of thermodynamics), and the ratio of the two:
n = Pout/Pin, where the same units are used for P, and Pout is mechanical power.
n will change depending on the loading (how difficult it is to turn whatever's attached to it) and the voltage applied to the motor. But assume 24V, if there seems to be no other voltage control in your scooter.
If you do some simple experiments, find the speed-torque curve of your motor (assuming it still runs). Do this by finding the torque (applied load) that makes the motor stop moving. This is one data point. Next, find another data point between the load and the speed.
Since the relationship between the torque applied to the motor and the speed of the motor is ideally linear, you can use this characteristic to find the LINEAR relationship between the torque applied, and the speed of the motor. If you like, make a line of best fit.
Since the OUTPUT power of the motor is the torque times the rotational velocity. You can generate an output power parabola as well. From all this data, should definitely find a motor (given a motor's spec. sheet provides motor curve info) that matches your application. Just make sure the current of the new motor isn't too much higher.


text:
Q: How to pass JSON to Redux -> React Component I am building an app from this boilerplate: https://github.com/werein/react
I am hitting an API that requires a Secret Key, so I am going to Fetch the JSON via Express (server.js) and pass it to my component as props.
How do I glue everything together to get the JSON in as props?
I tried just to pass some Dummy JSON
app.get('yourinfo', (req, res) => {
  res.json({ 'a': 'Some JSON' });
});

  <ConnectedRouter history={history}>
    <Layout>
      <Match exactly pattern="/yourinfo" component={App} />
    </Layout>
  </ConnectedRouter>

And I don't get anything rendered in when I inspect this.props.
Any ideas?

A: Remember when using redux that your application's state is stored in the redux state. And all changes to the state are done through actions which are dispatched.
So, to save your API key in your application's state, just create an action & dispatch it:
// the "save API key" action
export function saveAPIKey(key) {
  return {
    type: APP_APIKEY,
    key,
  };
}

// to use the loadAPIKey action, dispatch it
import store from './store/store';
import { saveAPIKey } from './path/to/actions';

fetch('/my/api/endpoint')
  .then((response) => response.json())
  .then((data) => store.dispatch(saveAPIKey(data.key)));

That's the basic idea, but there is a simpler way of doing it. If you read through the redux docs on async actions you'll see that you can use the redux-thunk package to create an action that behaves asynchronously. It looks a little more complicated, but it has the advantage of putting all the code handling the asynchronous actions in one place, rather than spreading fetch calls throughout your code.


text:
Q: devise before_action: Verify reCaptcha before a user is created I'm trying to set up reCaptcha with Devise and I want to add a filter that checks if verify_recaptcha is true before allowing a user to be created. If it's false, the user should not be created.
I've tried to follow Devise's documentation on how to do it, but it doesn't seem to work in my case. I'm testing recaptcha in production mode too, and the general setup works and I can check if reCaptcha is true or false.
This is what Devise tells me to do in the RegistrationsController:
prepend_before_action :check_captcha, only: [:create] # Change this to be any actions you want to protect.

private
def check_captcha
  unless verify_recaptcha
    self.resource = resource_class.new sign_up_params
    respond_with_navigational(resource) { render :new }
  end
end

Didn't work. Im 100% sure the verify_recaptcha method works and it's not something wrong with the setup.
I've tried:
class RegistrationsController < Devise::RegistrationsController
    before_action :check_captcha

  private
    def check_captcha
      if !verify_recaptcha == true
        flash[:recaptcha_error] = "Fejl. Husk at sætte flueben i at du ikke er en robot"
        signupuser_users_path
      end
    end

end
But no luck. How would I do this? Where does devise normally handle validation methods to be run before a user is signed up??

A: Made it work eventually by changing a tiny part of devise's method:
prepend_before_action :check_captcha, only: [:create] # Change this to be any actions you want to protect.

private
def check_captcha
  unless verify_recaptcha
    self.resource = resource_class.new sign_up_params
    respond_with_navigational(resource) { redirect_to :back }
  end
end

I guess what's behind devise is a little too advanced for me to roll with my own method, but a little tweak made an okay solution

A: You can use javascript validation
<%= submit_tag "Sign Up", :onclick => "return validatecaptcha();" %>

A: class Users::RegistrationsController < Devise::RegistrationsController

  def create
    if !verify_recaptcha
      flash.delete :recaptcha_error
      build_resource(sign_up_params)
      resource.valid?
      resource.errors.add(:base, "Recaptcha verification failed, please try again.")
      clean_up_passwords(resource)
      respond_with_navigational(resource) { render :new }
    else
      flash.delete :recaptcha_error
      super
    end
  end


text:
Q: Flutter plugin that uses .aar modules builds and runs fine in the example app but fails to build in a different app I've written a Flutter plugin to use an SDK that requires the inclusion of some .aar modules. It builds and runs perfectly in the example app for the plugin, but when I import the plugin in a different app and try to build it, the build immediately fails with a message saying that one of the .aar modules could not be found in the plugin. This makes no sense because the module is definitely there - the platform channels to use the SDK would fail in the example app if the module wasn't there.
Why would the example app build and run without any problems but a different app won't? The only thing I can think of is that I import the plugin from path in my pubspec but it seems unlikely to me that this is the culprit.
Any advice or assistance here would be appreciated. TIA!

A: I got it!!!!
The answer is as found here: How to add .aar dependency in library module?
The way this adapts to a Flutter plugin is as follows:

*

*Add a libs folder at the root of the android project in the plugin. Add the .aar files there.

*In the plugin's build.gradle file, update rootProject.allProjects to look as follows:

    repositories {
        google()
        jcenter()
        flatDir {
            dirs 'libs'
            dirs project(':your_plugin_name_here').file('libs')
        }
    }
}

*Still in the same build.gradle, add your .aar file(s) as dependencies as follows:

implementation(name:'aar_name_here', ext:'aar')

*In the Flutter app that you want to use the plugin for, open the app-level build.gradle file and add the plugin itself as a dependency, like so:

android {
  ...

    dependencies {
        implementation project(':your_flutter_plugin');
    }
}

*In the settings.gradle file for the app that us using the plugin, change

include ':app'

to
include ':app', ':your_flutter_plugin'

And this should do it!!


text:
Q: X server. How to know the screen number application was connected to? Is it possible to know the X11 screen number the application was connected to?
I know that if NULL is passed to XOpenDisplay, one can obtain the default screen number. But if application was connected to some display with some screen number, how to obtain the number?
For now I parse the display connection string to obtain the screen number. Maybe there are a function for that?


text:
Q: Automation Testing using VMSS Agent Does anyone here have tried using VMSS as their agent in ADO and was successful?
I did a POC on this for our company and it seems to be promising. Before we are using a MS Hosted agent. However, the MS agent has limitation as we can't access some certain sites on it due to IP restrictions, thus we are trying to move to using VMSS.
To those who have tried and tested, what would be the Pros and Cons? And is there a better alternative? Thanks

A: Pros: VMSS Agent can be autoscaled to meet your demands. This elasticity reduces your need to run dedicated agents all the time. Unlike Microsoft-hosted agents, you have flexibility over the size and the image of machines on which agents run. When I queue a build it will create an agent and destroy this agent when done.
Cons: You cannot run Mac agents using scale sets. You can only run Windows or Linux agents this way.
Please refer for more information about VMSS agent  here.
Reference:- https://www.reddit.com/r/azuredevops/comments/pjlq9y/automation_testing_using_vmss_agent/


text:
Q: XAMPP Port changes so frequent. Every second I have a issue with my XAMPP, PhpStorm. No idea what is the reason, I am not an expert. Please advise if you have any idea.
My PHP projects on my local host was working fine till yesterday night. But today morning it stopped working.
It's working on my server. When I checked my XAMPP the port number is 63342 at start. It was like that for several months. And it's constant for all the time. But now when I try to run a project on PhpStorm then my XAMPP ports starts fluctuating so frequent. It keeps on changing so fast. Every second new port number showing. It's only happens when PhpStorm project is started.
Is it the issue with PhpStorm or XAMPP? I am new. If I reinstall XAMPP will it be fine? Or is it with the issue with my PhpStorm.
My PhpMyadmin is working fine even when the port number changes. I don't want to do any thing with out an expert opinion. I am not sure what the problem is.

A: I guess any other software or application is using the port .
Check on your xampp configuration file check for port and change it . To check which app is using the port go to task manager for windows and check for port.
If helps you can reinstall the xampp
Try checking port numbers in task manager and change the port in the conf file of xampp


text:
Q: Sleeping php processes (mod_fcgid) counsuming RAM rapidly I hope that this is the right place to ask this question, so:
We are running a Debian (virtualized) server with Apache running php as fcgi. Today the administrator told me that the processes are consuming the RAM on the system. He asked me to look around my code.
Well I think that virtually I have no control over the php processes since Apache spawns them, so this seems more like a server configuration problem. It seems that every request spawns a new php process (this is ok). After my script terminates the php process goes to sleep.
This is what top looks like. I sorted by memory and these are the php processes (they run on the user edem):
top - 14:49:35 up 41 days,  2:09,  2 users,  load average: 0.16, 0.13, 0.06
Tasks: 228 total,   1 running, 227 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.7%us,  0.3%sy,  0.0%ni, 98.7%id,  0.0%wa,  0.0%hi,  0.3%si,  0.0%st

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
12358 edem      20   0 67380 6464 2976 S  0.3  0.2   0:00.06 php
12250 edem      20   0 66960 9776 6584 S  0.0  0.3   0:00.11 php
12253 edem      20   0 67480 7812 3832 S  0.0  0.3   0:00.19 php
12254 edem      20   0 67464 7108 3316 S  0.0  0.2   0:00.07 php
12255 edem      20   0 67404 7340 3604 S  0.0  0.2   0:00.14 php
12256 edem      20   0 67464 7128 3336 S  0.0  0.2   0:00.07 php
12257 edem      20   0 67380 6484 3000 S  0.0  0.2   0:00.04 php
12258 edem      20   0 67464 7092 3312 S  0.0  0.2   0:00.05 php
12259 edem      20   0 67464 7184 3392 S  0.0  0.2   0:00.07 php
12260 edem      20   0 67464 7088 3296 S  0.0  0.2   0:00.06 php
12263 edem      20   0 66960 9780 6584 S  0.0  0.3   0:00.11 php
12265 edem      20   0 67464 7084 3280 S  0.0  0.2   0:00.09 php
12266 edem      20   0 67436 7376 3600 S  0.0  0.2   0:00.14 php
12267 edem      20   0 67464 7144 3340 S  0.0  0.2   0:00.06 php
12268 edem      20   0 67380 6508 3016 S  0.0  0.2   0:00.05 php
12269 edem      20   0 67540 7672 3820 S  0.0  0.2   0:00.22 php
12270 edem      20   0 67496 6488 3040 S  0.0  0.2   0:00.05 php
12271 edem      20   0 67436 7372 3596 S  0.0  0.2   0:00.15 php
12272 edem      20   0 67464 7108 3304 S  0.0  0.2   0:00.07 php
12277 edem      20   0 66960 9776 6584 S  0.0  0.3   0:00.11 php
12279 edem      20   0 67436 7368 3596 S  0.0  0.2   0:00.15 php
12280 edem      20   0 67464 7096 3296 S  0.0  0.2   0:00.07 php
12281 edem      20   0 67464 7748 3808 S  0.0  0.2   0:00.18 php
12282 edem      20   0 67496 7388 3600 S  0.0  0.2   0:00.14 php
12283 edem      20   0 67380 6464 2976 S  0.0  0.2   0:00.04 php
12284 edem      20   0 67380 6464 2976 S  0.0  0.2   0:00.05 php
12285 edem      20   0 67464 7168 3368 S  0.0  0.2   0:00.07 php
12286 edem      20   0 67464 7104 3304 S  0.0  0.2   0:00.06 php
12287 edem      20   0 66960 9780 6584 S  0.0  0.3   0:00.11 php
12289 edem      20   0 67464 7140 3336 S  0.0  0.2   0:00.07 php

Do you have any ide how to kill those sleeping (idling) php processes? Is there something I'm doing wrong?

A: edem, I think you shouln't kill em. As fastcgi idea not to spawn new processes. See http://en.wikipedia.org/wiki/FastCGI#Implementation_details

Instead of creating a new process for each request, FastCGI uses persistent processes to handle a series of requests. These processes are owned by the FastCGI server, not the web server.

As a workaround you can try to play with your webserver fcgi settings to for example reduce "sleepin" number. Also I think your admin tells you about some peak usage, but we don't see it here, as you top your memory in possible calm time.


text:
Q: Cannot retrieve selected radio button value in PHP form post I am unable to get the selected radio button value in a form post.  No matter which option I select, I am getting the value "on".  Note this is in a Wordpress Plugin Options page.
Code for form below:
?>

    <?php screen_icon(); ?>

Title

    <form action="options-general.php?page=page" method="post">

            Site Name
            Site URL
            Username

            Site Name
            Site URL
            Username

    <?php

    $size = count($sites);

    for ( $i = 0; $i < $size; $i++) {

        echo '
';

        for ($j = 0; $j < 4; $j++) {
            if ($j == 0) {

            echo '<input type="radio" id="cta_siteID_'.$i.'" name="cta_siteID",value="'.$i.'"/>	';

            }
            else
            {

                echo ''.$sites[$i][$j-1].'	';
            }
        }
        echo '
';
    }
    ?>

   <input type="hidden" name="formType" value="main" />
   <select name="selectedItem">
        <option value="" selected="true">Select an Option</option>
        <option value="add">Add Site</option>
        <option value="edit">Edit Site</option>
        <option value="delete">Delete Site</option>
   </select>
   <input type="submit" name="Apply" value="Apply" class="button-primary" />
   </form>

When I do a var_dump($_POST) after selecting an item in the radio group, I get the following:

onarray(4) { ["cta_siteID"]=> string(2) "on" ["formType"]=> string(4) "main" ["selectedItem"]=> string(4) "edit" ["Apply"]=> string(5) "Apply" }

The values are being rendered correctly in the HTML before posting the form, not sure what is going on.
The "on" value shows up no matter which radio option I select, and does not show up at all if none is selected (as I would expect).

A: You shouldn't have a comma inside your input tag:
name="cta_siteID",value=

This could well be causing your browser to bork the value being passed.


text:
Q: get value in an element dynamically using DOM in javascript Dear all, my issue is this.
I have like the alert box to display all the text I have in a  element. May I know how I can do it?
My ori idea:
testing

function displaytext(something){
  alert(something);
}

Can someone please help me to solve this? Thanks.

A: Use innerHTML (or innerText if you don't want the HTML) and this:

testing

A: Use the innerHTML attribute, after you've gotten the object using getelementbyid or similar.

A: If you are just wanting to display the text you should use innerText
Live example
HTML
testing

I'll display the div innerText

I'll display the div innerHTML

Some sample text here

JavaScript

A: you should use a simple function like this. but be careful this function takes an element id so this will not work for a class name or a element name.

function sayText(elId) {
    var html = document.getElementById(elId).innerHTML;
    if (html != null) alert(html)
}


text:
Q: Java opencv unblur part of image around the mouse cursor I have an image on which gaussian blur is applied through this code
try {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        Mat im = Imgcodecs.imread("bin\\" + backImage[randNum]);
        Mat dst = new Mat();
        Imgproc.GaussianBlur(im, dst, new Size(55, 55) ,8 , 8);
        Imgcodecs.imwrite("bin\\gauLock.jpg", dst);
      } catch (Exception e) {
         dispose();
      }

Now I want to unblur the area around the mouse cursor
Somewhat like this
So my questions are

*

*Is this possible?

*Can this be done using only opencv?

*If yes then how?