text:
Q: Reading Outbound messages from HTTP Streaming Connection in JAVA I am implementing an integration client which will be connected to an API Gateway and send requests to the gateway. In short, I am the consumer of the API.
Now, the architecture the opposite party has built that I have to open a http streaming connection and read the outbound messages sent by the system.
In case of http streaming connection, it will be automatically closed if kept on idle state for a while so we have to send continuous heart-beat request to the system so that the stream connection shall stay alive.
Now I have following queries:

*

*Do I have to use URLConnection.openConnection to open streaming channel?

*How can I keep the stream open by sending requests? Do I have to open a separate thread for achieving this?

*What are Outbound messages? Is the term refers to the responses I receive from the API?

*How can I test it before getting actual testing setup? is there any dummy test case available on the internet where I can open stream and read data? if yes, please suggest any link?
I have to read JSON Data.
I have been provided with following Example Code for HTTP Streaming
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;

import javax.ws.rs.core.HttpHeaders;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;

/** * Sample on Java * Open stream and start StreamReader to read stream in separate thread */

/** * Sample of stream processing */

public class StreamReader implements Runnable {

    private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
    final private BufferedReader in;
    final private boolean toConsole;
    final private String serviceName;

    private final Crypto crypto;

    StreamReader(BufferedReader in, boolean toConsole, String serviceName, Crypto crypto) {
        this.in = in;
        this.toConsole = toConsole;
        this.serviceName = serviceName;
        this.crypto = crypto;
    }

    @Override
    public void run() {
        String inputLine;
        try {
            stop:
                while (!Thread.currentThread().isInterrupted()) {
                    try {
                        while (!StringUtils.isEmpty(inputLine = in.readLine())) {

                            if ( inputLine.startsWith( serviceName + ":" ) ) {
                                log.info("Stream message (outgoing from IPS):");

                                if (toConsole)
                                System.out.println("Stream message (outgoing from IPS):");

                                String[] s = inputLine.split(":");

                            if (s.length >= 2) {
                                log.debug("Encoded:");
                                log.debug(inputLine);
                                log.trace("Decoded:");
                                String decoded = URLDecoder.decode(s[1], "UTF-8");
                                log.trace(decoded);

                                NReply n = Gson.fromJson(decoded, NReply.class);
                                log.info("Readable:");
                                log.info(n.o.toString());

                                if (toConsole) {
                                    System.out.println("Readable:");
                                    System.out.println(n.o.toString());
                                }

                                if (s.length > 2) {

                                    int lastSemicolon = inputLine.lastIndexOf(':');
                                    log.debug("Signed data:");
                                    final String signedData = inputLine.substring(0, lastSemicolon);
                                    log.debug(signedData);
                                    log.debug("base64 encoded signature:");
                                    log.debug(s[2]);

                                    try {
                                        //crypto.checkSignSep(signedData, s[2]);
                                    }
                                    catch (Exception e) {
                                        log.error(e.getMessage(), e);
                                        }
                                    }
                                }
                            else {
                                    log.error("Invalid stream message:");
                                    log.error(inputLine);
                                    if (toConsole) {
                                        System.out.println("Invalid stream message:");
                                        System.out.println(inputLine);
                                    }
                                }
                        }
                            else {
                                log.debug("View's info:");
                                log.debug(inputLine);
                            }
                            if ("CLOSED".equals(inputLine)) {
                                Thread.currentThread().interrupt();
                                break stop;
                                }
                            }
                            Thread.sleep(1000L);
                            }

                        catch (InterruptedException e) {
                            log.error(e.getMessage(), e);
                            Thread.currentThread().interrupt();
                            break;
                        }
                        catch (Exception e) {
                            log.error(e.getMessage(), e);
                            break;
                        }
                    }
                    log.info("polling has been stopped");
                    }
        finally {
            try {
                in.close();
            }
            catch (IOException e) {
                log.error(e.getMessage(), e);
                }
            }
        }

    public void openStream(boolean toConsole) throws IOException
    {
        //final URL stream = new URL (hostName+"/stream");
        final URL stream = new URL ("url");
        final URLConnection uc = stream.openConnection();
        //uc.setRequestProperty(HttpHeaders.COOKIE, "JSESSIONID=" + heartBeat.getSessionId() );
        uc.setRequestProperty(HttpHeaders.COOKIE, "JSESSIONID=" + "SessionIDFROMSERVICE" );
        final BufferedReader in =new BufferedReader(new InputStreamReader(uc.getInputStream()));
        StreamReader reader=new StreamReader(in,toConsole,serviceName,crypto);
        Thread thread=new Thread(reader);
        thread.setDaemon(true);
        thread.start();
    }

}

Any sort of help is appreciated.. :).


text:
Q: Decent way to parse a string for a complex format I am trying to parse Science Bowl questions from a large string.
The general format is as follows:
PART
SUBJECT QuestionType Question goes here.
ANSWER: Answer goes here.

For example, the string might look like this:
A Team Questions 5/7/2014

TOSS-UP
1) PHYSICS Multiple Choice Gravity is 10 m/s^2. How far in meters will an object fired at 10 meters per second travel if it is fired at an angle of 22.5 degrees from the horizontal?
W) 5sqrt(2)
X) 10
Y) 10sqrt(2)
Z) 20
ANSWER: W) 5sqrt(2)

BONUS
1) PHYS Short Answer A proton is which of the following:
1) Fermion
2) Hadron
3) Lepton
4) Boson
5) Baryon
ANSWER: 1, 2, 5

TOSS-UP
2) EARTHSCI Short Answer What is the greatest prime factor of 5^2014+5^2015+5^2016+5^2017?
ANSWER: 13

...more tossup/bonus pairs...

The following regex (simplified version; the real one needs to be generated by a large PHP function) is less than 50% accurate. The goal is to capture each of the components (part, subject, type, question, answer) individually.
/(TOSS-UP|BONUS)\n\s*(?:([0-9]+)[\.\)])?\s*(BIO(?:LOGY)?|CHEM(?:ISTRY)?|PHYS(?:ICS|ICAL(?: SCIENCE)?)?|MATH(?:EMATICS)?|E(?:SS)?(?:ARTH)? ? ?(?:AND)? ?(?:SPACE)? ?(?:SCI(?:ENCE)?)?)\s*(Multiple Choice|Short Answer)\s*([^\n]+)(:?\s*W[\s\S]([^\n]+)\s*X[\s\S]([^\n]+)\s*Y[\s\S]([^\n]+)\s*Z[\s\S]([^\n]+))?\s*\nANSWER[\s\S]([^\n]+)/i

My question is, is there a better way to do this than bashing with a massive regex with tons of capture groups? If not, is there a better way to conveniently write a regex?
Or is the entire paradigm messed up and there's a way to avoid string parsing entirely?
I use plain old PHP (preg_replace) although I can be convinced to switch to something else.
A test file can be found here, if you want: http://www.filedropper.com/compiled11-26-13
Thank you!

redpajama_set_name: RedPajamaStackExchange


text:
Q: DevExpress Report Toolbar not picking up the Report Viewer I set up my reporting page so that it all just rendered out and had no problems at all, everything worked dandy :).
Now the problem comes when I want to render the report when the Run Report button is clicked. This still renders fine, but the toolbar and viewer are not hooked up properly. When I click any of the page navigation buttons (Not the "Go To beginning/end ones) I get a NaN error from the current page index. Now this stuff is auto generated when the report viewer partial is rendered, and as the toolbar is already rendered it seems to have a problem picking it up. Here is my index and ajax call for your reference to see if anyone can help.

Basic Error Report

@Html.Partial("_BasicErrorReportFilters")

<input type="button" value="RunReport" id="runReportBtn" onclick="RunReport()"/>
@Html.DevExpress().ReportToolbar(settings =>
    {
        settings.Name = "ReportViewerToolbar";
        settings.ReportViewerName = "reportViewer1";
    }).GetHtml()

Ajax Call:
$.ajax({
            type: "POST",
            url: '@Url.Action("ReportViewerPartial", "BasicError")',
            data: queryString,
            statusCode: {
                200: function (r) {

                    $('#reportDiv').html(r);
                    var dxo = new ClientReportToolbar('ReportViewerToolbar');
                    window['ReportViewerToolbar'] = dxo;
                    dxo.menuID = 'ReportViewerToolbar_Menu';
                    dxo.reportViewerID = 'reportViewer1';

                    dxo.InlineInitialize();

                },
                400: function(r) {

                },
                500: function(r) {

                }
            }
        });

    }

You'll see that I am re initializing the toolbar in the javascript. Before I put that in, the toolbar would not pick up the viewer at all.
Funilly, once I have had the NaN error, I can use the go to beginning and end buttons properly, and once I have used one of those, all of the navigation/export/print buttons work fine. Thanks in advance for any help.
Cheers

A: I found the issue.
It seems that when reinitializing, having this bunch of code:
 var dxo = new ClientReportToolbar('ReportViewerToolbar');
                    window['ReportViewerToolbar'] = dxo;
                    dxo.menuID = 'ReportViewerToolbar_Menu';
                    dxo.reportViewerID = 'reportViewer1';

In that code block doesn't work, but moving it outside of that block and just having dxo.initialize in there does.
Cheers


text:
Q: Elasticsearch not returning singular/plural matches I am using a php library of elasticsearch to index and find documents in my website. This is the code for creating the index:
curl -XPUT 'http://localhost:9200/test/' -d '
{
  "index": {
    "numberOfShards": 1,
    "numberOfReplicas": 1
  }
}'

I then use curl XPUT to add documents to the index and XGET to query the index. This works well except for the fact that singulars and plurals of query words are not matched across the index while returning results. For example, when I search for "discussions", the matches for "discussion" are not returned  and vice versa. Why is this so? I thought this is taken care of by default in elasticsearch. Is there anything that we have to mention explicitly for it to match the singular/plural forms?

A: The default elascticsearch analyzer doesn't do stemming and this is what you need to handle plural/singular. You can try using Snowball Analyzer for your text fields to see if it works better for your use case:
curl -XPUT 'http://localhost:9200/test' -d '{
    "settings" : {
        "index" : {
            "number_of_shards" : 1,
            "number_of_replicas" : 1
        }
    },
    "mappings" : {
        "page" : {
            "properties" : {
                "mytextfield": { "type": "string",  "analyzer": "snowball", "store": "yes"}
            }
        }
    }
}'

A: Somehow snowball is not working for me... am getting errors like I mentioned in the comment to @imotov's answer.
I used porter stem and it worked perfectly for me. This is the config I used:
curl -XPUT localhost:9200/index_name -d '
{
"settings" : {
    "analysis" : {
        "analyzer" : {
            "stem" : {
                "tokenizer" : "standard",
                "filter" : ["standard", "lowercase", "stop", "porter_stem"]
            }
        }
    }
},
"mappings" : {
    "index_type_1" : {
        "dynamic" : true,
        "properties" : {
            "field1" : {
                "type" : "string",
                "analyzer" : "stem"
            },
            "field2" : {
                "type" : "string",
                "analyzer" : "stem"
            }
         }
      }
   }
}'

A: Since 'porterStem' filter is oversensitive, it is more suited if you use 'minimal_english' filter. 'porterStem' creates similar tokens for words such as :
searching for 'Test' will result you 'Test', 'Tests', 'Testing', 'Tester' et. al.
But 'minimal_english' will only yield - 'Test' and 'Tests'.


text:
Q: mysql cli: how to list all databases I have permisions to create/read/update/delete? What command do I use on a mysql command line to see all the databases on some database server that I have permissions to? Specifically I am looking for the DBs that I have full CRUD permissions to.

A: mysql -e "show databases"

UPDATE:
Based on your edit, here is a query you can run against the mysql database in your server:
mysql> select Db from db where User='aj' and (select_priv='Y' and insert_priv='Y' and update_priv='Y' and delete_priv='Y');
+---------+
| Db      |
+---------+
| HopeDB  |
| LocusDB |
+---------+
2 rows in set (0.00 sec)


text:
Q: Passing a double to a function through inline x86 I am not a professional at assembly by any means and am receiving the following error when running my code: "Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call."
I am currently working on binding C-style functions to Python 3.2 using the CPython library and have run into an issue in my code with passing doubles. I have a single template function that is used to call the C function that is prototyped as such:
template <const char* MODULE, const char* FUNCTION>
static PyObject* ModuleFunction (PyObject* self, PyObject* param);

Currently my method works for passing integral types between Python and C/C++, but I'm having trouble with doubles. Maybe someone more well versed in x86 assembly can spot what I'm doing wrong. I've extracted all the code that does not involve doubles in my snippet:
__asm
{
      mov ecx, num_params
      mov ebx, 0
      cmp ebx, ecx
      je functionCall

    extractParameters:
      mov ebx, ecx
      dec ebx
      push ecx // save ecx
      push ebx
      push param
      call Py_GrabElementFromTuple
      pop edx // I know I could modify esp, but this made it more readable to me
      pop edx
      push eax // push the returned PyObject* onto the stack

      mov edx, 0
      mov ecx, dword ptr [paramTypes]
      mov dl, byte ptr [ecx+ebx]
      cmp decimal, edx
      je extractDouble
      jmp endLoop

    extractDouble:
      call Py_ExtractDouble
      pop ebx
      pop ecx
      fstp qword ptr [esp]
      jmp endLoop
    endLoop:
      loop extractParameters

    functionCall:
      call func

      mov ecx, dword ptr [stacksize]
      add esp, ecx

      mov edx, returnType
      cmp decimal, edx
      je wrapDouble
      jmp done

    wrapDouble:
      fstp qword ptr [esp]
      call Py_WrapDouble
      mov returnObj, eax
      jmp done

    done:
}

Clarification on the following functions I used that may not be clear to everyone:
PyObject* Py_GrabElementFromTuple(PyObject* tuple, int index);
PyObject* Py_WrapDouble(double d);
double Py_ExtractDouble(PyObject* obj);

The above functions are all wrappers I wrote around CPython methods to add error checking.

A: Your pushes and pops are only symmetrical if the exractDouble path is taken. In case you jump to endLoop you have two more pushes than pops. Generally you should avoid branches between function argument pushing and the actual function call, unless you know what you are doing.
Additionally the fstp qword ptr [esp] seems wrong, because it overwrites the return address. You probably want to subtract 8 from esp before and of course adjust the stack after the call again.


text:
Q: How change a for loop so I can use eof? so I have to create a code where I'm reading from two files, inventory and order. I have compare the order and get the number of items were fulfilled and the total amount. This program below satisfies all that's needed however, I have to use eof() and I don't know how.
The lines before this part of the program just simply reads the files and imports the information of the file to instream1 and instream2 which are internal names for the files. Thank you so much in advance.
for(int i=0;i<ord;i++){
    for(int j=0;j<inv;j++){
        if(prod_ord[i] == prod_code[j])
            {
            if(order[i] <= units[j])
            {
                fullfill[i]= order[i];
                amt_billed[i] = fullfill[i] * unitprice[j];
            }
            else
            {
                fullfill[i]= units[j];
                amt_billed[i] = fullfill[i] * unitprice[j];
            }
            }
        else
            {
                cout<< "Order invalid."<<endl;
    }
    }

}
float total_due = 0;

cout<< "Order#: order0923\nSalesman: full name\n \t Fullfilled \t Amt Billed" <<endl;
    for(int i= 0;i<ord;i++)
    {
        cout<< prod_ord[i]<<" \t"<<fullfill[i]<<" \t"<<amt_billed[i]<<endl;
        total_due += amt_billed[i];
    }
cout<<"Total Due: $"<<total_due<<endl;

A: If you're using eof(), you probably mean using it to figure out when to stop reading input.  That is, you want your termination condition, the second clause of the for loop, to call eof().  Not a complete solution, because this looks like homework, but there are basically two equivalent approaches:
for (records = 0; !std::cin.eof(); ++records) {
  // Parse a record and store it, preferably in a vector.
  // The records variable stores the number of records.
}

And:
int records = 0;
while (!std::cin.eof()) {
  // Read in and store a record, preferably in a vector.
  ++records;
}

But Take Note
Note that either of these will fail if the input contains an EOF while reading a record.  So you really want something like (untested):
bool read_record( std::istream&, record_t& );
using std::cin;
constexpr size_t SOME_REASONABLE_NUMBER = 4096U/sizeof(record_t);
std::vector<record_t> recordv;
recordv.reserve(SOME_REASONABLE_NUMBER);

while (cin.good()) {
  record_t this_record;

  if (read_record(cin, this_record))
    recordv.push_back(this_record);
  else
    break;
}

If you're using built-in types or overloading std::istream::operator>>, record_t this_record; while (cin >> this_record) will work.  (It returns a reference to cin, which evaluates to true if there are no errors on the stream.  It does not check EOF, but the next iteration would fail.)


text:
Q: How to disable / get rid of the Mozilla Quality Feedback program? How do I get rid of 'Mozilla Quality Feedback' program, which appears in my taskbar every time I start Firefox? Clicking on it does nothing.

A: Navigate to
C:\Program Files\Mozilla Firefox\extensions\talkback@mozilla.org\components\

You should see a talkback.exe executable, run it.
Choose Settings > Turn Agent Off.

A: Copied from "How to Disable Mozilla Crash Reporter":

*

*Open My computer and goto the installation directory of the application:

*

*Mozilla Firefox: %programfiles%\Mozilla Firefox

*Thunderbird: %programfiles%\Mozilla Thunderbird

*SeaMonkey: %programfiles%\mozilla.org\SeaMonkey
Here %programfiles% stands for C:\Program Files folder. Replace C: with your system drive letter where Windows is installed.

*Now look for application.ini file and open it in Wordpad.

*At the end of the file, you'll see following lines:
[Crash Reporter]
Enabled=1
ServerURL=https://crash-reports.mozilla.com/submit

*Simply change the value of Enabled to 0 as following:
[Crash Reporter]
Enabled=0
ServerURL=https://crash-reports.mozilla.com/submit

*Save the file and now you'll no longer see the Crash reporter window.

A: I have not seen this pop up for me since Firefox 2.0 or so, so this may not be completely applicable. I found this page about the feedback agent. If you are using an older version, this tells you where to find it and how to enable/disable it. Other than that, I believe it is an option in the installer to either enable or disable it.


text:
Q: How do I limit Wix bootstrapper bundle installs based on whether it is installed in silent mode? I would like to check whether the UI is in quiet/silent mode or gui mode and then either error or exit installation if the ui is displayed, preferably with a message indicating that this "cannot be run in gui mode"
in WiX 3.11 there is a variable WixBundleUILevel:
http://wixtoolset.org/documentation/manual/v3/bundle/bundle_built_in_variables.html
but how do I give an error if this value is set to show the UI?
Thanks

A: add to: Bundle wxs
xmlns:bal="http://schemas.microsoft.com/wix/BalExtension">

<Bundle .... \>
<bal:Condition Message="reason">WixBundleUILevel=2</bal:Condition>
<BootstrapperApplicationRef Id="WixStandardBootstrapperApplication.RtfLicense"/>
<Chain>

when calling candle and light, include
  -ext (wixfolder)bin\WixBalExtension.dll"


text:
Q: Crontab runs only a part of my script My script first executes two python scripts which write a temperature from a sensor to a file, which is then uploaded via ftp from within the .sh file.
For some reason the temperature only updates when I run the .sh file manually. When the crontab runs the script it does only upload the ftp, but it does not seem to run the python scripts, except for the the take_pic.py.

*

*The crontab is executed from the root's crontab.

*The python files are executable

*The log files do not show anything

*If I run the script manually everything works perfectly

ftp.sh :
echo "Run :$(date)" >> python_temp.log
python write_temp.py >> python_temp.log

python temp_to_file.py >> python_temp_to_file.log

#raspistill -o snapshot2.jpg -n -w 1280 -h 720

python takePic.py
sleep 3
HOST=XX                #This is the FTP servers host or IP address.
USER=XX                #This is the FTP user that has access to the server.
PASS=XX                #This is the password for the FTP user.
NOW=$(date +"%c")

#    echo beginne upload
    touch work
    ftp -inv $HOST << EOF
user $USER $PASS
cd /bilder/
put snapshot2.jpg
rename snapshot2.jpg snapshot.jpg

put temp.js

bye
EOF
#    echo erfolgreicher upload

temp_to_file.py
import subprocess
import datetime
import sys

output = subprocess.check_output("temper-poll -q -c" , shell=True)
output = output.rstrip()

#write to file

fobj_out = open("temp.js","w")
fobj_out.write('document.write("' + output + '*C ");')
fobj_out.close()

Crontab:
*/5 * * * * /root/ftp.sh

A: >> If I run the script manually everything works perfectly
You can include your .bash_profile in /root/ftp.sh before running any command.
. /root/.bash_profile
I have frequently faced issues like this with cron jobs.  You test them in shell when your profile is active, and when cron job runs, the environment (PATH and other things) is not available.
I looked at your two scripts, the first one uses only OS commands, but the second one calls temper-poll which may be not available to cron job.

A: Do you have a shebang in your ftp.sh script, i.e. does it begin with a #!/usr/bin/env bash line that you did not show here?
If it does not, you either need to add it, or in your crontab you must run bash /root/ftp.sh. Otherwise your script won't execute correctly.

A: Mostly this problem occurs due to script file permission and ownership of script files. The same problem was faced by me. I found that my scrip owner was not a super user e.g. root.
So, you have to set the permission and ownership of your scrip as super user. Find below.
First of all edit your crontab as super user.
[abc@host] crontab -e

and save crontab :wq!
Now set permission for script
[abc@host] chmod +x script.sh
[abc@host] chown root:root script.sh

Now restart your crontab.
[abc@host] /etc/init.d/crond restart

A: It is likely that that the python interpreter can'f find you takePic.py script.
Because a cronjob is executed in the users home directory (e.g.: /home/myuser/). So use the full path of your script:
python /some/path/takePic.py >> /some/path/python_temp.log


text:
Q: How to pass raw parameter using jsoup I want to call an API which just accepts raw data when you send requests using jsoup.
My code looks like this:
Document res = Jsoup.connect(url)
        .header("Accept", "application/json")
        .header("X-Requested-With", "XMLHttpRequest")
        .data("name", "test", "room", "bedroom")
        .post();

But I know the above code is not right for passing raw data.
Can anybody tell me how can I do it?

A: You'd have to use HttpUrlConnection to post the raw data to the website, and fetch the response as a String. Some Example, post data:
HttpUrlConnection conn = new URL("http://somesite.com/").openConnection();
String str =  "some string goes here";  //use a String for our raw data
byte[] outputInBytes = str.getBytes("UTF-8");  //byte array with raw data
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );

Getting response as String:
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

StringBuilder response = new StringBuilder();
String inputLine;

while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}

in.close();
conn.disconnect();

To parse with Jsoup:
Document doc = Jsoup.parse(response.toString());


text:
Q: Prove that $\int_{0}^{\infty} \sin(t^2)\,dt$ equals $\sqrt{\pi/8}$ Why is $$\int_{0}^{\infty} \sin(t^2)\,dt=\sqrt{\frac{\pi}{8}}$$ I am kinda new to this kind of calculus and I only know that $$\int_{-1}^{1}\sqrt{1-x^2}dx=\frac{\pi}{2}$$
The problem in which I have to use it is:
$$\lim_{x\to\infty}\frac{\int_{0}^{x} \sin(t^2)\,dt}{x^3}$$

A: You do not need to evaluate that integral in order to calculate the limit. Just note that
$$
\Bigl|\int_0^x\sin (t^2)\,dt\Bigr|\leq\int_0^x|\sin(t^2)|\,dt
$$
by the triangle inequality for integrals. Next, $|\sin(t^2)|\leq 1$ for all $0\leq t\leq x$, and hence
$$
\Bigl|\int_0^x\sin (t^2)\,dt\Bigr|\leq\int_0^x1\,dt=x.
$$
Thus, we find that, for all $x>0$,
$$
-\frac{1}{x^2}=-\frac{x}{x^3}\leq\frac{\int_0^x\sin(t^2)\,dt}{x^3}\leq\frac{x}{x^3}=\frac{1}{x^2}.
$$
Then, the squeeze theorem gives you that
$$
\lim_{x\to+\infty}\frac{\int_0^x\sin(t^2)\,dt}{x^3}=0.
$$

A: Hint. By setting, for any real number $t$ such that $t>0$,
$$
I_t:=\int_0^\infty e^{-tx^2}\cos (x^2)\:dx,\quad J_t:=\int_0^\infty e^{-tx^2}\sin (x^2)\:dx. \tag1
$$ One may prove that
$$
\begin{align}
\left(I_t\right)^2-\left(J_t\right)^2 &=\left(\int_0^\infty e^{-tx^2}\cos (x^2)\:dx\right)^2-\left(\int_0^\infty e^{-tx^2}\sin (x^2)\:dx\right)^2
\\\\&=\int_0^\infty\!\int_0^\infty e^{-t(x^2+y^2)}\left(\cos (x^2)\cos (y^2)-\sin (x^2)\sin (y^2)\right)dxdy
\\\\&=\int_0^\infty\!\int_0^\infty e^{-t(x^2+y^2)}\cos (x^2+y^2)\:dxdy
\\\\&=\int_0^{\pi/2}d\theta\int_0^\infty r\:e^{-tr^2}\cos(r^2)\:dr
\\\\&=\frac{\pi}4\:\frac t{1+t^2}. \tag2
\end{align}
$$ Similarly
$$
\begin{align}
2\:I_tJ_t &=\int_0^\infty\!\int_0^\infty e^{-t(x^2+y^2)}\sin (x^2+y^2)\:dxdy
\\\\&=\int_0^{\pi/2}d\theta\int_0^\infty r\:e^{-tr^2}\sin (r^2)\:dr
\\\\&=\frac{\pi}4\:\frac1{1+t^2}. \tag3
\end{align}
$$ From $(2)$ and $(3)$, one easily gets
$$
I_t=\sqrt{\frac{\pi}8}\:\sqrt{\frac{\sqrt{1+t^2}+t}{1+t^2}},\quad J_t=\sqrt{\frac{\pi}8}\:\sqrt{\frac{\sqrt{1+t^2}-t}{1+t^2}} \tag4
$$ As $t\to 0$, this leads to

$$
\int_0^\infty \cos (x^2)\:dx=\int_0^\infty \sin (x^2)\:dx=\sqrt{\frac{\pi}8}. \tag5
$$

A: I'm not sure what the top integral is useful for computing the final limit, which can be done with a straightforward application of l'Hôpital (in the form "whatever/$\infty$"), via the fundamental theorem of calculus:
$$
\lim_{x\to\infty}\frac{\displaystyle\int_0^x\sin(t^2)\,dt}{x^3}=
\lim_{x\to\infty}\frac{\sin(x^2)}{3x^2}=0
$$
However, it's not difficult to show that the integral converges. Let's do
$$
\int\sin(t^2)\,dt=
\frac{1}{2}\int\frac{\sin u}{\sqrt{u}}\,du=
-\frac{1}{2}\frac{\cos u}{\sqrt{u}}
  -\frac{1}{4}\int\frac{\cos u}{\sqrt{u^3}}\,du
$$
The first step is $u=\sqrt{t}$, the second is integration by parts. Now
$$
\int_1^{\infty}\frac{\cos u}{\sqrt{u^3}}\,du
$$
converges absolutely, because
$$
\frac{|\cos u|}{\sqrt{u^3}}\le\frac{1}{\sqrt{u^3}}
$$
and
$$
\int_1^{\infty}\frac{1}{\sqrt{u^3}}\,du
$$
is convergent. Set
$$
k=\int_1^{\infty}\frac{\cos u}{\sqrt{u^3}}\,du
$$
so we have
$$
\int_1^{\infty}\sin(t^2)\,dt=
-\frac{k}{4}
  -\frac{1}{2}\lim_{v\to\infty}\left[\frac{\cos u}{\sqrt{u}}\right]_1^v
$$
which is finite, say $K$. Then your integral is
$$
\int_0^{\infty}\sin(t^2)\,dt=K+\int_0^1\sin(t^2)\,dt
$$
The fact that this integral is $\sqrt{\pi/8}$ is much more complicated to establish and requires higher level methods.

A: I thought it might be instructive to present a way forward that uses contour integration in the complex plane.  To that end, let $I$ be the integral given by
$$\begin{align}
I&=\int_0^\infty e^{it^2}\,dt\\\\
&= \lim_{R\to \infty}\int_{0}^R e^{it^2}\,dt
\end{align}$$

Next, we analyze the closed-contour integral $J$ given by
$$J=\oint_{C_1+C_2+C_3}  e^{iz^2}\,dz$$
where
(i) $C_1$ is the straight line segment from $(0,0)$ to $(R,0)$;
(ii) $C_2$ is the circular arc of radius $R$ from $(R,0)$ to $(R/\sqrt 2,R/\sqrt 2)$;
(iii) $C_3$ is the straight line segment from $(R/\sqrt 2,R/\sqrt 2)$ to $(0,0)$.

Therefore, we can write
$$\begin{align}
J&=\int_0^R e^{ix^2}\,dx+\int_0^{\pi/4} e^{i R^2e^{i2\theta}}\,iRe^{i\theta}\,d\theta+\int_{R}^{0} e^{i(1+i)^2t^2/2}\,\frac{1+i}{\sqrt 2}\,dt\\\\
&\int_0^R e^{ix^2}\,dx+\int_0^{\pi/4} e^{i R^2e^{i2\theta}}\,iRe^{i\theta}\,d\theta-\frac{1+i}{\sqrt 2}\int_{0}^{R}e^{-t^2}\,dt \tag 1
\end{align}$$

Since $e^{iz^2}$ is analytic in and on $C_1+C_2+C_3$, Cauchy's Integral Theorem guarantees that $J=0$.
And as $R\to \infty$, the first integral on the right-hand side of $(1)$ approaches $I$, the second integral approaches $0$, and the third approaches $(1+i)\sqrt{\pi/8}$ (see Gaussian Integral).
Thus, we conclude that
$$I=\int_0^\infty \cos(t^2)\,dt+i\int_0^\infty \sin(t^2)\,dt=(1+i)\sqrt{\pi/8}$$
whereupon equating real and imaginary parts reveals
$$\bbox[5px,border:2px solid #C0A000]{\int_0^\infty \cos(t^2)\,dt=\int_0^\infty \sin(t^2)\,dt=\sqrt{\pi/8}}$$
as was to be shown!


text:
Q: How do I use least and less? How do I use least and less? for example, can I say this? This is a novel I'm writing and the character who says this phrase is supposed to be ignorant and immature.

Come on, hop on my back and try to make this the least silly possible, I don't want the girls to see this.

or

Come on, hop on my back and try to make this the less silly possible,  I don't want the girls to see this.

or

Come on, hop on my back and try to make this as less as silly possible,  I don't want the girls to see this.

A: A very common and idiomatic way of using 'possible' in a sentence is to use the construction:

as X as possible.

where X can be any number of adjectives.

as little as possible.
as much as possible.

So, I think, in quoted speech, where informal grammar is acceptable, you could 'quote' the character saying something that English speakers will often do - which is (sort of) making words up on the fly where they are needed.

Come on, hop on my back and try to make this as un-silly as possible, I don't want the girls to see this.

'Un-silly' is a single word adjective which might well be used by someone, although it is not in a dictionary. Just adding 'un' reverses the meaning of the word. 'Un' can be used with other adjectives which [cough] might be used here.
Or avoid the negation, and say it this way:

Come on, hop on my back and try to make this as sensible as possible.

Or reword to avoid the whole problem

Come on, hop on my back, and try not to make it look dumb/stupid/embarassing.

Of your three choices, the first one is the closest to being acceptable, but I would suggest none of them sound entirely natural, and the second two are ungrammatical.


text:
Q: Border with different colors Im trying to achieve the layout below using bootsrap but without success.
Im using bootstrap nav, but do you know how to  have that gray border bottom below the links and when the active item is active have a border with a different color?

working example: https://jsfiddle.net/b6yqLc2d/
HTML:

Title

          Active
          Link
          Link
          Link

A: Simply add border to nav-link without specifying color:

.text-gray {
  color: gray;
}

.nav-link {
  border-bottom: 3px solid;
}
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

Title

          Active
          Link
          Link
          Link

A: .text-gray{
  color:gray;
  border-bottom: 1px solid grey;
}

.active{

  border-bottom: 1px solid skyblue;
}

A: .nav-link {
 border-bottom: 3px solid grey;
}
.nav-link.active {
 border-bottom-color: #007bff;
}

This is a solution you are looking for

A: I've never seen a border that was more than one color, but each link can have its own border, so each border can have a different color.
Try adding this to the CSS in your jsfiddle:
a{
  border-bottom: solid 3px #ccc
}
a:hover{
  border-bottom: solid 3px #007bff;
}
a.active{
  border-bottom: solid 3px #007bff;
}


text:
Q: How to set keep touch on Mac touchpad? I am rookie in Mac and I came from Ubuntu
On my previous Dell laptop if I needed to mark some part of text in order to copy or delete it I just made one short touch on touchpad and immediately second touch (not click) and second touch I keep my finger on touchpad and than I can just move mouse and mark text.
or for example how I deleted files:
I have a file on desktop I need to trash it. I put mouse on the file make one short touch and immediately second touch and keep touch on file and now I am able to move file to trash on somewhere on the desktop.
But with mac touchpad I need make click (not just touch) and keep click with one finger and another finger I can move the file somewhere I need. Just remember how you move you file on the desktop, you use two fingers for this.
I hope I describe my problem clearly but feel free to ask
Question is : if there is some settings how to change behavior of touch click?

A: It is a bit hidden, but it is possible:

*

*Open System Preferences

*Click on Accessibility

*Scroll down a bit and click on Mouse & Trackpad

*Click on Trackpad Options…

*Enable dragging

*Select "three finger drag"


text:
Q: How to check the Live Agent Status? I am working on Einstein Chat Bot through WhatsApp.
I want to check whether any agent is online and available to chat(Not busy with other customers)
How can I check the status of Live Agent through Apex?
I tried to fetch in different Objects and Fields but didn't get any


text:
Q: Win32: full-screen and hiding taskbar I have a window, which I SetWindowPos(window, HWND_TOP, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), SWP_FRAMECHANGED);
It covers the whole screen, ok, but it takes a while (0.5 sec) to cover the taskbar as well.
Is there a way to come over the taskbar immediately? I found that setting HWND_TOPMOST does it immediately, but it stays above all the other windows, even if I switch the app - this is something I don't want. Also, if I first hide the window and then show it, it somehow forces the window to redraw and covers the taskbar immediately, but it flickers (because of the hiding). Is there another way?

A: Edit 2. There is even a better way for doing fullscreen, the chromium way, source taken from here:
http://src.chromium.org/viewvc/chrome/trunk/src/ui/views/win/fullscreen_handler.cc?revision=HEAD&view=markup
void FullscreenHandler::SetFullscreenImpl(bool fullscreen, bool for_metro) {
  ScopedFullscreenVisibility visibility(hwnd_);

  // Save current window state if not already fullscreen.
  if (!fullscreen_) {
    // Save current window information.  We force the window into restored mode
    // before going fullscreen because Windows doesn't seem to hide the
    // taskbar if the window is in the maximized state.
    saved_window_info_.maximized = !!::IsZoomed(hwnd_);
    if (saved_window_info_.maximized)
      ::SendMessage(hwnd_, WM_SYSCOMMAND, SC_RESTORE, 0);
    saved_window_info_.style = GetWindowLong(hwnd_, GWL_STYLE);
    saved_window_info_.ex_style = GetWindowLong(hwnd_, GWL_EXSTYLE);
    GetWindowRect(hwnd_, &saved_window_info_.window_rect);
  }

  fullscreen_ = fullscreen;

  if (fullscreen_) {
    // Set new window style and size.
    SetWindowLong(hwnd_, GWL_STYLE,
                  saved_window_info_.style & ~(WS_CAPTION | WS_THICKFRAME));
    SetWindowLong(hwnd_, GWL_EXSTYLE,
                  saved_window_info_.ex_style & ~(WS_EX_DLGMODALFRAME |
                  WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE));

    // On expand, if we're given a window_rect, grow to it, otherwise do
    // not resize.
    if (!for_metro) {
      MONITORINFO monitor_info;
      monitor_info.cbSize = sizeof(monitor_info);
      GetMonitorInfo(MonitorFromWindow(hwnd_, MONITOR_DEFAULTTONEAREST),
                     &monitor_info);
      gfx::Rect window_rect(monitor_info.rcMonitor);
      SetWindowPos(hwnd_, NULL, window_rect.x(), window_rect.y(),
                   window_rect.width(), window_rect.height(),
                   SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
    }
  } else {
    // Reset original window style and size.  The multiple window size/moves
    // here are ugly, but if SetWindowPos() doesn't redraw, the taskbar won't be
    // repainted.  Better-looking methods welcome.
    SetWindowLong(hwnd_, GWL_STYLE, saved_window_info_.style);
    SetWindowLong(hwnd_, GWL_EXSTYLE, saved_window_info_.ex_style);

    if (!for_metro) {
      // On restore, resize to the previous saved rect size.
      gfx::Rect new_rect(saved_window_info_.window_rect);
      SetWindowPos(hwnd_, NULL, new_rect.x(), new_rect.y(),
                   new_rect.width(), new_rect.height(),
                   SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
    }
    if (saved_window_info_.maximized)
      ::SendMessage(hwnd_, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
  }
}

Edit.
It is probably better to create a fullscreen window as BrendanMcK pointed it out in a comment to this answer, see this link: http://blogs.msdn.com/b/oldnewthing/archive/2005/05/05/414910.aspx ("How do I cover the taskbar with a fullscreen window?")
The new code using the link above would be:
HWND CreateFullscreenWindow(HWND hwnd)
{
 HMONITOR hmon = MonitorFromWindow(hwnd,
                                   MONITOR_DEFAULTTONEAREST);
 MONITORINFO mi = { sizeof(mi) };
 if (!GetMonitorInfo(hmon, &mi)) return NULL;
 return CreateWindow(TEXT("static"),
       TEXT("something interesting might go here"),
       WS_POPUP | WS_VISIBLE,
       mi.rcMonitor.left,
       mi.rcMonitor.top,
       mi.rcMonitor.right - mi.rcMonitor.left,
       mi.rcMonitor.bottom - mi.rcMonitor.top,
       hwnd, NULL, g_hinst, 0);
}

Old answer below - do not use it, stays only for the record on how NOT to do this.
You have to hide taskbar and menubar to see fullscreen immediately.
Here is the code (uses WTL), call SetFullScreen(true) to go into full screen mode:
template <class T, bool t_bHasSip = true>
class CFullScreenFrame
{
public:
    bool m_fullscreen;
    LONG m_windowstyles;
    WINDOWPLACEMENT m_windowplacement;

    CFullScreenFrame()
        :
        m_fullscreen(false),
        m_windowstyles(0)
    { }

    void SetFullScreen(bool fullscreen)
    {
        ShowTaskBar(!fullscreen);

        T* pT = static_cast<T*>(this);

        if (fullscreen) {
            if (!m_fullscreen) {
                m_windowstyles = pT->GetWindowLongW(GWL_STYLE);
                pT->GetWindowPlacement(&m_windowplacement);
            }

        }

        // SM_CXSCREEN gives primary monitor, for multiple monitors use SM_CXVIRTUALSCREEN.
        RECT fullrect = { 0 };
        SetRect(&fullrect, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));

        WINDOWPLACEMENT newplacement = m_windowplacement;
        newplacement.showCmd = SW_SHOWNORMAL;
        newplacement.rcNormalPosition = fullrect;

        if (fullscreen) {
            pT->SetWindowPlacement(&newplacement);
            pT->SetWindowLongW(GWL_STYLE,  WS_VISIBLE);
            pT->UpdateWindow();
        } else {
            if (m_fullscreen) {
                pT->SetWindowPlacement(&m_windowplacement);
                pT->SetWindowLongW(GWL_STYLE, m_windowstyles);
                pT->UpdateWindow();
            }
        }

        m_fullscreen = fullscreen;
    }

    void ShowTaskBar(bool show)
    {
        HWND taskbar = FindWindow(_T("Shell_TrayWnd"), NULL);
        HWND start = FindWindow(_T("Button"), NULL);

        if (taskbar != NULL) {
            ShowWindow(taskbar, show ? SW_SHOW : SW_HIDE);
            UpdateWindow(taskbar);
        }
        if (start != NULL) {
            // Vista
            ShowWindow(start, show ? SW_SHOW : SW_HIDE);
            UpdateWindow(start);
        }
    }
};

You also have to add some code to WM_CLOSE message:
case WM_CLOSE:
    ShowTaskBar(true);

There is one caveat with this solution, if your application crashes or is killed through task manager, then user losses taskbar on his system permanently! (unless he runs your application again, goes into fullscreen and exits, then he will see the taskbar again).
Earlier in my answer I pointed to "atlwince.h" but that function worked only on Windows CE, the one I pasted above works fine with XP, Vista and 7.

A: Here's the latest unbroken link to Raymond Chen answer.
Since MSDN/Microsoft keeps breaking links I'll paste below for posterity:

For some reason, people think too hard. If you want to create a fullscreen window that covers the taskbar, just create a fullscreen window and the taskbar will automatically get out of the way. Don't go around hunting for the taskbar and poking it; let it do its thing.
As always, start with the scratch program and add the following:
HWND CreateFullscreenWindow(HWND hwnd)
{
 HMONITOR hmon = MonitorFromWindow(hwnd,
                                   MONITOR_DEFAULTTONEAREST);
 MONITORINFO mi = { sizeof(mi) };
 if (!GetMonitorInfo(hmon, &mi)) return NULL;
 return CreateWindow(TEXT("static"),
       TEXT("something interesting might go here"),
       WS_POPUP | WS_VISIBLE,
       mi.rcMonitor.left,
       mi.rcMonitor.top,
       mi.rcMonitor.right - mi.rcMonitor.left,
       mi.rcMonitor.bottom - mi.rcMonitor.top,
       hwnd, NULL, g_hinst, 0);
}

void OnChar(HWND hwnd, TCHAR ch, int cRepeat)
{
 if (ch == TEXT(' ')) {
  CreateFullscreenWindow(hwnd);
 }
}

HANDLE_MSG(hwnd, WM_CHAR, OnChar);

Note that this sample program doesn't worry about destroying that fullscreen window or preventing the user from creating more than one. It's just a sample. The point is seeing how the CreateFullScreenWindow function is written.
We use the MonitorFromWindow function to figure out which monitor we should go fullscreen to. Note that in a multiple monitor system, this might not be the same monitor that the taskbar is on. Fortunately, we don't have to worry about that; the taskbar figures it out.
I've seen people hunt for the taskbar window and then do a ShowWindow(hwndTaskbar, SW_HIDE) on it. This is nuts for many reasons.
First is a mental exercise you should always use when evaluating tricks like this: "What if two programs tried this trick?" Now you have two programs both of which think they are in charge of hiding and showing the taskbar, neither of which is coordinating with the other. The result is a mess. One program hides the taskbar, then the other does, then the first decides it's finished so it unhides the taskbar, but the second program wasn't finished yet and gets a visible taskbar when it thought it should be hidden. Things only go downhill from there.
Second, what if your program crashes before it gets a chance to unhide the taskbar? The taskbar is now permanently hidden and the user has to log off and back on to get their taskbar back. That's not very nice.
Third, what if there is no taskbar at all? It is common in Terminal Server scenarios to run programs by themselves without Explorer (archived). In this configuration, there is no Explorer, no taskbar. Or maybe you're running on a future version of Windows that doesn't have a taskbar, it having been replaced by some other mechanism. What will your program do now?
Don't do any of this messing with the taskbar. Just create your fullscreen window and let the taskbar do its thing automatically.

A: Yup, HWND_TOPMOST does it for me.
Here is a section of code that makes full-screen work well (and quick) for me:

bool enterFullscreen(HWND hwnd, int fullscreenWidth, int fullscreenHeight, int colourBits, int refreshRate) {
    DEVMODE fullscreenSettings;
    bool isChangeSuccessful;
    RECT windowBoundary;

    EnumDisplaySettings(NULL, 0, &fullscreenSettings);
    fullscreenSettings.dmPelsWidth        = fullscreenWidth;
    fullscreenSettings.dmPelsHeight       = fullscreenHeight;
    fullscreenSettings.dmBitsPerPel       = colourBits;
    fullscreenSettings.dmDisplayFrequency = refreshRate;
    fullscreenSettings.dmFields           = DM_PELSWIDTH |
                                            DM_PELSHEIGHT |
                                            DM_BITSPERPEL |
                                            DM_DISPLAYFREQUENCY;

    SetWindowLongPtr(hwnd, GWL_EXSTYLE, WS_EX_APPWINDOW | WS_EX_TOPMOST);
    SetWindowLongPtr(hwnd, GWL_STYLE, WS_POPUP | WS_VISIBLE);
    SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, fullscreenWidth, fullscreenHeight, SWP_SHOWWINDOW);
    isChangeSuccessful = ChangeDisplaySettings(&fullscreenSettings, CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL;
    ShowWindow(hwnd, SW_MAXIMIZE);

    return isChangeSuccessful;
}

Note that this will change the resolution if you tell it the wrong settings. This is what I usually want, but if you don't like that, you can find out your resolution by using (where mainWindow is returned from something like CreateWindow() or CreateWindowEx()):

windowHDC = GetDC(mainWindow);
fullscreenWidth  = GetDeviceCaps(windowHDC, DESKTOPHORZRES);
fullscreenHeight = GetDeviceCaps(windowHDC, DESKTOPVERTRES);
colourBits       = GetDeviceCaps(windowHDC, BITSPIXEL);
refreshRate      = GetDeviceCaps(windowHDC, VREFRESH);

When you want to get out of full-screen you do something like this:

bool exitFullscreen(HWND hwnd, int windowX, int windowY, int windowedWidth, int windowedHeight, int windowedPaddingX, int windowedPaddingY) {
    bool isChangeSuccessful;

    SetWindowLongPtr(hwnd, GWL_EXSTYLE, WS_EX_LEFT);
    SetWindowLongPtr(hwnd, GWL_STYLE, WS_OVERLAPPEDWINDOW | WS_VISIBLE);
    isChangeSuccessful = ChangeDisplaySettings(NULL, CDS_RESET) == DISP_CHANGE_SUCCESSFUL;
    SetWindowPos(hwnd, HWND_NOTOPMOST, windowX, windowY, windowedWidth + windowedPaddingX, windowedHeight + windowedPaddingY, SWP_SHOWWINDOW);
    ShowWindow(hwnd, SW_RESTORE);

    return isChangeSuccessful;
}

I set my code to change between full-screen and windowed mode using a hotkey, and I keep the windowed mode variables as global, so that when changing to windowed mode, it stays put.

This code also has the advantage of running in the equivalent of "exclusive mode" (I'm using XP, and haven't tried it on the newer versions of windows), which means it'll be much, much faster. Let me know if I've made any mistakes from condensing the code (from my much bigger code).

A: Raymond Chen describes the "correct" way to do this at his blog:
https://devblogs.microsoft.com/oldnewthing/20100412-00/?p=14353
Fiddling with the task bar window explicitly is not recommended behaviour.

A: I believe the taskbar will get out of the way when its shell hook tells it about a "rude app", this might take a little while.
What if you start out with the window HWND_TOPMOST and make it not top most after 1 second?

A: *

*Right click on the taskbar

*choose Properties

*uncheck the checkbox that says "Keep the taskbar on top of other windows".

The taskbar belongs to the user, It's up to them to care about having it take 1/2 second to auto-hide when you app goes full screen.  If they want to change that behavior then they can change it.
If you are working in an embedded system, then you may have a legitimate reason to hide the taskbar. But in that case, there's no reason not to simply configure the taskbar to not always be on top.  You could also have a look at SystemParametersInfo if you want to change some of these settings in your code.


text:
Q: MSSQL число с 0 вначале Подскажите, мне необходимо хранить код в виде "091", в каком бы формате я не инсертил он упрямо вставляет "91", как сделать что бы 0 оставался, только varchar?

A: Если вы хотите хранить некий код, то да, указывайте любой текстовый формат (char, varchar, nchar, nvarchar).
Если же вы хотите хранить число, и выводить его по определенным правилам (с впередистоящими нулями), то можете добавление предстоящих нулей реализовать на клиенте или в запросе.
Вот так, например, я делаю преобразование числа в строку для сохранения порядка сортировки:
create table testtable (id int);

insert into testtable values (1), (101), (2147483647);

select right('000000000' + cast(id as varchar), 10) from testtable

drop table testtable;


text:
Q: sqlite3 & python: get list of primary and foreign keys I am very new to sql and intermediate at python. Using sqlite3, how can I get a print() list of of primary and foreign keys (per table) in my database?
Using Python2.7, SQLite3, PyCharm.
sqlite3.version = 2.6.0
sqlite3.sqlite_version = 3.8.11
Also note: when I set up the database, I enabled FKs as such:
conn = sqlite3.connect(db_file)
conn.execute('pragma foreign_keys=ON')

I tried the following:
conn=sqlite3.connect(db_path)
print(conn.execute("PRAGMA table_info"))
print(conn.execute("PRAGMA foreign_key_list"))

Which returned:
<sqlite3.Cursor object at 0x0000000002FCBDC0>
<sqlite3.Cursor object at 0x0000000002FCBDC0>

I also tried the following, which prints nothing (but I think this may be because it's a dummy database with tables and fields but no records):
conn=sqlite3.connect(db_path)
rows = conn.execute('PRAGMA table_info')
for r in rows:
    print r
rows2 = conn.execute('PRAGMA foreign_key_list')
for r2 in rows2:
    print r2

A: SELECT
    name
FROM
    sqlite_master
WHERE
    type ='table' AND
name NOT LIKE 'sqlite_%';

this sql will show all table in database, for eache table run sql PRAGMA table_info(your_table_name);, you can get the primary key of the table.
Those pictures show what sql result like in my database:
 first sql result
second sql result

A: Unknown or malformed PRAGMA statements are ignored.
The problem with your PRAGMAs is that the table name is missing. You have to get a list of all tables, and then execute those PRAGMAs for each one:
rows = db.execute("SELECT name FROM sqlite_master WHERE type = 'table'")
tables = [row[0] for row in rows]

def sql_identifier(s):
    return '"' + s.replace('"', '""') + '"'

for table in tables:
    print("table: " + table)
    rows = db.execute("PRAGMA table_info({})".format(sql_identifier(table)))
    print(rows.fetchall())
    rows = db.execute("PRAGMA foreign_key_list({})".format(sql_identifier(table)))
    print(rows.fetchall())


text:
Q: pandas: pandas.DataFrame.describe returns information on only one column For a certain Kaggle dataset (rules prohibit me from sharing the data here, but is readily accessible here),
import pandas
df_train = pandas.read_csv(
    "01 - Data/act_train.csv.zip"
)
df_train.describe()

I get:
>>> df_train.describe()
            outcome
count  2.197291e+06
mean   4.439544e-01
std    4.968491e-01
min    0.000000e+00
25%    0.000000e+00
50%    0.000000e+00
75%    1.000000e+00
max    1.000000e+00

whereas for the same dataset df_train.columns gives me:
>>> df_train.columns
Index(['people_id', 'activity_id', 'date', 'activity_category', 'char_1',
       'char_2', 'char_3', 'char_4', 'char_5', 'char_6', 'char_7', 'char_8',
       'char_9', 'char_10', 'outcome'],
      dtype='object')

and df_train.dtypes gives me:
>>> df_train.dtypes
people_id            object
activity_id          object
date                 object
activity_category    object
char_1               object
char_2               object
char_3               object
char_4               object
char_5               object
char_6               object
char_7               object
char_8               object
char_9               object
char_10              object
outcome               int64
dtype: object

Am I missing some reason why pandas only describes one column in the dataset?

A: By default, describe only works on numeric dtype columns. Add a keyword-argument include='all'. From the documentation:

If include is the string 'all', the output column-set will match the
  input one.

To clarify, the default arguments to describe are include=None, exclude=None. The behavior that results is:

None to both (default). The result will include only numeric-typed
  columns or, if none are, only categorical columns.

Also, from the Notes section:

The output DataFrame index depends on the requested dtypes:
For numeric dtypes, it will include: count, mean, std, min, max, and
  lower, 50, and upper percentiles.
For object dtypes (e.g. timestamps or strings), the index will include
  the count, unique, most common, and frequency of the most common.
  Timestamps also include the first and last items.

A: try the follwing code
import pandas
df_train = pandas.read_csv(
    "01 - Data/act_train.csv.zip"
)

def describe_categorical(df_train):
    from Ipython.display import display, HTML
    display (HTML(df_train[df_train.columns[df_train.dtypes=="object"]].describe().to_html()))

describe_categorical(df_train)


text:
Q: WatchKit get data from closed App in iPhone There are some applications (example Runtastic) where is possible from the Watch to activate some function of the companion App even if the App is not running in the iPhone (never opened or closed). How is possible to make the same with my Apps (get general data or settings)? I read some documents from Apple about app in background but I don't find nothing about App closed. Can someone help me? Thanks in advance

A: You have a few choices here: open the parent iPhone app to the background using openParentApplication:reply: in WKInterfaceController, use shared app containers or use app groups to share NSUserDefaults and keychain items. This will work for WatchKit 1 apps and here is an article on how to use these (+ MMWormhole): http://www.kristinathai.com/watchkit-best-practices-for-sharing-data-between-your-watch-and-ios-app/
One thing to keep in mind is when watchOS 2 launches later in this fall, this won't work with WatchKit 2 apps anymore. There you need WCSession, but that is a completely different thing and question.


text:
Q: Simple Webservice that outputs JSON I want to build a simple web service that outputs JSON to test a parser on iPhone.
I have considered using public apis like twitter etc but I want to use a custom JSON text for a small proof of concept test.
I am using a MAC with Apache.
I got the web server up and I can access an HTML page saying Hello World from 127.0.0.1
Can someone guide me as to how can I modify the HTML such that when I post a NSURLRequest, all I get back is JSON text. Not JSON in HTML/XML but plain JSON text.
Something like -http://twitter.com/statuses/public_timeline.json
Any leads much appreciated.
Thanks
Dev.

A: Got it right here - http://www.youtube.com/watch?v=7k-suIGS_1k
Just in case some one else is looking for the same thing.


text:
Q: Regex to find valid url + text python only I have a regex
((http\://|https\://|ftp\://)|(www.)|([a-zA-Z0-9\.-]))+(([a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4}))(/[a-zA-Z0-9%:/-_\?\.'~#-]*)?

which is picking valid url perfectly.
I have a scenario where there can be

*

*VALID URL + TEXT or (www.abc.com testing the regex)

*Text + VALID URL (Testing the regex www.abc.com)

REQ:
What i want is first the regex check the valid url then if url is valid it ignores the Valid url and search TEXT only outside the Valid URL.
Issues:
I have tried many regex but it is picking the valid url also which i don't want i only want if url is valid search for the text outside the url.
NO function Please . I am trying to fix this using Regex.

A: Perhaps you want this:
(.*?)((?:(?:http\:\/\/|https\:\/\/|ftp\:\/\/)|(?:www.)|(?:[a-zA-Z0-9\.-]))+(?:(?:[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4}))(?:\/[a-zA-Z0-9%:\/-_\?\.'~#-]*)?)(.*)

See demo here:
You will get three groups, you can used named groups to catpure beforeUrl text, Url and afterUrl text, which will be something like this:
(?<beforeUrl>.*?)(?<Url>(?:(?:http\:\/\/|https\:\/\/|ftp\:\/\/)|(?:www.)|(?:[a-zA-Z0-9\.-]))+(?:(?:[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4}))(?:\/[a-zA-Z0-9%:\/-_\?\.'~#-]*)?)(?<afterUrl>.*)

See demo here.


text:
Q: Uploading file to restful service So i have this method in my CMSController (MVC Web Application):
[HttpPost]
public bool UploadFile(Stream file)
{
    return file != null;
}

and alongside that project, I created another console application for testing, and that one has 1 function, which looks like this:
static void Main(string[] args)
{
    //Console.ReadLine();
    var stream = new FileStream(@"C:\Users\MyUsername\Desktop\test.txt", FileMode.Open);
    var file = new StreamContent(stream);

    var formData = new MultipartFormDataContent();
    formData.Add(file, "file", "file");

    //"http://localhost:49200/api/users/currentUsers"
    string actionURL = "http://localhost:49200/api/cms/uploadFIle";
    var request = new HttpRequestMessage(HttpMethod.Post, actionURL);
    request.Headers.Add("Accept", "application/xml");
    request.Headers.Add("enctype", "application/octet-stream");
    request.Content = formData;

    using (var client = new HttpClient())
    using (var response = client.SendAsync(request))
    {
        response.Wait();
        var resContent = response.Result.Content.ReadAsStringAsync();
        resContent.Wait();
        Console.WriteLine(resContent.Result);
        //Console.WriteLine(response.Result.RequestMessage.Content.ReadAsStringAsync());
    }

    Console.ReadLine();
}

And I am always getting an error:
<Error>
<Message>The request entity's media type 'multipart/form-data' is not supported for this resource.</Message>
<ExceptionMessage>No MediaTypeFormatter is available to read an object of type 'Stream' from content with media type 'multipart/form-data'.</ExceptionMessage>
<ExceptionType>System.Net.Http.UnsupportedMediaTypeException</ExceptionType>
<StackTrace>   at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
   at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)</StackTrace>
</Error>

I tried uploading image insted, using request.Headers.Add("enctype", "image/jpeg");, I tried (in CMSController.UploadFile) public bool UploadFile(HttpPostedFileBase file), I've tried this code, I've tried editing the web config by adding the
  <webHttpBinding>
    <binding name="CMSController.UploadFIle" maxBufferSize="2147483647"
             maxBufferPoolSize="2147483647"
             maxReceivedMessageSize="2147483647"
             transferMode="Streamed"
             sendTimeout="00:05:00">
      <readerQuotas  maxDepth="2147483647"
                     maxStringContentLength="2147483647"
                     maxArrayLength="2147483647"
                     maxBytesPerRead="2147483647"
                     maxNameTableCharCount="2147483647"/>
      <security mode="TransportCredentialOnly">
        <transport clientCredentialType="Windows"></transport>
      </security>
    </binding>
  </webHttpBinding>

But I am always getting the same error (mentioned above).
How do you upload a file using Controller's function, and a console application?
 (If I didn't provide enough info, please comment below, I will explain/edit question/etc)


text:
Q: I am converting existing GCM to Firebase Messaging in my project but I am getting this error? I am trying to convert existing GCM to Firebase Messaging in my project but,I am getting this error,Please Help me to solve this problem:
12-23 11:27:22.729 4443-4443/com.example.tabswithswipe E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             java.lang.RuntimeException: Unable to get provider com.google.firebase.provider.FirebaseInitProvider: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: DexPathList[[zip file "/data/app/com.example.tabswithswipe-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.example.tabswithswipe-2, /vendor/lib, /system/lib]]
                                                                                at android.app.ActivityThread.installProvider(ActivityThread.java:5100)
                                                                                at android.app.ActivityThread.installContentProviders(ActivityThread.java:4680)
                                                                                at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4613)
                                                                                at android.app.ActivityThread.access$1300(ActivityThread.java:162)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1424)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:107)
                                                                                at android.os.Looper.loop(Looper.java:194)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5371)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:525)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
                                                                                at dalvik.system.NativeStart.main(Native Method)
                                                                              Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: DexPathList[[zip file "/data/app/com.example.tabswithswipe-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.example.tabswithswipe-2, /vendor/lib, /system/lib]]
                                                                                at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:53)
                                                                                at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
                                                                                at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
                                                                                at android.app.ActivityThread.installProvider(ActivityThread.java:5085)
                                                                                at android.app.ActivityThread.installContentProviders(ActivityThread.java:4680)
                                                                                at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4613)
                                                                                at android.app.ActivityThread.access$1300(ActivityThread.java:162)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1424)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:107)
                                                                                at android.os.Looper.loop(Looper.java:194)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5371)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:525)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
                                                                                at dalvik.system.NativeStart.main(Native Method)

A: You need to tack care of following points:

*

*A device running Android 2.3 (Gingerbread) or newer, and Google Play services 10.0.1 or higher

*The Google Play services SDK from the Google Repository, available in the Android SDK Manager

*The latest version of Android Studio, version 1.5 or higher

*In Android Studio, add the FCM dependency to your app-level build.gradle file.

Gradle:
dependencies {
       compile 'com.google.firebase:firebase-messaging:10.0.1'
    }

Add the following to your app's manifest:
<service
    android:name=".MyFirebaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>
<service
    android:name=".MyFirebaseInstanceIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>

If you need more details please visit official web site.


text:
Q: Networking in Azure. Openswan inside Azure up but won't route packet I have set up a VPN using ubuntu 14.04 and openswan on azure 192.168.0.5. I have another box ubuntuapp behind the openswan in the same subnet 192.168.0.6(only encryption domain on azure). The right side has encryption domain of 172.31.20.10 and 172.31.20.12.
While I can connect from 192.168.0.6 azure side to the all 172.31.. encryption domain on 8080. I can't connect the 172.31. network to 192.168.0.6:80 even though port TCP 80 has been opened for both 172.31.20.10 and 172.31.20.12.
192.168.0.6 --> 172.31.20.10:8080 [yes]
192.168.0.6 --> 172.31.20.12:8080 [yes]

Connection to Azure
172.31.20.10 --> 192.168.0.6:80 [no]
172.31.20.12 --> 192.168.0.6:80 [no]

I know by default boxes on the save vnet can reach each other thanks to the default rules. Should there be a specific rule between ubuntuapp and openswan and vice versa? If yes kindly enlighten me.
EDIT
With some little tcpdump search I found out that the openswan box doesn't seem to know where to send the packet to
14:52:27.623074 IP 192.168.0.5.65000 > 192.168.0.6.65001: Flags [R], seq 0, win 0, length 0
14:52:27.623142 IP 192.168.0.5.65000 > 192.168.0.6.65001: Flags [R], seq 0, win 0, length 0
14:52:32.629621 ARP, Request who-has 192.168.0.6 tell 192.168.0.5, length 28
14:53:36.683792 IP 192.168.0.5.65000 > 192.168.0.6.65001: Flags [R], seq 0, win 0, length 0
14:53:36.683865 IP 192.168.0.5.65000 > 192.168.0.6.65001: Flags [R], seq 0, win 0, length 0

But ping or telnet from 192.168.0.5 to 192.168.0.6 works fine.
Thanks in advance

A: From what I could understand you have everything right except IP forwarding and UDR. The following article will help you with the configuration and general understanding.
Create User-Defined Routes (UDR) using PowerShell:
https://docs.microsoft.com/en-us/azure/virtual-network/virtual-network-create-udr-arm-ps
Once you enable IP forwarding, you have to explicitly tell Azure what's the next hop, otherwise, it will try to use Azure standard network gateway to reach the desired location.
I believe your virtual VPN appliance have to sit in another subnet in order for this to work as well.

A: The only thing that was missing was nat traversal on vyos vpn configuration
set vpn ipsec nat-traversal enable

This was added to the configuration and it's all fine now.


text:
Q: How to prevent a click() event through a child div to a parent div in jQuery? Situation:

+ OPEN

- CLOSE

.....

Visually:
|+Open..............................|-Close|..| (header)

|............Content..........................|
Header DIV is a 'big button' with jQuery click() event for opening the content.
The close DIV is inside the big header DIV and represents the close button also with click() event to close the content.
This close button is only visible by clicking on the big header.
Clickng on the header and oppening the content works as expecting but clicking on the close button let the click event through to the header DIV. The content closes and opens again beacause of two click events.
So how can i design the whole thing properly to make the close button solid and to prevent click through it to the header?

A: You need to stop the event from propagating up the DOM tree:
$('.closeBtn').click(function (evt) {
    evt.stopPropagation();

    // Your code here
});

A: $('.closeBtn').click(function (event){
   event.stopPropagation();
   //   ... your code here
   return false;
});

that should do the trick, so everytime you click on close it will not affect your header div,

A: Why not hook open event with
+ OPEN
 instead of parent div. Otherwise return false or stopPropagation from inner div click handler


text:
Q: How to bind conditions to yii2 active record queries? Given this query:
Customers::find()

if(isset($request->post('hasPhone')))
->where(['=', 'has_phone', 1])

if(isset($request->post('hasEmail')))
->where(['=', 'has_email', 1])

->orderBy('id DESC');

How do I add the where clauses to the query if the conditions are met and skip them if they dont?

A: $query = Customers::find()->orderBy('id DESC');

if (isset($request->post('hasPhone'))) {
    $query->andWhere(['has_phone' => 1]);
}
if (isset($request->post('hasEmail'))) {
    $query->andWhere(['has_email' => 1]);
}

Remember to actually fetch data with $query->one() or $query->all().


text:
Q: What is the best way to create an index on 3 column and if this is possible? We have a SQL query that is doing a full table scan:
DELETE
  FROM oc_cart
 WHERE (api_id > ? OR customer_id = ?)
   AND date_added < DATE_SUB(NOW(), INTERVAL ? HOUR)

Is it possible to create an index to optimize this query?
For now I have create 2 indices:

*

*one on date_added

*one on (date_added, customer_id and api_id)

But it seems that the query is still doing full scan.

A: How many rows in the table?  What does SHOW CREATE TABLE provide?  EXPLAIN SELECT ...`?
It is not possible to optimize the query much.
If api_id > ? is more selective than date added < ..., then this may be the best:
DELETE
  FROM oc_cart
 WHERE api_id > ?
   AND date_added < DATE_SUB(NOW(), INTERVAL ? HOUR);
DELETE
  FROM oc_cart
 WHERE customer_id = ?
   AND date_added < DATE_SUB(NOW(), INTERVAL ? HOUR);

together with these two indexes:
INDEX(api_id, date_added)
INDEX(customer_id, date_added)

In case api_is not that selective, also add
INDEX(date_added, api_id)  (but _not_ INDEX(date_added))


text:
Q: jQuery doesn't display specific hidden content when I use the .show() command Below is my HTML and jQuery code. jQuery displays the hidden elements, except for the #image4 and #video4 elements, which stay hidden with if I select image or video. All the other elements get displayed correctly.
Any idea why those two won't show?
JS:
 $(document).ready(function(){
        var fields = jQuery('#image_type');
        var select = this.value;
        fields.change(function () {
            if ($(this).val() == 'image') {
              alert($(this).val());
                $('#images_pop_up').show();
                $('#video1').hide();
                $('#video2').hide();
                $('#video3').hide();
                $('#video4').hide();
                $('#image1').show();
                $('#image2').show();
                $('#image3').show();
                $('#image4').show();
                $(' #image5').show();
              }
              else {
                $('#images_pop_up').show();
                $('#image1').hide();
                $('#image2').hide();
                $('#image3').hide();
                $('#image4').hide();
                $('#image5').hide();
                $('#video1').show();
                $('#video2').show();
                $('#video3').show();
                $('#video4').show();
                $('#image5').show();
              }

        });
    });

HTML:

   <input type="hidden" name="products_previous_image_lrg" value="easton-163135-wheeled-bag.jpg">
Nice bag

            <input type="hidden" name="products_previous_image_lrg" value="easton-163135-wheeled-bag.jpg"><input type="hidden" name="products_previous_image_lrg_caption" value="Nice bag">
            <input type="hidden" name="products_previous_video_embed"><input type="hidden" name="products_previous_video_embed_caption">
            New Image File: <input type="text" name="products_image_lrg" value="easton-163135-wheeled-bag.jpg">
Image Caption: <input type="text" name="products_image_lrg_caption" value="Nice bag">
               Video Embed field: <input type="text" name="products_video_embed">
Video Image Caption: <input type="text" name="products_video_embed_caption">

A: What sticks out most to me is that you're copy pasting when you could be putting CSS to work for you by giving them all the same class (or the appropriate groups of elements the same class at least) and then hiding and showing them based on that.
Your bug is probably caused by a slight typo somewhere in the selectors or the place where you're setting the ids in the markup.

A: try like this
    $(document).ready(function () {
    var fields = jQuery('#image_type');
    var select = this.value;
    $('#image_type').change(function () {
        if ($(this).val() == 'image') {
            alert($(this).val());
            $("[id^=image]").show();
            $("[id^=video]").hide();
        } else {
            $("[id^=video]").show();
            $("[id^=image]").hide();
        }

    });
});


text:
Q: How to point tools.jar in Spring Tool Suite I'm encountering this issue regarding a tools.jar in Spring Tool Suite. It seems that it has already enumerated where it checked for the said jar. Fortunately, I was able to find where it is located but I can't figure out how to tell Spring Tool Suite where it can be found. Any help will be much appreciated.
Here is a screen shot of the error message:

A: The best way is to install a regular JDK on your system and then point Eclipse/STS at this JDK in the SpringToolSuite4.ini file (aka eclipse.ini), as described here: https://wiki.eclipse.org/Eclipse.ini
This will let your IDE run on that JDK and the tools.jar will be found automatically.


text:
Q: IIS Config HTTP OPTIONS returns 200 but with empty response I have an ASP.NET Web API application running on .NET 4.0 with MVC 4.0. This is running on IIS 7.5, Windows Server 2008 R2 Datacenter Edition.
When I make a HTTP GET request to myserver/api I get a response with HTTP status code 200 (or 401 if not logged in) with appropriate content.
But when I make a HTTP OPTIONS request to the same url I always get a response with status code 200 and an empty response body (Content-length = 0).
Also I get this response when I make a HTTP OPTIONS request to a non-existent url (for example, myserver/api/foo).
The OPTIONS verb is allowed in my web.config file.
The problem is present only on one server, others work correctly.
Why would this be happening?

A: IIS has a default OPTIONSVerbHandler that might catch the request before MVC does.
If you remove that handler, your application should handle the request and return the correct response.
<system.webServer>
    <handlers>
        <remove name="OPTIONSVerbHandler" />


text:
Q: What does Backward Power flow mean to me? Drone pilot here, we use LiPo batteries and speed controls to brushless motors for flight.  My new electronics state that one should not use a power supply and only use a lipo for testing.
After some emails I learned that it is the regenerative breaking (active braking) that is causing issue here. I quote:

"A Lipo can handle the Backward-Power during active Braking."

It was also recommended that I use "a ipo on the bench".  No idea on what an ipo is, yet? (might be a typo meaning "lipo?)
I understand the basics of regenerative breaking via the brushless motor, and the brushless motor operation.
My goal is to use a VERY MASSIVE 12v power supply for testing. (60a stable, burst into the hundreds. Yeah, it weighs like 50lbs and cost a lot of $) I don't want to hurt the speed control (http://kiss.flyduino.net/kiss-esc-24a-re/) and seem to not be able to get a clear answer from the vendor yet.
Regardless of their answer, I think it is important for me to get some instruction on what backward flow is and add some droplets to the kill bucket.

A: It doesn't matter how big a current your big supply can deliver, under braking, the ESC is feeding power back into whatever is supplying it. A battery can take this power without its terminal voltage increasing much. A power supply, even a humungeous one, is probably not designed to expect a reverse flow of power into it, and its output voltage might rise dangerously, as it doesn't have the components in it to absorb that power, damaging the supply and/or the ESC.
If you supplied (say) 30 amps of auto bulbs with your 60A power supply, then you'd have 30A left to drive your motors. If the ESC sent 30A back into the supply when regernatively braking, the bulbs would be able to absorb the power (but no more than 30A).
A lower power alternative would be to shunt your supply with something capable of dumping the power if the voltage rose more than a volt or two. It might be possible to find transorbs with pass/stop voltages close enough, or you could build something with darlingtons and zener diodes as an active clamp.


text:
Q: How can I supply data to a JavaFX 2.0 LineChart from a file? I need to create a LineChart and want to supply the data points via a file. I.e. the numerical values are in a text file. Is this native functionality or do I have to do it the old fashioned way?

A: There is no such native functionality (I think because it's hard to guess desired format -- csv, xml, json, etc). So you just need to implement simple file reader which will add Chart.Data for each read line.


text:
Q: I accidentally ran `rm -rf /*` on my wsl, what should i do I accidentally ran rm -rf /* on my wsl (with root permission). and i rebooted and it became unusable. What should I do?

A: I can only offer condolences and hope you have a backup of important files.  Because, by default, WSL mounts your Windows drives in each WSL distribution (/mnt/c, etc.), a recursive rm from the root of the WSL virtual drive will extend into the Windows mounted filesystem. The integration between WSL and Windows is much tighter than a traditional "VM", and the resulting damage from this mistake is much more catastrophic.
It honestly doesn't matter (much) if you run the command as root or as the regular WSL user, since it's your regular WSL user that has access to your Windows user's files.  It would be the same as running a recursive remove-item from PowerShell as your regular Windows user.
While Windows system files won't be deleted (unless you were running WSL as a Windows administrator), your Windows user files were removed (likely including all application settings, desktop, etc.), so you will almost certainly not be able to log in to Windows after rebooting.
You aren't the first person to do this, so see here for other advice I've given when this has happened in the past. Ultimately, you are almost certainly looking at a full reinstall and (hopefully) restore from backup.


text:
Q: Why is My MYSQLI DELETE set on interval function not running I have search and tried all codes I could find to try to delete certain rows based on an 8hr interval from current time but it is not working. I put it in the header and in other pages. here is my code:
`date_default_timezone_set('Country/City');
if (isset($_SESSION["login"])) {
    $display = $_SESSION["login"];
    $day_nudge = mysqli_query($conn,"DELETE FROM nudges WHERE nudge_time < DATE_ADD(NOW(), INTERVAL -8 HOUR)");
}`

I have also tried other ways such as:
DELETE FROM nudges
WHERE nudge_time < (NOW() - INTERVAL 8 HOUR)

DELETE FROM nudges
WHERE nudge_time < DATE_SUB(NOW(), INTERVAL 8 HOUR)

these all worked on local host but now its on my server it does not execute.

A: After taking a break and playing with some other bugs... I came back and just thought I would try something and it worked for me, thought I would post it here incase anyone else may find it useful.

$datnudge = date('Y-m-d H:i:s', strtotime('-8 hour'));
$day_nudge = mysqli_query($conn,"DELETE FROM nudges WHERE nudge_time <= '$datnudge'");


text:
Q: WPF запретить доступ к кнопке если один из textbox пустой У меня на окне 36 textBox, как адекватно сделать запрет к кнопке если хоть одно поле пустое? Каждый textBox подписываеться на параметры свойства:
    private Mark selectedMark;
    public Mark SelectedMark
    {
        get { return selectedMark; }
        set
        {
            selectedMark = value;
            OnPropertyChanged("SelectedMark");
        }
    }

Подписываюсь к параметрам так
<TextBox Text="{Binding SelectedMark.OC1}" />

A: Я бы предложил Вам завести bool переменную, равную && всех значений в textBox.
Т.е. проверять каждый textBox и через && добавлять значение выражения (text == "") к этой переменной.
А доступ соответственно подвесить на true этой переменной.

A: Пример с использованием атрибутов и рефлексии.
Есть базовый класс для VM:
abstract class Vm : INotifyPropertyChanged
{
    protected virtual bool Set<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, value))
            return false;
        field = value;
        NotifyPropertyChanged(propertyName);
        return true;
    }

    protected void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

наследуем от него класс поддерживающий валидацию:
abstract class ValidatableVm : Vm
{
    protected override bool Set<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
    {
        var b = base.Set(ref field, value, propertyName);
        if (b && GetType().GetProperty(propertyName).GetCustomAttributes(typeof(RequiredAttribute), true).Length > 0)
        {
            IsValid = GetType().GetProperties()
                               .Where(p => p.GetCustomAttributes(typeof(RequiredAttribute), true).Length > 0)
                               .Select(p => (string)p.GetValue(this))
                               .All(s => !string.IsNullOrEmpty(s));
            NotifyPropertyChanged(nameof(IsValid));
        }
        return b;
    }

    public bool IsValid { get; private set; }
}

Здесь в методе Set если произошло обновление свойства, то для текущего типа VM берем все свойства помеченные атрибутом и проверяем чтобы они были не пусты.
Я использовал атрибут Required из пространства имен System.ComponentModel.DataAnnotations, если вам это не подходит - вы можете создать свой атрибут.
Пример использования, VM:
class MainVM : ValidatableVm
{
    string name;
    [Required]
    public string Name
    {
        get => name;
        set => Set(ref name, value);
    }

    string address;
    [Required]
    public string Address
    {
        get => address;
        set => Set(ref address, value);
    }

    string phone;
    public string Phone
    {
        get => phone;
        set => Set(ref phone, value);
    }
}

Обратите внимание, атрибутом помечены только 2 свойства, именно они и будут проверяться на непустоту.
Разметка:
<StackPanel Margin="5">
    <TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"/>
    <TextBox Text="{Binding Address, UpdateSourceTrigger=PropertyChanged}"/>
    <TextBox Text="{Binding Phone, UpdateSourceTrigger=PropertyChanged}"/>
    <Button Content="Click me" IsEnabled="{Binding IsValid}"/>
</StackPanel>


text:
Q: CosmosDB Deserialize String As List I need to change an existing model property type from string to List<string>.
Because my database already has several instances of such model with the string property, I'd like to find a way to read the property:

*

*If it is valorized as string, return a new List with the item

*If it's valorized as a List, return as is

I am on .NET Core 6 and I believe my two options are

*

*Add a decorator to the property

*Modify the SQL query and try to parse string as array

What would be the best way to accomplish this?

A: On .NET you can define a method that handles custom deserialization/serialization.
The V3 SDK uses Newtonsoft, so I'll use that as an example, you can implement JsonConverter (https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm).
public class MyConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(List<string>);
    }

    // Used for serializing, if true, override WriteJson
    public override bool CanWrite { get { return false; }}

    public override object ReadJson(
        JsonReader reader,
        Type objectType,
        object existingValue,
        JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
        {
            return null;
        }

        JToken itemsJToken = JToken.Load(reader);
        if (itemsJToken.Type == JTokenType.String)
        {
            return new List<string>(){ itemsJToken.Value<string>() };
        }
        else // assuming it can only be an array
        {
            return itemsJToken.ToObject<List<string>>(serializer);
        }
    }

    public override void WriteJson(
        JsonWriter writer,
        object value,
        JsonSerializer serializer)
    {
        throw new NotImplementedException("Unnecessary because CanWrite is false. The type will skip the converter.");
    }
}

public class MyType
{
    /* other properties */
    [JsonConverter(typeof(MyConverter))]
    public List<string> Items {get;set;}
}


text:
Q: Does there exist a morphism from the projective line to another model of it Let $C$ be a smooth curve with function field $K$. The projective line $\mathbf{P}^1_C$ is a smooth model over $C$ for the projective line $\mathbf{P}^1_K$. Does there exist another model of $\mathbf{P}^1_K$, say $X$, and a surjective birational morphism $\mathbf{P}^1_{C} \to X$?
On the generic fibre this morphism is the identity.

A: If $X$ is any model of ${\bf P}^1_K$ over $C$, then any morphism ${\bf P}^1_C\to X$ is birational, quasi-finite (the fibers are finite sets) hence finite because ${\bf P}^1_C$ is projective over $C$. So if $X$ is normal, then ${\bf P}^1_C\to X$ is an isomorphism.
If you don't require $X$ be normal, there are counterexamples. Let $Y$ be any singular integral rational curve, let $X=Y\times_k C$ (here $k$ is the field on which $C$ is defined). Then $X$ is a non-normal (hence non-smooth) model of ${\bf P}^1_K$. The normalization map ${\bf P}^1_k\to Y$ induces a surjective birational morphism ${\bf P}^1_C\to X$.


text:
Q: How to disable all Windows useless built-in apps and features I am using a VM for a game EVE Online and in this VM I only run game and not any other supporting thing like Xbox Game Bar Overlay etc.
I have deleted all WUP apps and other installed apps
I want that my system use minimum RAM and CPU and only has basic things which are required to run a desktop apps...
Windows 10 Pro x64


text:
Q: AWS Lambda function working properly despite throwing timeout error and not resolving callback I have a Lambda function that receives a message from SNS and uses a custom module that queries an external database and outputs calculations to the database. The module works fine: the Lambda has internet access via VPC and successfully connects to the database and outputs the desired data to the database, but I am still getting the error "Task timed out after 3.00 seconds." The module itself uses sequelize, async/await, and promises.
I increased the max timeout and the only difference was that the number of seconds in the error message increased to the timeout limit. I tried reserving concurrency and the error persists. Every part of my function works great other than the fact that the callback never resolves, producing a timeout error. I have tried running the function with and without the "context.callbackWaitsForEmptyEventLoop" statement, running it with the statement only makes the code return before any of the rating engine function is completed. Here is the rating engine code: https://github.com/elizajanus/rating-engine-module
Is it possible that the database connection is not closing within my custom module and preventing the code from fully completing the imported function? Or could it be something else? This issue may be connected: https://github.com/sequelize/sequelize/issues/8468
const {RatingEngine} = require('./rating-engine');

exports.handler = (event, context, callback) => {
    const message = event.Records[0].Sns.Message;
    RatingEngine(message, message.d_customer_id,
      message.d_total_distance_travelled);
    callback(null, 'move record created in database');
};

A: @Eliza Janus, you can test your code locally with https://www.npmjs.com/package/lambda-local, this will help you you to better identify the problem debugging the code.


text:
Q: Trino S3 partitions folder structure I do not understand what paths Trino needs in order to create table from existing files. I use S3 + Hive metastore.
My JSON file:
{"a":1,"b":2,"snapshot":"partitionA"}

Create table command:
create table trino.partitioned_jsons (a INTEGER, b INTEGER, snapshot varchar) with (external_location = 's3a://bucket/test/partitioned_jsons/*', format='JSON', partitioned_by = ARRAY['snapshot']

What I have tried:

*

*Store JSON file in s3://bucket/test/partitioned_jsons/partitionA/file.json

*Store JSON file in s3://bucket/test/partitioned_jsons/snapshot=partitionA/file.json

*Store JSON file in s3://bucket/test/partitioned_jsons/snapshot/partitionA.json
But all returns just an empty table.


text:
Q: Удалять лишние пробелы в поле ввода информации на лету Ситуация такая как удалять пробелы на лету с начала и конца строки, у меня всё работает только проблема такая что допустим я буду вводить " пробное " то введётся отлично просто "пробное" пробелы отсекаются, но есть я буду вводить "пробное сообщение" то после первого слова ставлю пробел и он отсекается, как мне исправить это?
name_z = $('input[name=name_otprav]');  // Выбираем поле ввода имени
var form_glav_input_error_name = $("#form_glav_input_error_name");  // Выбираем блок под ошибки ввода информации
name_z.live("keyup", function(){    // При нажатии на кнопку срабатывает функция
    var name_l_val = $.trim(name_z.val());  // Получаем текст введённый в поле ввода имени и отсекаем пробелы
    var name_l_val_pro = name_z.val(name_l_val);    // Получаем значение без пробелов
    var name_l_val_trim = name_z.val(); // Получаем текст введённый в поле ввода имени без пробелов
    var name_l = name_l_val_trim.length;    // Считаем сколько символов введено
    if (name_l == 0)
        {
            var name_otprav = "Минимум 2 символа, максимум 20 символов";
            form_glav_input_error_name.text(name_otprav);
        }
    if (name_l == 1)
        {
            var name_otprav = "Поле имени должно состоять минимум из 2 символов";
            form_glav_input_error_name.text(name_otprav);
        }
    if (name_l > 20)
        {
            var name_otprav = "Поле имени должно состоять максимум из 20 символов";
            form_glav_input_error_name.text(name_otprav);
        }
    if (name_l <= 20 && name_l >= 2)
        {
            var name_otprav = "Поле имени заполнено верно";
            form_glav_input_error_name.html(name_otprav);
            var name = name_z.val();
        }
});

A: Для начала - забудьте про метод .live(), а используйте вместо него метод .on().
И скажите, зачем вам такие сложности? Если вам нужно получить значение поля с обрезанными по краям лишними пробелами, то после того, как пользователь закончил вводить данные, просто примините функцию $.trim();
A: Нужно перед обрезкой запоминать, был ли введен пробел, и после ввода каждого символа проверять, не был ли последним введен пробел.
Вот так: http://jsfiddle.net/jbqP5/


text:
Q: How to configure header's (and footer's) "Header from Top" value when using Python's docx library? I am trying to create from scratch a docx file report, so I am using the python-docx library ver 0.8.10, with great results. When I am adding a header to the document, the header has the default values of "Header from Top:" = 0.5 Inches. I see this value when I have created the docx file and opened it in MS WORD.
So, how can I configure the "Header from Top" and the "Footer from Bottom" default values? For example How can I configure the header to be "Header from Top" = 0.1 inches? Something like header.top_margins = Inches(0.1). I have checked online but haven't found anything related.
Thanks in advance

A: I think you're looking for Section.header_distance and .footer_distance:
https://python-docx.readthedocs.io/en/latest/api/section.html#docx.section.Section.header_distance

header_distance
      Length object representing the distance from the top edge of the page to the top edge
      of the header. None if no setting is present in the XML.


text:
Q: What is the property name to break long lines in VS Code? When I have long text line I would like to show it next line.

What is the property name in VS Code?

A: On Windows, press Alt + Z (macOS: Option ⌥ + Z) to toggle word wrapping, or, select View > Toggle Word Wrap from VSCode Menu.

A: For Windows users do the following in -->

*

*Open VScode

*Go to Settings(Gear icon on the bottom-left side)

*Click Settings in the menu

*In the searching bar search for "word wrap"

*Click the drop-down menu and change it to "on"

This setting will wrap your words according to your editor: viewport.
In case this auto wrapping isn't working you can press -->  Alt + z to wrap content

A: For Windows, Pressing Alt+Z will break the line.

A: In VS Code:

*

*Install Beautify plugin. (or any Formatter)

*Go to the file & select the desired part.

*Right-Click on it & select Format Selection Or press Ctrl + k Ctrl + F.

Hope this helps.

A: The menu under File > Preferences or press Ctrl+,  (on Mac Code > Preferences > Settings or press Command (or Cmd) ⌘+,) provides entries to configure user and workspace settings. You are provided with a list of default Settings.
Set editor.wordWrap: on in your User Settings or Workspace Settings under preference.
Select the below options to change to the desired settings.

*

*Off - Lines will never wrap.

*on  - Lines will wrap at the viewport width.

*wordWrapColumn - Lines will wrap at "Editor: Word Wrap Column".

*bounded - Lines will wrap at the minimum of viewport and "Editor: Word Wrap Column".

You can toggle word wrap for the VS Code session with Alt+Z (macOS: Option (or Alt) ⌥+Z) or select View >  Word Wrap from Menu.
For more about User and Workspace Settings or Key Bindings for Visual Studio Code

A: HTML > Format: Wrap Line Length
set the maximum number of characters (for example - 1000)

A: You can press Ctrl + W / Ctrl + L to toggle word wrapping or select Main menu "Edit>Advanced>Word Wrap" .


text:
Q: how to add text in top border of view in andriod I am new to android development please help me in creating this type design
I want to add text in the center of the top borders in the card

please help me or guide me to achive the same view

A: in TextView
android:hint="@string/name"

Example
<com.google.android.material.textfield.TextInputLayout
        android:id="@+id/editTextLayout"
        style="@style/Widget.Material3.TextInputLayout.OutlinedBox.Dense"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:autofillHints="none"
            android:hint="@string/name"
            android:inputType="textPersonName" />
    </com.google.android.material.textfield.TextInputLayout>

A: Take a look at he reference code available here
CountDownTimerView
Make changes according to your need.
Happy Coding

A: <RelativeLayout
    android:layout_width="300dp"
    android:layout_height="100dp"
    android:background="@drawable/bg_border_offer"
    >
  <androidx.appcompat.widget.AppCompatTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Offer ends in"
    android:layout_centerHorizontal="true"
    android:background="@drawable/bg_white"
    android:textColor="@color/black_text_color"
      android:layout_marginTop="-8dp"
    />
</RelativeLayout>