text:
Q: Access Azure SQL Database from on premise network performance I have a VB.NET desktop solution that works with a SQL Server as database server.  When running locally or on a local network, the data queries run 1-2 seconds the most.  The same code when accessing an Azure Sql Database runs 15 to 30 seconds.  I have chosen a region as close as possible to the client's location, but this does not help.
What is the best way to improve the performance of this system?  Do I need to create a hybrid network or something of that effect?
I apologize in advance, I am not a network engineer and don't have much experience in fixing performance issues of this type.
Thank you.

A: There are a couple of things you need to keep in mind when comparing performance between SQL Azure and SQL Server:

*

*The number of round trips on the network matters more in SQL Azure if your client/app tier is not also in Azure.  If it takes 2ms round trip on-premises but 150ms round trip in your cloud example, the number of round trips can really add up quickly.  Sometimes the batch size can be made larger to hide some latencies to the data center from wherever you are running your client.

*There is also a decent chance that you did not really get the same query plans on SQL Server and SQL Azure and that this may be part of what you are seeing in the performance difference.  One way to get insight into the query plan choices in both cases is to use the query store (which is on-by-default in SQL Azure but can be enabled in SQL 2016+).  You can read about it here: https://learn.microsoft.com/en-us/azure/sql-database/sql-database-operate-query-store.  There are also monthly releases of the SSMS client tool which has nice UI to navigate the query store.  You can download the most recent one  here.  When looking at performance of why a query performs differently, you first start by looking to see if the overall plan shapes are the same or not.  If they are different, then that might be the actual explanation for the performance difference.  If they are the same, then the next option is more likely the issue for you

*Finally, there are cases where customers are running SQL Azure with a very small reservation size (ex: Basic) and comparing it against their workstation or laptop in terms of performance.  Basic and Standard (S3 or so) databases are generally running on less than a core of CPU.  So, if you are trying to compare performance against your local machine, you need to remember that the reservation size can impact performance substantially as well.  Trying with a larger size (for testing) can help isolate whether this is the case or not.  If it is, there are various ways to improve performance of the query (indexing, considering how the query is written/what it is asking to see if there is a simpler way to represent things, etc) may be an option to improve the efficiency of the query to run efficiently enough in a smaller performance tier (to save money).

A broader explanation of why any generic query is slow in SQL is a much larger topic, so if you post some specifics from your investigation it may help people narrow down whether you have an indexing problem, something related to parameter sniffing, or one of the other more common pitfalls people hit when building SQL apps.
Best of luck - I hope this helps you take the next step to figure out your performance issue.


text:
Q: how to display line numbers of errors I'm hacking in Racket and I keep getting errors.
The default error handler shows a stack trace.  At the end of the stack trace, it shows the "top level" evaluation as "/path/to/file/my_module.rkt: [running body]"
How do I show the line number for the running body part?

A: If you use DrRacket, it will highlight the error location in the source.  To get similar functionality in the racket REPL, see the errortrace tool.

redpajama_set_name: RedPajamaStackExchange


text:
Q: nodejs - officegen - pipesCount in order to create word documents, i use officegen package:
  var fs = require('fs');
  var officegen = require('officegen');

  var docx = officegen ({
    'type': 'docx',
    'title': 'test title'
  })

  var pObj = docx.createP ();
  pObj.addText('Text');
  pObj.addText('with color', {color: '000088'});
  pObj.addText('and back color.', {color: '00ffff',back: '000088'});

  var out = fs.createWriteStream(__dirname + '/tmp/out.docx');
  docx.generate(out)
  out.on('error', function(err) {
    console.log('out error: ' + err);
  });

  docx.on('finalize', function(written) {
    console.log('Finish to create a Word file.\nTotal bytes created: ' + written + '\n');
  });

  docx.on('error', function(err) {
    console.log('docx appeared: ' + err);
  });

What happens:
File get created, with content 'PK'

Why?
Error thrown in console:
Cannot read property 'pipesCount' of undefined

Anybody faced this issue before?
Greetings and thanks


text:
Q: How to combine ranges in VBA? I have a form that I have developed in Excel and added a command button to print the form.  There are four pages to the form, but if the first cell of the second or third pages of the cell are blank, I want to skip those pages.  I have come up with the following code, but i get an "Type Mismatch" error as it combines the ranges. Is this not an appropriate way to combine ranges/ is there a better way?
Private Sub PrintAuth1_Click()
'   Prints the Authorization Form upon clicking once

Dim printrng As Range   'Range to be printed so that blank pages are not printed.
    Set printrng = Worksheets("BLR 13210").Range("A1:AX69")
Dim ws As Worksheet
    Set ws = ActiveSheet

If ws.Range("E75") <> "" Then   'If first line of this page is blank, then it won't print the page
    printrng = printrng & ws.Range("A70:AX135")
End If
If ws.Range("E141") <> "" Then  'If first line of this page is blank, then it won't print the page
    printrng = printrng & ws.Range("A136:AX200")
End If

printrng = printrng & ws.Range("A201:AX264")    'Adds last page to print range

' Dialog Box to decide whether to quick print or make changes to printer setup.
msg = "Would you like to send to default printer?"
msg = msg & vbNewLine
config = vbYesNoCancel + vbQuestion + vbDefaultButton1
Title = "Printer Selection"
ans = MsgBox(msg, config, Title)

If ans = vbYes Then printrng.PrintOut Copies:=1, Collate:=True
If ans = vbNo Then Application.Dialogs(xlDialogPrint).Show
If ans = vbCancel Then
End If

End Sub


text:
Q: JSON path parsing - object vs array var sample1 = {
  "book" : {
    "name" : "book 1",
    "type" : "type 1"
  }
}

var sample2 = {
  "book" : [{
      "name" : "book 1",
      "type" : "type 1"
    }, {
      "name" : "book 2",
      "type" : "type 2"
    }, {
      "name" : "book 1",
      "type" : "type 3"
    }
  ]
}

Can any one help me to construct a single JSON path to extract the book name for which the type = "type 1" from both the samples? The problem is the book can be an array or an object but I can have only one json path to extract the value. Any help would be appreciated.
I'm using this node module for parsing - https://github.com/s3u/JSONPath

A: A function with a logical loop would probably work:
function getBooks(type, object) {
    var response = [];

    for (var key in object) {
        if (object.hasOwnProperty(key)) {
            //If its an object, another for-in loop
            if (typeof object[key] == object) {
                for (var k in object[key]) {
                    if (object[key].hasOwnProperty(k)) {
                        if (object[key][k].type == type) {
                            response.push(object[key][k]);
                        }
                    }
                }
            //If array, a normal for loop will do
            } else if (typeof object[key] == array) {
                for (var i = 0; i < object[key].length; i++) {
                    if (object[key][i].type == type) {
                        responses.push(object[key][i]);
                    }
                }
            }
        }
    }
    return response;
}

You should now be able to pass in either object (with an array of books or objects of books) and a type to match on and get an array of matching objects back. This is untested, so bear with me.
Edit: object was also a terrible naming choice for that parameter, change that to bookObject or something!

A: I have modified s3u/JSONPath module to be able to apply constraints to individual objects, not only to array elements. With that modification you can get what you're asking for with this single path :
"$.book[?(@.type=='type 1')]"
Here is the modification for the jsonpath.js:
JSONPath.prototype._walk = function (loc, expr, val, path, f) {
    var i, n, m;

    if (!Array.isArray(val)) {
        //make it array of one element, so that @ filters can be applied to non-arrays
        val = [val];
    }

    for (i = 0, n = val.length; i < n; i++) {
          f(i, loc, expr, val, path);
    }

};

I did not commit it yet, it should probably be voted for by the contributors to that project, but feel free to do that.
I use that modified module in my projects, and it allows me to write filter expressions that are more to the spirit of JSONPath.


text:
Q: Unable to get content of file using google drive api I am working with a react application where you can access google drive files using react-google-picker and I am using get api of google apis where you can pass "alt=media" as a URL parameter to get the file content. It's working as expected for text files but for PDF/Doc files, it returns metadata instead of actual content of file.
Is there any other way to get the content using google api's ??
this is the code for getting content of the file.
axios.get(`https://www.googleapis.com/drive/v2/files/${data.docs[0].id}?key=${developerKey}&alt=media`, {
                headers: {
                    Authorization: Bearer ${this.state.token}
                }
            })


text:
Q: Merge type of variable with token I want to have a macro, which can merge the type of a variable with another token to create a new token. A random example:
int var;
int make_token(var);

This would become:
int var;
int var_int;

I've tried to define the macro like so:
#define make_token(x) x ## _ ## typeof(x)

But the whole thing gets expanded to:
int var;
int var_typeof(var)

Is there a way to achieve this without having to pass the type of the variable in the parameters of the macro?

A: Since typeof is determined in a later phase of compilation, way after preprocessing, this is impossible.
Also typeof does not expand to a type identifier; it does not work at the textual/code level, but at the semantic level instead.  It's a keyword the compiler interprets and uses to determine the type for its internal data structures.
Only thing you can do is to add the type to the macro:
#define TYPED_VARIABLE(type, identifier) type identifier ## _ ## type

However, as a wise man recently said: "Using Hungarian notation is brainless and is a huge error, so don't do it!"  I fully agree.

A: You'd need a macro for each type you want to define.


text:
Q: Set AES key in iOS from a byte array My service gives me a key as a byte array. For example:
(byte) 0x16, (byte) 0xBB, (byte) 0xAB, (byte) 0xEA, (byte) 0x85, (byte) 0xA7,(byte) 0xD4, (byte) 0xE5, (byte) 0x2F, (byte) 0x7F, (byte) 0x28, (byte) 0x4C, (byte) 0x96, (byte) 0x7D,

In iOS, the AES key is a string. I am trying to use this byte array as a key in iOS.

A: this OC code ------
//Encrypt AES  NOPadding
-(NSData *)AES128Encrypt{
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
//  Encrypt Key
Byte keybyte[]={0x77,0x24,0x56,0xf2,0xa7,0x66,0x4c,0xf3,0x39, 0x2c,0x35,0x97,0xe9,0x3e,0x57,0x47};
NSData *keyData=[[NSData alloc]initWithBytes:keybyte length:16];
const void *vKey = (const void *)[keyData bytes];
//Encrypt Iv
Byte ivbyte[]={0x24,0x4e,0x6d,0x8a,0x56,0xac,0x87,0x91,
    0x24,0x43,0x2d,0x8b,0x6c,0xbc,0xa2,0xc4};
NSData *IvData=[[NSData alloc]initWithBytes:ivbyte length:16];
const void *vIv = (const void *)[IvData bytes];

CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                      kCCAlgorithmAES128,
                                      0x0000,
                                      vKey,
                                      kCCBlockSizeAES128,
                                      vIv,
                                      [self bytes],
                                      dataLength,
                                      buffer,
                                      bufferSize,
                                      &numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
    return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer);
return nil;

}


text:
Q: How to create a button to save the state of a checkbutton in python? I am using tkinter in python 3.
I have a checkbutton and button on my GUI:
entercheck = Checkbutton(window1, variable = value)
entercheck.pack()
savebutton = Button(window1, width=5, height=2, command = savecheck)
savebutton.pack()

where value=IntVar().
I am trying to make it so that when clicked, the button saves the status of the checkbutton to the variable status. I have tried:
def savecheck():
    global status
    status = value.get()

However, this always results in status (which is a global variable) being equal to 0 no matter whether the checkbutton is checked or not. Why is this?
I have had a look at this question: Getting Tkinter Check Box State and this method seems to be working for them?
Edit:
I created a smaller version of my program to try and get it to work, this time just trying to output the value of the checkbutton variable, but it still doesn't work. Here is the whole code:
from tkinter import *
root=Tk()

def pressbttn1():

    def savecheck():
        print (value.get()) #outputs 0 no matter whether checked or not???

    window1 = Tk()

    value=IntVar()
    entercheck = Checkbutton(window1, bg="white", variable = value)
    entercheck.pack()

    savebttn = Button(window1,text= "Save", command = savecheck)
    savebttn.pack()

class Application(Frame):

    def __init__(self, master):
        super(Application, self).__init__(master)
        self.grid()
        self.create_widgits()

    def create_widgits(self):

        self.bttn1 = Button(self, text= "New Window", command = pressbttn1)
        self.bttn1.pack()

#main
app=Application(root)
root.mainloop()

I don't understand why the above code doesn't work, when the below does:
from tkinter import *
master = Tk()

def var_states():
   print(check.get())

check = IntVar()
Checkbutton(master, text="competition", variable=check).pack()

Button(master, text='Show', command=var_states).pack()
mainloop()

A: status is a variable local to the savecheck function. Make it a global and it will work as intended.
status = 0
value = IntVar()

def savecheck():
    global status
    status = value.get()

entercheck = Checkbutton(self, variable = value)
entercheck.pack()
savebutton = Button(self, width=5, height=2, command = savecheck)
savebutton.pack()

A: In all honesty, I'm not entirely clear about why your program doesn't work, but nevertheless have a solution for you.
In your pressbttn1() function, change the:
    window1 = Tk()

to
    window1 = Toplevel()

Calling Tk() creates a new root window. Calling Toplevel() creates a separate top-level window widget which exists independently from the root window, but is controlled by the same window manager. An application can have any number of them.
See Toplevel Window Methods for additional information about window managers.


text:
Q: What does a timeOut do (using html parsing with Jsoup) I am new to this, and I am writing a program that parses html from a Url:
Document doc = Jsoup.connect("http://example.com").timeout(600000).get();

What does the .timeout(600000) do?

A: Timeout sets timeout period for connection (in another words, the maximum time for which that client will wait for a response from server). Method parameter is in milliseconds.
Following are details from the jsoup Connection javadoc.

Timeout:
  Set the request timeouts (connect and read). If a timeout occurs, an
  IOException will be thrown. The default timeout is 30 seconds (30,000
  millis). A timeout of zero is treated as an infinite timeout. Note
  that a read timeout is not the same as a maximum timeout. As long as
  the connection is sending bytes at least every timeout seconds (e.g.
  in the case of an infinite stream of data, or a slow large download),
  the read timeout will not fire. This can be mitigated by using a
  maximum download size (see maxBodySize(int)), or interrupting the
  connecting thread after a max timeout.


text:
Q: Correct syntax to use in mysql 5.5.25 for not exists Hi I'm trying to write a cursor in powerbuilder 12 to fetch some records . Here this is my query.
I'm trying to fetch some records from the trninvhdr table which are not in the second table.
SELECT
INV_DATE,
INV_NO,
INV_TYPE,
CUR_CODE,
EXCH_RATE,
usd_rate,
CR_TERM,
DUE_DATE,
bl_date,
TOT_AMT
FROM trninvhdr
WHERE
COMP_CODE ='NFL1' AND
CUST_CODE = 'NLML' AND
INV_TYPE ='F' AND
INV_DATE <= '2016-03-25' AND
NOT EXISTS
 (SELECT * FROM trninvoiceavailability WHERE trninvoiceavailability.COMP_CODE = trninvhdr.COMP_CODE
 AND trninvoiceavailability.INV_TYPE = trninvhdr.INV_TYPE AND trninvoiceavailability.INV_NO = trninvhdr.INV_NO);

Here how I use it in the program.
DECLARE lc_retrieve CURSOR FOR

SELECT
 trninvhdr.INV_DATE,
 trninvhdr.INV_NO,
 trninvhdr.INV_TYPE,
 trninvhdr.CUR_CODE,
 trninvhdr.EXCH_RATE,
 trninvhdr.usd_rate,
 trninvhdr.CR_TERM,
 trninvhdr.DUE_DATE,
 trninvhdr.bl_date,
 trninvhdr.TOT_AMT
FROM trninvhdr
WHERE
COMP_CODE = :as_comp_code AND
CUST_CODE = :as_cust_code AND
INV_TYPE ='F' AND
INV_DATE <= :as_inv_date )AND
NOT EXISTS (SELECT * FROM trninvoiceavailability
 WHERE trninvoiceavailability.COMP_CODE = trninvhdr.COMP_CODE
 AND trninvoiceavailability.INV_TYPE = trninvhdr.INV_TYPE AND
 trninvoiceavailability.INV_NO = trninvhdr.INV_NO);

     open lc_retrieve ;

The query works fine in the mysql server but in the progra it gives me the following error .
Database c0038 SQLSTATE = 3700 MySQL ODBC 5.2 a Driver mysql id 5.5.25 You have an error in your syntax. check the manual that corresponds to your mysql version for the right syntax to use near NOT EXISTS (SELECT * FROM trninvoiceavailability.... at line 1.
What is the correct Syntax that I should use to work this query.

A: You need to remove ) from your query as per below-
INV_DATE <= :as_inv_date )AND

sholuld be INV_DATE <= :as_inv_date AND

A: I can see a bracket in this code... where did it come from and where is it's friend?
INV_DATE <= :as_inv_date )AND


text:
Q: NSSpeechSynthesizer Saving to URL I'm creating a MacOS application that generates dialog files from a tab-delimited text file. The text file is formatted (output filename) [tab] (text to be spoken to that file). I got the program working perfectly running in the main thread, but this blocked the UI, of course. When I moved the meat of the application to a User Initiated thread, I unblocked the UI, but now it occasionally and randomly speaks a line out the speaker instead of to a file. A file is still created, but it's of zero duration. If the script contains 1,000 lines, it might get through the whole thing perfectly, or it might "speak" ten or more of them out the speaker. It's almost always different lines each time.
This is the code that speaks to a file:
// Set URL to save file to disk
if let speechFileURL = NSURL(string: speechFilePath) {
    speechSynth.startSpeakingString(spokenText, toURL: speechFileURL)  // Speak to file
}
else {
    dialogAlert("Invalid File: ", text: speechFileName)
}

while(NSSpeechSynthesizer.isAnyApplicationSpeaking() == true) {
    if self.gUserClickedStop {
        speechSynth.stopSpeaking()
        self.gIsSpeaking = false
        break
    }
}

This is the call to the function that parses the script and generates the speech files:
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { [unowned self] in
    self.parseTheScript()
}

As mentioned above, calling parseTheScript() without wrapping it in the Grand Central Dispatch call makes it work perfectly, except for the blocking issue.
I'm new to programming in Swift and the idea of multithreaded programming, so I'm sure I'm doing something wrong, but I'm stumped as to how to fix this problem.
Thank you in advance for your help.
Edit to add...
This is the entire function that parses the text file and generates the dialog files:
    // This opens the text file and generates the spoken audio files
func parseTheScript() {
    let filemgr = NSFileManager.defaultManager()
    print("Chosen path: \(scriptFileTextField.stringValue)")   // debug
    if filemgr.fileExistsAtPath(scriptFileTextField.stringValue) {
        print("File exists")
        do {
            outputFilename.stringValue = ""
            scriptToSpeak.stringValue = ""
            outputFilename.hidden = false
            scriptToSpeak.hidden = false
            progressBar.minValue = 0
            progressBar.doubleValue = 0.0
            progressBar.hidden = false
            filenameLabel.hidden = false

            let text = try String(contentsOfFile: scriptFileTextField.stringValue, encoding: NSUTF8StringEncoding)
            let lines: [String] = text.componentsSeparatedByString("\n")
            var progressEndValue = Double(lines.count)
            progressBar.maxValue = progressEndValue

            let speechSynth = NSSpeechSynthesizer.init()
            let theVoice = gVoiceList[voiceListPopup.indexOfSelectedItem - 1]   // Not sure why it's off by one
            speechSynth.setVoice(theVoice)

            for line in lines {
                let thisLine: [String] = line.componentsSeparatedByString("\t") // Split the line at the tab character
                if (thisLine.count == 2) {                  // Did the line split into two parts?
                    let speechFileName = thisLine[0]
                    let spokenText = thisLine[1]
                    outputFilename.stringValue = speechFileName
                    scriptToSpeak.stringValue = spokenText
                    let speechFilePath = destinationFolderTextField.stringValue + speechFileName + ".aif"        // Build the path string for the output speech file
                    print("Filename: \(speechFilePath)")
                    print("SpokenText: \(spokenText)")

                    if(gSpeakToFile) {
                        // Set URL to save file to disk
                        if let speechFileURL = NSURL(string: speechFilePath) {
                            speechSynth.startSpeakingString(spokenText, toURL: speechFileURL)  // Speak to file
                        }
                        else {
                            dialogAlert("Invalid File: ", text: speechFileName)
                        }
                    }
                    else {
                        speechSynth.startSpeakingString(spokenText) // Speak to audio output
                    }

                    while(NSSpeechSynthesizer.isAnyApplicationSpeaking() == true) {
                        if self.gUserClickedStop {
                            speechSynth.stopSpeaking()
                            self.gIsSpeaking = false
                            break
                        }
                    }

                    progressBar.incrementBy(1.0)
                }
                if gUserClickedStop {
                    gUserClickedStop = false
                    gIsSpeaking = false
                    progressEndValue = 0
                    generateButton.title = "Start"
                    break
                }

            }
            gIsSpeaking = false
            progressBar.doubleValue = progressEndValue
            generateButton.title = "Start"
            filenameLabel.hidden = true
            outputFilename.stringValue = ""
            scriptToSpeak.stringValue = ""

        } catch let error as NSError {
            dialogAlert("Error:", text: String(error.localizedDescription))
            print("Error: \(error)")
        }
    } else {
        print("File does not exist")
    }

}


text:
Q: Read contents of text file from offset to end in Perl I'm teaching myself Perl and Regex by reading Jeffrey Friedl's excellent Mastering Regular Expressions.
While trying to solve the "A Small Mail Utility" exercise starting on page 53 I stumbled upon the problem of not knowing how to save the content of file into a variable starting from an offset.
So here's my (shortened) script.
my ($body, $line, $subject);
$body = $line = $subject = "";

open(MYFILE, "king.in") || die("Could not open file!");
# Read the file's content line by line
while ($line = <MYFILE>)
{
    # An empty line marks the beginning of the body
    if ($line =~ m/^\s+$/ ) {
        # HERE IS THE ISSUE
        # Save the file content starting from the current line
        # to the end of the file into $body
        last;
    }

    if ($line =~ m/^subject: (.*)/i) {
        $subject = $1;
    }
    # Parse additional data from the mail header
}
close(MYFILE);

print "Subject: Re: $subject\n";
print "\n" ;
print $body;

I did some online research but couldn't figure out how to put the remainder of the file (i.e., the email body) into the variable $body.
I figured out that I could get the current position within the file in bytes using $pos = tell(MYFILE);
Eventually I ended up with the working but unsatisfactory solution of putting the file's lines first into an array.
How do I save the file content starting from an offset (either as a line number or bytes) into $body?
Edit:
My solution -as provided by vstm- is to use $body = join("", <MYFILE>) to read in the rest of the file when encountering the empty line that marks the beginning of the body.
The whole script I wrote can be found here.
Although this works great for me now, I would still like to know how to say (elegantly) in Perl "give me lines x to z of this file".
Thanks for your advice everybody.

A: The variable $. will give you the line number of the current file handle. Documentation here.
If you want to get an offset in bytes in the file, you can use seek to set the file handle position. But usually, you don't really want to do that, unless bytes is actually your desired offset.
The easiest solution for this is probably using the input record separator. Setting it to undef will slurp the file, instead of reading it line-by-line:
my $text;
my $subject;
while (<MYFILE>) {
    if (/^subject: /i) {  # /i flag to ignore case
        $subject = $_;
    } elsif (/^\s*$/) {
        local $/;
        $text = <MYFILE>;
    }
}

This will end the loop as well, since it has reached eof.

A: Instead of stopping immediately, you could just set a flag that says "now I'm reading the body". Like that:
my $inbody = 0;

while ($line = <MYFILE>)
{
    if($inbody) {
        $body .= $line;
        next;
    }
    # An empty line marks the beginning of the body
    if ($line =~ m/^\s+$/ ) {
        # HERE IS THE ISSUE
        # Save the file content starting from the current line
        # to the end of the file into $body
        $inbody = 1;
        next;
    }

    if ($line =~ m/^subject: (.*)/i) {
        $subject = $1;
    }
    # Parse additional data from the mail header
}

It's like a mini state-machine. First It's in the "header"-state and if the first empty newline is read it switches to the "body"-state and just appends the body to the variable.
Alternatively you could just slurp the rest of the MYFILE-handle into the body at the end of your original while-loop and before the close:
# This would be your original while loop, (I've just shortened it)
while ($line = <MYFILE>)
{
    if ($line =~ m/^\s+$/ ) {
        last;
    }
    # Parse additional data from the mail header
}

# The MYFILE-handle is now still valid and at the beginning of the body
$body = join("", <MYFILE>);

# now you can close the handle
close(MYFILE);

A: You can change the input record separator:
local $/;
$body = <MYFILE>;


text:
Q: Async: How to break on exact line of code that has thrown the exception? Say I have the following code:
async void buttonClick(object sender, RoutedEventArgs e)
{
    await nested1();
}

async Task nested1()
{
    await nested2();
}

async Task nested2()
{
    await nested3();
}

async Task nested3()
{
    await Task.Delay(1000);
    throw new Exception("Die");  // <-- I want Visual Studio to break on this line
}

How can I make Visual Studio break on the indicated line only when the exception is unhandled?

Normally when the exception is thrown, Visual Studio will break here in App.g.i.cs:

If I then enable "Just my code" in the debugger options, it will break here instead:

Getting close. If I then check System.Exception under the "Thrown" column in the Exceptions window (Ctrl+Alt+E), it will break exactly where I want:

but now Visual Studio will break on all thrown exceptions, not just unhandled ones. Is there any way to get Visual Studio to break at the most logical line of code only for unhandled exceptions, just like it would in regular non-async code? If this behavior is not possible, then:

*

*Why is it not possible?

*How can I identify the line of code that has thrown the exception, whether that be a throw statement of my own code, or a framework method call that has thrown an exception?

I've used 3 nested functions here in this example to emphasize that my code may be complex with many branches and nested method calls, and identifying the problematic line of code is difficult if Visual Studio doesn't break on the innermost line of code.

A: It's not possible.

Why is it not possible?

Because it's not done yet. async is still getting better tooling support with every release, and I do expect this behavior to be added sooner or later.

How can I identify the line of code that has thrown the exception, whether that be a throw statement of my own code, or a framework method call that has thrown an exception?

Visual Studio 2013 does have the ability to view asynchronous causality stacks in the debugger. If you want similar behavior at runtime, then you can use my async diagnostics package.

A: I think I may have discovered the answer to my question.
First, I uncheck System.Exception under the "Thrown" column in the exceptions window (Ctrl+Alt+E). I do this because I don't want Visual Studio to break on all exceptions, only unhandled ones.
Second, I keep "Just my code" enabled in the debugger options.
Now, when the debugger breaks, it will break here:

as per the screenshot in my question. But if I inspect the call stack:

I can actually see where the exception originated from (in nested3(), line 46). If I click this entry in the call stack window, Visual Studio will jump to the correct line, and the "Locals" window will even show me the values of local variables in that frame. Cool! I think this is what I wanted.


text:
Q: Rspec fails on "let"s I have a mailer
class MyMailer < ActionMailer::Base
  def send1(a, b, c)
    #.....
    mail(....).deliver
  end

  def send2(a, b, c)
    #.....
    mail(....).deliver
  end
end

And I test it
describe MyMailer do
  describe "#send1" do
    let(:a) { "a@b.com" }
    let(:b) { "message" }
    let(:c) { FactoryGirl.create :user }
    let(:send1_email1) { MyMailer.send1 a, b, c }

    after(:all) { MyMailer.deliveries.clear }

    it "should send an email" do
      expect(MyMailer.deliveries.count).to eq(1)
    end

    #........ other ITs testing send1_emai1

  describe "#send2" do
    let(:d) { "aaa@bbbb.com" }
    let(:e) { FactoryGirl.create :admin }
    let(:g) { "message2" }
    let(:send1_emai2) { MyMailer.send2 d, e, g }

    after(:all) { MyMailer.deliveries.clear }

    it "should send an email2" do
      expect(MyMailer.deliveries.count).to eq(1)
    end

    #........ other ITs testing send1_emai2

end

So most of the time it fails due to the errors should send an email expect 1 got 2 and should send an email expect 1 got 4 or 0
Sometimes the numbers are different (got 0 - 4). I tried to do this:
  let!(:send1_email) { MyMailer.send1 a, b, c }
  let!(:send1_emai2) { MyMailer.send2 d, e, g }

But it also failed.
Failure/Error: expect(MyMailer.deliveries.count).to eq(1)

       expected: 1
            got: 4

I wonder why?
Previously I used before :all and @variables and everything was well (no errors)
The same errors:
   it "should send an email" do
      expect(MyMailer.deliveries.count).to eq(1)
      MyMailer.deliveries.clear
    end

   it "should send an email2" do
     expect(MyMailer.deliveries.count).to eq(1)
     MyMailer.deliveries.clear
   end

A: As the documentation states at this location.

Use let to define a memoized helper method. The value will be cached
  across multiple calls in the same example but not across examples.

Also i'm sure you are aware that rspec runs examples in random order, meaning other examples call the mail-sending let() helper, meaning by the time it gets to your test, the suite has already sent out 4 emails, making your test fail. You should not rely on the order of defining tests. You should be making sure that your test data is scrubbed and cleaned before your examples.

A: There is a difference between let and let!
let is instantiated only when called, in other words, rspec won't be looking inside let block before you use the variable.
let(:send1_email2) { MyMailer.send2 d, e, g }
it 'testing' do
  # email not sent yet because we use let without bang
  expect(MyMailer.deliveries.count).to eq(0)

  send1_email2.call_a_method
  # now email is sent since we used the variable send1_email2
  expect(MyMailer.deliveries.count).to eq(1)
end

let! is instantiated as if it was a before block
let!(:send1_email2) { MyMailer.send2 d, e, g }
it 'testing' do
  # before we do anything the email is sent because we used let with a bang
  expect(MyMailer.deliveries.count).to eq(1)
end

Additionaly do no user after(:all) { MyMailer.deliveries.clear }, but after { MyMailer.deliveries.clear } instead, otherwise your counter won't be cleared between your examples


text:
Q: I've just upgraded to Php7 now I'm having this issues Problem 1
    - Installation request for phpunit/phpunit 5.7.14 -> satisfiable by phpunit/phpunit[5.7.14].
    - phpunit/phpunit 5.7.14 requires ext-dom * -> the requested PHP extension dom is missing from your system.

A: You most probably need to uninstall php5 extension and install php7.0-xml extension.
Afterward restart apache2/nginx and you should be good to go!


text:
Q: pthread_cond_timedwait hanging with gdb I'm using pthread_cond_timedwait on a thread loop to execute at every X ms (unless it is waked first).
When I'm using gdb to debug it sometimes it the function never returns.
This forum post also have the same problem, but there is no solution.
Here's some code that reproduces the problem:
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

static pthread_cond_t s_cond = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t s_mutex = PTHREAD_MUTEX_INITIALIZER;

int main(int argc, char **argv)
{
    int rc = 0;
    struct timespec curts = { 0 }; /* transformed timeout value */

    clock_gettime(CLOCK_REALTIME, &curts);
    curts.tv_sec += 10; /* Add 10 seconds to current time*/

    pthread_mutex_lock(&s_mutex);

    printf("pthread_cond_timedwait\n");
    rc = pthread_cond_timedwait(&s_cond, &s_mutex, &curts);
    if (rc == ETIMEDOUT)
    {
        printf("Timer expired \n");
    }

    pthread_mutex_unlock(&s_mutex);

    return 1;
}

If I run it, it will run OK, and if I run in gdb it will also run OK.
I've narrowed down to these steps (I've named the program timedTest ):

*

*Run the program;

*While it runs attach gdb to it;

*Execute continue on gdb;

*The timedTest program never returns...;
Then, if I hit Ctrl+C on the terminal running gdb and run continue again, then the program will return.
I can probably use some other method to achieve what I want in this case, but I assume that it should be a solution to this problem.
EDIT:
Looks like this only happens in some machines, so maybe there's something to do with gcc / glibc / gdb / kernel versions...
Versions where this happens almost always:
$ ldd --version
ldd (Ubuntu EGLIBC 2.13-0ubuntu13) 2.13

$ gcc --version
gcc (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2

$ gdb --version
GNU gdb (Ubuntu/Linaro 7.2-1ubuntu11) 7.2

$ uname -a
Linux geovani 2.6.38-8-generic-pae #42-Ubuntu SMP Mon Apr 11 05:17:09 UTC 2011 i686 i686 i386 GNU/Linux

A: According to this forum post, this is a bug in the 2.6.38 kernel. I've made some tests with a 2.6.39 kernel and problem does not happen. Rolling back to the 2.6.38 it appears again.


text:
Q: Do azure eventHub binding(Java) supports partitionKey for @EventHubOutput? I could find a document or example of eventhub  output binding supporting a partitionKey. The below link says it is an option for trigger metadata however there is no java example.
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-hubs#trigger---event-metadata
Did I miss anything in this document or its still not supported?
Thanks in Advance

A: If you want an example about how to use trigger metadata, you could refer to the below code or you could go to the github check the code. The below is my test code.
public class Eventhubtest {
    /**
     * This function will be invoked when an event is received from Event Hub.
     */
    @FunctionName("Eventhubtest")
    public void run(
        @EventHubTrigger(name = "message", eventHubName = "myevent", connection = "EventHubConnection", cardinality = Cardinality.MANY)String message,
        @BindingName("SystemPropertiesArray") SystemProperty[] systemPropertiesArray,
        final ExecutionContext context) {
        context.getLogger().info("Java Event Hub trigger function executed."+message);
        context.getLogger().info("SystemProperties for message[0]: EnqueuedTimeUtc=" + systemPropertiesArray[0].EnqueuedTimeUtc +" Offset=" +systemPropertiesArray[0].Offset+" PartitionKey="+ systemPropertiesArray[0].PartitionKey);

    }
    public static class SystemProperty {
        public String SequenceNumber;
        public String Offset;
        public String PartitionKey;
        public String EnqueuedTimeUtc;
    }
}

And here is the result. You could find the PartitionKey is available in the pic.


text:
Q: drawing dashed line using CALayer I was able to draw a dashed box, using the following code:
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
CGRect shapeRect = CGRectMake(0.0f, 0.0f, 200.0f, 100.0f);
[shapeLayer setBounds:shapeRect];
[shapeLayer setPosition:CGPointMake(self.coreImageView_.frameX, self.coreImageView_.frameBottom - self.coreImageView_.frameHeight/2)];
[shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
[shapeLayer setStrokeColor:[[UIColor whiteColor] CGColor]];
[shapeLayer setLineWidth:2.0f];
[shapeLayer setLineJoin:kCALineJoinRound];
[shapeLayer setLineDashPattern:
[NSArray arrayWithObjects:[NSNumber numberWithInt:5],
[NSNumber numberWithInt:5],
  nil]];

Now if I want to just draw a dashed line from point X to point B, how should I modify this code?

A: Lines are drawn by first moving the path to a starting point of the line, then adding a line segment to a point:
CGContextBeginPath(context);
CGContextMoveToPoint(context, 10.5f, 10.5f);
CGContextAddLineToPoint(context, 20.5f, 20.5f);
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFillStroke);

For drawing dashed line, You need to use CAShapeLayer
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
[shapeLayer setBounds:self.bounds];
[shapeLayer setPosition:self.center];
[shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
[shapeLayer setStrokeColor:[[UIColor blackColor] CGColor]];
[shapeLayer setLineWidth:3.0f];
[shapeLayer setLineJoin:kCALineJoinRound];
[shapeLayer setLineDashPattern:
 [NSArray arrayWithObjects:[NSNumber numberWithInt:10],
  [NSNumber numberWithInt:5],nil]];

// Setup the path
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 10, 10);
CGPathAddLineToPoint(path, NULL, 100,100);

[shapeLayer setPath:path];
CGPathRelease(path);

[[self layer] addSublayer:shapeLayer];

A: See:
https://developer.apple.com/library/mac/documentation/graphicsimaging/Reference/CGContext/Reference/reference.html#//apple_ref/c/func/CGContextSetLineDash
CGFloat dashLengths[] = { 10, 5 };
CGContextSetLineDash(context, 0, dashLengths, 2);

A: Swift 2.2
dropping this in here to save others time..
extension UIView {
    func addDashedLine(color: UIColor = UIColor.lightGrayColor()) {
        layer.sublayers?.filter({ $0.name == "DashedTopLine" }).map({ $0.removeFromSuperlayer() })
        self.backgroundColor = UIColor.clearColor()
        let cgColor = color.CGColor

        let shapeLayer: CAShapeLayer = CAShapeLayer()
        let frameSize = self.frame.size
        let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)

        shapeLayer.name = "DashedTopLine"
        shapeLayer.bounds = shapeRect
        shapeLayer.position = CGPoint(x: frameSize.width / 2, y: frameSize.height / 2)
        shapeLayer.fillColor = UIColor.clearColor().CGColor
        shapeLayer.strokeColor = cgColor
        shapeLayer.lineWidth = 1
        shapeLayer.lineJoin = kCALineJoinRound
        shapeLayer.lineDashPattern = [4, 4]

        let path: CGMutablePathRef = CGPathCreateMutable()
        CGPathMoveToPoint(path, nil, 0, 0)
        CGPathAddLineToPoint(path, nil, self.frame.width, 0)
        shapeLayer.path = path

        self.layer.addSublayer(shapeLayer)
    }
}

A: Try this code, it works for me,
Swift 3.0
extension UIView {
    func addDashedLine(strokeColor: UIColor, lineWidth: CGFloat) {

        backgroundColor = .clear

        let shapeLayer = CAShapeLayer()
        shapeLayer.name = "DashedTopLine"
        shapeLayer.bounds = bounds
        shapeLayer.position = CGPoint(x: frame.width / 2, y: frame.height / 2)
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = strokeColor.cgColor
        shapeLayer.lineWidth = lineWidth
        shapeLayer.lineJoin = kCALineJoinRound
        shapeLayer.lineDashPattern = [4, 4]

        let path = CGMutablePath()
        path.move(to: CGPoint.zero)
        path.addLine(to: CGPoint(x: frame.width, y: 0))
        shapeLayer.path = path

        layer.addSublayer(shapeLayer)
    }
}

A: Swift, more compact:
func addDashedLine(fromPoint start: CGPoint, toPoint end:CGPoint) {
    let line = CAShapeLayer()
    let linePath = UIBezierPath()
    linePath.moveToPoint(start)
    linePath.addLineToPoint(end)
    line.path = linePath.CGPath
    line.strokeColor = UIColor.redColor().CGColor
    line.lineWidth = 1
    line.lineJoin = kCALineJoinRound
    line.lineDashPattern = [4, 4]
    self.layer.addSublayer(line)
}

A: Below is the code snippet to draw a Dashed line in UIView (Xamarin iOS)
Note:
 separatorView is my UIView which i need to show as Dashed
 public void ShowDottedLine()
 {
      var dashedLayer = new CAShapeLayer();
      var frameSize = separatorView.Frame.Size;
      var shapeRect = new CGRect(0, 0, frameSize.Width, frameSize.Height);
      dashedLayer.Bounds = shapeRect;
      dashedLayer.Position = new CGPoint(frameSize.Width / 2, frameSize.Height / 2);
      dashedLayer.FillColor = UIColor.Clear.CGColor;
      dashedLayer.StrokeColor = ColorUtils.ColorWithHex(ColorConstants.DarkBlue).CGColor;
      dashedLayer.LineWidth = 2;
      dashedLayer.LineJoin = CAShapeLayer.JoinRound;
      NSNumber[] patternArray = {5,5};
      dashedLayer.LineDashPattern = Array;
      var path = new CGPath();
      path.MoveToPoint(CGPoint.Empty);
      path.AddLineToPoint(new CGPoint(frameSize.Width, 0));
      dashedLayer.Path = path;
      separatorView.Layer.AddSublayer(dashedLayer);
 }

A: Got it working in Objective C with the simplified code as below
   //Dashed line for road
    CAShapeLayer *dashedLine = [CAShapeLayer layer];
    [dashedLine setFrame:CGRectMake(0, 342, 100 , 100)];

    // Setup the path
    CGMutablePathRef thePath = CGPathCreateMutable();
    CGPathMoveToPoint(thePath, NULL, 0, 10);
    CGPathAddLineToPoint(thePath, NULL, screenSize.width,10);
    dashedLine.path = thePath;
    CGPathRelease(thePath);

    [dashedLine setLineDashPattern: [NSArray arrayWithObjects:[NSNumber numberWithFloat:15], nil]];
    dashedLine.lineWidth = 1.0f;
    dashedLine.strokeColor =  [[UIColor redcolor] CGColor]];

    [self.view.layer addSublayer:dashedLine];

A: CAShapeLayer *shaplayer = [CAShapeLayer layer];
    shaplayer.frame = CGRectMake(100, 100, 100, 100);
    [self.view.layer addSublayer:shaplayer];
    UIBezierPath *uipath = [UIBezierPath bezierPath];
    [uipath moveToPoint:CGPointMake(50, 200)];
    [uipath addLineToPoint:CGPointMake(250, 200)];
    shaplayer.path = uipath.CGPath;
    shaplayer.strokeColor = [UIColor redColor].CGColor;
    shaplayer.lineDashPattern = @[@4];


text:
Q: Access $rootScope through controller not working I have the following code, which is trying to add a variable to the $rootScope through a directive and trying to get that value and show it inside a controller element.
But when I click the links inside the directive, it doesn't display the new $rootScope variable.
https://plnkr.co/edit/P7Lq7h13RmXryFC0uBMi?p=info
var mod = angular.module('myApp', []);

mod.directive('mainMenu', menuDirec);

function menuDirec($rootScope){
  return {
    templateUrl: 'menu.html',
    restrict: 'A',
    controller: menuControl,
    controllerAs: 'vm'
  };

  function menuControl(){
    var vm = this;

    vm.menu = {
      'one': 'Link 1',
      'two': 'Link 2',
      'three': 'Link 3',
      'four': 'Link 4'
    };
    vm.clickMenu = function(slug){
      $rootScope.active = slug;

      console.log($rootScope);
      console.log(slug);
    }
  }
}

mod.controller('content', contentControl);

function contentControl($scope, $rootScope){
  $scope.title = $rootScope.active;
}

A: Change the HTML to access the title as a function

{{ title() }}

In your JS make it a function
mod.controller('content', contentControl);

function contentControl($scope, $rootScope){
  $scope.title = function () {
    return $scope.active;
  };
}

Then on each digest cycle, the $watch attached to the {{title()}} will execute the function and update the DOM as the value of $scope.active changes.
The UPDATE on PLNKR.

Best practice
Avoid cluttering $rootScope with variables. Instead use isolate scope and two-way binding. For more information, see AngularJS Comprehensive Directive API - scope.

As example
mod.directive('mainMenu', menuDirec);

function menuDirec(){
  return {
    templateUrl: 'menu.html',
    restrict: 'A',
    controller: menuControl,
    controllerAs: 'vm',
    scope: { active: '=' },
    bindToController: true
  };

  function menuControl(){
    var vm = this;

    vm.menu = {
      'one': 'Link 1',
      'two': 'Link 2',
      'three': 'Link 3',
      'four': 'Link 4'
    };
    vm.clickMenu = function(slug){
      vm.active = slug;
      console.log(slug);
    }
  }
}

HTML

{{ title }}

The DEMO on PLNKR


text:
Q: Do high-temperature rated coin cells exist? I'm currently working on a project that will implement a coin cell as its primary power source. My PCB will likely be exposed to high temperatures ranging from 100C upwards. Now I realize that I will likely need a proper enclosure along with other cooling capabilities, however, I would still like to select the highest temperature rated coin cell possible.
So I'm curious if anyone is aware of coin cells that possess high temperature ratings. Also, what would determine whether or not a coin cell possesses high temperature rating? Would it primarily be based upon battery type (alkaline, lithium, etc.), or would it depend primarily on how the battery was manufactured?
Thanks!

A: Lithium thionyl chloride primary cells have been rated up to 150degC, but you will need to consult the manufacturer with regards to cell size and actual temperature rating.


text:
Q: Bash 'swallowing' sub-shell children process when executing a single command Bumped into an unexpected bash/sh behavior and I wonder someone can explain the rationale behind it, and provide a solution to the question below.
In an interactive bash shell session, I execute:
$ bash -c 'sleep 10 && echo'
With ps on Linux it looks like this:
\_ -bash
   \_ bash -c sleep 10 && echo
     \_ sleep 10
The process tree is what I would expect:

*

*My interactive bash shell process ($)

*A children shell process (bash -c ...)

*a sleep children process

However, if the command portion of my bash -c is a single command, e.g.:
$ bash -c 'sleep 10'
Then the middle sub-shell is swallowed, and my interactive terminal session executes sleep "directly" as children process.
The process tree looks like this:
\_ -bash
   \_ sleep 10
So from process tree perspective, these two produce the same result:

*

*$ bash -c 'sleep 10'

*$ sleep 10
What is going on here?
Now to my question: is there a way to force the intermediate shell, regardless of the complexity of the expression passed to bash -c ...?
(I could append something like ; echo; to my actual command and that "works", but I'd rather not. Is there a more proper way to force the intermediate process into existence?)
(edit: typo in ps output; removed sh tag as suggested in comments; one more typo)

A: There's actually a comment in the bash source that describes much of the rationale for this feature:
/* If this is a simple command, tell execute_disk_command that it
   might be able to get away without forking and simply exec.
   This means things like ( sleep 10 ) will only cause one fork.
   If we're timing the command or inverting its return value, however,
   we cannot do this optimization. */
if ((user_subshell || user_coproc) && (tcom->type == cm_simple || tcom->type == cm_subshell) &&
    ((tcom->flags & CMD_TIME_PIPELINE) == 0) &&
    ((tcom->flags & CMD_INVERT_RETURN) == 0))
  {
    tcom->flags |= CMD_NO_FORK;
    if (tcom->type == cm_simple)
      tcom->value.Simple->flags |= CMD_NO_FORK;
  }

In the bash -c '...' case, the CMD_NO_FORK flag is set when determined by  the should_suppress_fork function in builtins/evalstring.c.
It is always to your benefit to let the shell do this. It only happens when:

*

*Input is from a hardcoded string, and the shell is at the last command in that string.

*There are no further commands, traps, hooks, etc. to be run after the command is complete.

*The exit status does not need to be inverted or otherwise modified.

*No redirections need to be backed out.

This saves memory, causes the startup time of the process to be slightly faster (since it doesn't need to be forked), and ensures that signals delivered to your PID go direct to the process you're running, making it possible for the parent of sh -c 'sleep 10' to determine exactly which signal killed sleep, should it in fact be killed by a signal.
However, if for some reason you want to inhibit it, you need but set a trap -- any trap will do:
# run the noop command (:) at exit
bash -c 'trap : EXIT; sleep 10'


text:
Q: Record(s) cannot be read; no read permission on  I am getting one of those warning messages which states, "Record(s) cannot be read; no read permission on ".  Here is what I've done thus far:

*

*Checked the permissions and confirmed that all the relevant tables,
forms, queries and reports are accessible by Admin (me).

*Run Compact & Repair.

*Deleted the table in question and re-created from scratch.

None of these has solved the problem.  In addition, I can open the table in question directly.
This particular Access database has been copied over from a template and customized for a specific clinical study.  This warning message is occurring with numerous Access databases and started appearing after we upgraded from Office 2003 to 2010.


text:
Q: Configure ipython to automatically use certain settings like doctest_mode on I know ipython has a very extensive configuration system.  I've looked all over in the generated ipython_config.py file for a way to configure certain settings.  I would like to always start ipython with %doctest_mode on.
Is there an easy way to do this?  I've tried adding this command in the c.TerminalIpythonApp.code_to_run configuration option.  However, this causes ipython to start up, run the command and exit instead of being interactive.

A: Instead of code_to_run, find these lines in your config file:
# lines of code to run at IPython startup.
# c.InteractiveShellApp.exec_lines = []

If you put commands in there, they'll be executed, and you can use IPython interactively.


text:
Q: How does clang++ 9.0 magically cure dangling reference use in a lambda? I was experimenting on wandbox in hopes of finding compiler warnings that would help with inadvertent dangling references in lambdas. I had this example which misbehaves in multiple ways:
std::array<std::function<const int *(void)>,N> createFunctions()
{
    std::array<std::function<const int *(void)>,N> fns;
    for ( int i = 0 ; i < N ; i++ ) {
        std::cout << &i << " ";
        fns[i] = [&]() {
            return &i;
        };
    }
    std::cout << "\n";
    return fns;
}

This stuffs a set of lambdas into an array of functions. Each lambda returns a pointer to a reference to a captured variable, i. Should be trouble all around.
My driver routine prints out the pointer, and dereferences it as well.
int main()
{
  auto fns = createFunctions();
  for (int j = 0 ; j < N ; j++ ) {
    if (j != 0)
      std::cout << ", ";
    std::cout << fns[j]() << ": " << *fns[j]();
  }
  std::cout << "\n";
  return 0;
}

If this lambda was modified to pass i by copy, you'd get output like this - four pointers, and four pointers with unique values:
0x7ffc80e65358 0x7ffc80e65358 0x7ffc80e65358 0x7ffc80e65358
0x7ffc80e65380: 0, 0x7ffc80e653a0: 1, 0x7ffc80e653c0: 2, 0x7ffc80e653e0: 3

When it is written in error, taking a reference that passes silently out of scope, it miraculously runs without faulting, but clearly shows the error of its ways
0x7ffeebdfe9f4 0x7ffeebdfe9f4 0x7ffeebdfe9f4 0x7ffeebdfe9f4
0x7ffeebdfe9f4: 32766, 0x7ffeebdfe9f4: 32766, 0x7ffeebdfe9f4: 32766, 0x7ffeebdfe9f4: 32766

All four pointers are identical, and the value they are pointing to is bogus.
This is the case for all versions of g++, and all versions of clang++ up to 8.x. But clang 9.0 miraculously deals with it in a magical way:
0x7ffd193bfa30 0x7ffd193bfa30 0x7ffd193bfa30 0x7ffd193bfa30
0x7ffd193bfa30: 0, 0x7ffd193bfa30: 1, 0x7ffd193bfa30: 2, 0x7ffd193bfa30: 3

The part that is really interesting is that the pointer to the reference has the same value in all four lambdas - but dereferencing them returns four different values. I have tried to come up with a good explanation for how this can be, but I'm stumped.
I'm guessing that it is an intentional optimization in which the compiler has deduced what I want to do, and makes it happen. Since using a dangling reference falls into that "undefined behavior" category, the compiler is free to do what it likes. But is this the case?
If the compiler is smart enough to figure that out, it seems like it would be smart enough to issue a warning, but I don't get that.

A: Based on the comment train, and in particular a comment from @RaymondChen, it became clear that clang did not fix this problem. The generated code made it look like they fixed it, but it was just some very fortuitous undefined behavior.
With almost 100% certainty, we can say this:

*

*The lambda functions created a dangling reference to variable i, an auto which disappeared from the stack before the lambdas were used.

*Calling the lambda then pointed to random data on or around the stack, the value of which could be anything.

*In most of the implementations, the value pointed to was clearly not what was desired.

*In clang 9, luckily enough, the dangling reference pointer was pointing to loop variable j, which was in scope, and was iterating from 0 to 3, making it appear as if we somehow had a good copy of the dangling reference.

Changing the loop in main() to iterate of the lambda references like this:
   for (auto fn: fns ) {

eliminates loop variable j, so now the output is:
0x7ffc0f21a100 0x7ffc0f21a100 0x7ffc0f21a100 0x7ffc0f21a100
0x7ffc0f21a100: 4212390, 0x7ffc0f21a100: 4212390, 0x7ffc0f21a100: 4212390, 0x7ffc0f21a100: 4212390

Still looking for good ways to detect this kind of programming error that gives us an adjunct to eternal human vigilance. Herb Sutter's Lifetime profile would be a really good way of doing this, if it ever comes to pass.


text: Q: apt-get purge package does not delete! I am trying to fully uninstall PHP. I tried apt-get purge php7.3. But after my installation, the folder in /etc/ is still there and filled with data. Why? I also did autoremove.


text:
Q: How to add the shipping TITLE to admin sales grid I want to add the shipping method ( shipping title NOT shipping description ) to the admin sales grid.
I've already added the shipping description using this code
$collection->getSelect()
       ->join('magento_sales_flat_order',
              'main_table.entity_id = magento_sales_flat_order.entity_id',
               array('shipping_description'));
$this->setCollection($collection);

but this is not what i want, i want only the shipping title whithout the method name.


text:
Q: How do I disable/toggle gestures in C4ios? Reading through the documentation here.
I know how to successfully setup PAN gestures for a C4Object. How would I disable a PAN gesture though?
Using...
[object setUserInteractionEnabled:NO]

... disables all gestures including TAP events and...
object.gestureRecognizers = NO

... doesn't allow me to reinitialize PAN gestures.
If anyone could share with me how disable PAN gestures (toggle PAN on/off) without effecting other gesture events it would be greatly appreciated.

A: You can get access to the gestures that you add to an object by using the gestureForName: method, which returns a UIGestureRecognizer object. From there, you can interact with that gesture recognizer and change its properties directly.
To toggle on/off a gesture recognizer, all you have to do is change the value of its enabled property.
The following works for me:
#import "C4WorkSpace.h"

@implementation C4WorkSpace {
    UIGestureRecognizer *gesture;
    C4Shape *square, *circle;
}

-(void)setup {
    square = [C4Shape rect:CGRectMake(0, 0, 100, 100)];
    square.center = self.canvas.center;

    circle = [C4Shape ellipse:square.frame];
    circle.center = CGPointMake(square.center.x, square.center.y + 200);
    [self listenFor:@"touchesBegan" fromObject:circle andRunMethod:@"toggle"];

    [self.canvas addObjects:@[square, circle]];

    [square addGesture:PAN name:@"thePan" action:@"move:"];
    gesture = [square gestureForName:@"thePan"];
}

-(void)toggle {
    gesture.enabled = !gesture.isEnabled;
    if(gesture.enabled == YES) square.fillColor = C4GREY;
    else square.fillColor = C4RED;
}

@end

The key part of this example is the following:
    [square addGesture:PAN name:@"thePan" action:@"move:"];
    gesture = [square gestureForName:@"thePan"];

Notice, in the implementation there is a UIGestureRecognizer variable called gesture. What we do on the second line is find the PAN gesture associated with the square object and keep a reference to it.
Then, whenever we toggle by touching the circle we do the following:
gesture.enabled = !gesture.isEnabled;

That is, if the gesture is enabled then disable it (and vice-versa).
You can check out more on the UIGestureRecognizer Class Reference


text:
Q: VBA OCR via API https://ocr.space i would like to use the API of https://ocr.space/ to look for given text positions.
I saw some topics but none of them was VBA related.
My code at the moment is:
Sub test()
Dim pic As String
Dim httpReq As New XMLHTTP60
Dim UserName, Key As String
UserName = Sheets("main").Range("B8")
Key = Sheets("main").Range("B9")

pic = "C:\Users\myname\Desktop\Capture.png"
pic = EncodeFile(pic)

     strURL = "https://api.ocr.space/Parse/Image"
     httpReq.Open "POST", strURL, False, UserName, Key

     httpReq.setRequestHeader "Content-Type", "form-data" '  "application/x-www-form-urlencoded?"
     httpReq.setRequestHeader UserName, Key
     httpReq.send "base64Image=data:image/png;base64," & pic & "&isOverlayRequired=true"

     resp = httpReq.responseText

MsgBox resp

End Sub

The code I use to get the base64 string of the picture is the following, however it seems to work fine, as I can get back the picture if i paste it to an online converter.
Public Function EncodeFile(strPicPath As String) As String
    Const adTypeBinary = 1          ' Binary file is encoded

    ' Variables for encoding
    Dim objXML
    Dim objDocElem

    ' Variable for reading binary picture
    Dim objStream

    ' Open data stream from picture
    Set objStream = CreateObject("ADODB.Stream")
    objStream.Type = adTypeBinary
    objStream.Open
    objStream.LoadFromFile (strPicPath)

    ' Create XML Document object and root node
    ' that will contain the data
    Set objXML = CreateObject("MSXml2.DOMDocument")
    Set objDocElem = objXML.createElement("Base64Data")
    objDocElem.DataType = "bin.base64"

    ' Set binary value
    objDocElem.nodeTypedValue = objStream.Read()

    ' Get base64 value
    EncodeFile = objDocElem.Text

    ' Clean all
    Set objXML = Nothing
    Set objDocElem = Nothing
    Set objStream = Nothing

End Function

Could you please help me to find what do I do wrong?

A: I tried a different approach.
Now I upload the files itself instead of creating a base64 string ( as I would have the picture on my pc anyway).
The code is copied from somewhere, but I can not recall where I found it.
Sub uploader()

a = Upload("https://api.ocr.space/Parse/Image", "C:\Users\xxxxxxxxxxxxxxxxx\Desktop\Capture.png", "isOverlayRequired=true", "isOverlayRequired=true")

MsgBox a

End Sub

Function Upload(strUploadUrl, strFilePath, strFileField, strDataPairs)

Const MULTIPART_BOUNDARY = "---------------------------0123456789012"
Dim ado, rs
Dim lngCount
Dim bytFormData, bytFormStart, bytFormEnd, bytFile
Dim strFormStart, strFormEnd, strDataPair
Dim web

UserName = Sheets("main").Range("B8")
Key = Sheets("main").Range("B9")

Const adLongVarBinary = 205
    'Read the file into a byte array
    Set ado = CreateObject("ADODB.Stream")
    ado.Type = 1
    ado.Open
    ado.LoadFromFile strFilePath
    bytFile = ado.Read
    ado.Close
    'Create the multipart form data.
    'Define the end of form
    strFormEnd = vbCrLf & "--" & MULTIPART_BOUNDARY & "--" & vbCrLf
    'First add any ordinary form data pairs
    strFormStart = ""
    For Each strDataPair In Split(strDataPairs, "|")
        strFormStart = strFormStart & "--" & MULTIPART_BOUNDARY & vbCrLf
        strFormStart = strFormStart & "Content-Disposition: form-data; "
        strFormStart = strFormStart & "name=""" & Split(strDataPair, "=")(0) & """"
        strFormStart = strFormStart & vbCrLf & vbCrLf
        strFormStart = strFormStart & Split(strDataPair, "=")(1)
        strFormStart = strFormStart & vbCrLf
    Next
    'Now add the header for the uploaded file
    strFormStart = strFormStart & "--" & MULTIPART_BOUNDARY & vbCrLf
    strFormStart = strFormStart & "Content-Disposition: form-data; "
    strFormStart = strFormStart & "name=""" & strFileField & """; "
    strFormStart = strFormStart & "filename=""" & Mid(strFilePath, InStrRev(strFilePath, "\") + 1) & """"
    strFormStart = strFormStart & vbCrLf
    strFormStart = strFormStart & "Content-Type: application/upload" 'bogus, but it works
    strFormStart = strFormStart & vbCrLf & vbCrLf

    'Create a recordset large enough to hold everything
    Set rs = CreateObject("ADODB.Recordset")
    rs.Fields.Append "FormData", adLongVarBinary, Len(strFormStart) + LenB(bytFile) + Len(strFormEnd)
    rs.Open
    rs.AddNew
    'Convert form data so far to zero-terminated byte array
    For lngCount = 1 To Len(strFormStart)
        bytFormStart = bytFormStart & ChrB(Asc(Mid(strFormStart, lngCount, 1)))
    Next
    rs("FormData").AppendChunk bytFormStart & ChrB(0)
    bytFormStart = rs("formData").GetChunk(Len(strFormStart))
    rs("FormData") = ""
    'Get the end boundary as a zero-terminated byte array
    For lngCount = 1 To Len(strFormEnd)
        bytFormEnd = bytFormEnd & ChrB(Asc(Mid(strFormEnd, lngCount, 1)))
    Next
    rs("FormData").AppendChunk bytFormEnd & ChrB(0)
    bytFormEnd = rs("formData").GetChunk(Len(strFormEnd))
    rs("FormData") = ""
    'Now merge it all
    rs("FormData").AppendChunk bytFormStart
    rs("FormData").AppendChunk bytFile
    rs("FormData").AppendChunk bytFormEnd
    bytFormData = rs("FormData")
    rs.Close
    'Upload it
    Set web = CreateObject("WinHttp.WinHttpRequest.5.1")
    web.Open "POST", strUploadUrl, False
    web.setRequestHeader "Content-Type", "multipart/form-data; boundary=" & MULTIPART_BOUNDARY
    web.setRequestHeader UserName, Key
    web.setRequestHeader "isOverlayRequired", "true"
    web.send bytFormData

    Upload = web.responseText

End Function

Finally after like 2 months i have a solution :D
I just had to register here :P


text:
Q: I havent'got any SWF file but Getting popup message - This page requires AC_RunActiveContent.js I haven't got any  .swf file on my web page but getting popup message This page requires AC_RunActiveContent.js. And my web page not working. I'm using Jquery library, colorbox and responsiveSlide plugin. Can someone help me ?
link my website
------ Edit - Solved
If you use some plugins on your browser you could get this error. Because some plugins need this file. I upload this JS file into root directory on FTP and problem is solved.

A: If you don't have Flash, remove this line:
<script src="js/AC_RunActiveContent.js"></script>

The file is not found anyway, and you don't need it...


text:
Q: jQuery Ajax character issue with IE I am facing a strange problem. I am posting some data using jQuery Ajax method.
$.ajax({
            type: "POST",
            url: '/Member/GetPagedResult?page=1'
                + '&company=' + $('#CompanyName').val().trim()
                + '&member=' + $('#MemberLastName').val().trim()
                + '&regionID=' + $('#SelectedRegionID').val()
                + '&year=' + $('#SelectedAwardYear').val(),

But in MVC controller when posting some Latin characters(ôté) from Chrome I am getting correct value, but when it is from IE getting some special characters instead of right value. Please see the screenshot below. I tried setting contentType 'application/json; accept-charset=UTF-8' but not working
How can I get the correct value in MVC from all browsers?


text:
Q: Haskell parameter is not right? I am new haskell leaner, my code as follows:
{-- snippet all --}
{- | Our usual CustomColor type to play with -}
data CustomColor =
  CustomColor {red :: Int,
               green :: Int,
               blue :: Int}
  deriving (Eq, Show, Read)

{- | A new type that stores a name and a function.

The function takes an Int, applies some computation to it, and returns
an Int along with a CustomColor -}
data FuncRec =
    FuncRec {name :: String,
             colorCalc :: Int -> (CustomColor, Int)}

plus5func color x = (color, x + 5)

purple = CustomColor 255 0 255

plus5 = FuncRec {name = "plus5", colorCalc = plus5func purple }
always0 = FuncRec {name = "always0", colorCalc = \_ -> (purple, 0)}
{-- /snippet all --}

In the line "colorCalc=plus5func purple", why there are just one parameter("purple") after plus5func, actually plus5func should need two parameters?

A: The definition
plus5func color x = (color, x + 5)

is equivalent to
plus5func color = f
    where f x = (color, x + 5)

In other words: plus5func actually takes only one argument (color) ad returns a function f. This returned function takes one argument (x) and returns the final color&int pair.
This is the style in which "binary" functions are usually represented in Haskell and other functional languages. This style is named "Currying" after the mathematician/computer scientist "Haskell Curry".
You can use such function as they were binary functions because
plus5func color x
= (plus5func color) x
= f x                      {- where f is as above -}
= (color, x + 5)

As a bonus you get "partial application", namely the ability of passing fewer arguments (one in this case) and getting a function of the remaning arguments to be passed (f in this case).
So, the line
plus5 = FuncRec {name = "plus5", colorCalc = plus5func purple }

actually means
plus5 = FuncRec {name = "plus5", colorCalc = f }
     where f x = plus5func purple x

A: All functions in haskell are implicitly curried. This means that when you write a function like
f x y = x + y

You're really doing something more like
f = \x -> \y -> x + y

That is, f is a function that maps x to another function that maps y to x + y.
So f 5 is really the function \y -> 5 + y.

A: You can apply parameters to a function partially. It means you give the first parameter now and the second parameter later.
For example:
(+) :: Num a => a -> a -> a
(1+) :: Num a => a -> a
(1+1) :: Num a => a


text:
Q: Dynamodb updateitem only with global secondary index Can we update a dynamodb item only with global secondary index?
$response = $dynamodbClient->updateItem(array(
            'TableName' => 'feed',
            'Key' => array(
                'feed_guid'      => array('S' => 'ac1e9683832ad2923f0bd84b91f34381'),
                'created_date'   => array('N' => '1439295833'),
            ),
            "ExpressionAttributeValues" =>  array (
                    ":val1" => array('N' => '1')
                ) ,
            "UpdateExpression" => $updateExpression,
            'ReturnValues' => 'ALL_NEW'
        ));

In the above code, I want to replace the key section and update the item using a global secondary index, that is user_id.

A: A workaround I used for this was to first execute a query command using the document client, then extract the partition key from the result, and call the update method with my retrieved value as the key.

A: No, you cannot update items in a GSI. You make changes/updates to items in the table and those updates are propagated to the GSIs.


text:
Q: how to solve W:Some index files failed to download. They have been ignored, or old ones used instead I use Ubuntu 18.04.4 and when I run "sudo apt-get update", I get the following error.
Err:1 http://repo.mysql.com/apt/ubuntu bionic InRelease
  Could not connect to repo.mysql.com:80 (23.213.169.17), connection timed out
Err:2 http://ny-mirrors.evowise.com/ubuntu bionic InRelease
  Cannot initiate the connection to ny-mirrors.evowise.com:80 (2606:4700:10::6816:4b3). - connect (101: Network is unreachable) Cannot initiate the connection to ny-mirrors.evowise.com:80 (2606:4700:10::6816:5b3). - connect (101: Network is unreachable) Could not connect to ny-mirrors.evowise.com:80 (104.22.5.179), connection timed out Could not connect to ny-mirrors.evowise.com:80 (104.22.4.179), connection timed out
Err:3 http://ny-mirrors.evowise.com/ubuntu bionic-updates InRelease
  Cannot initiate the connection to ny-mirrors.evowise.com:80 (2606:4700:10::6816:4b3). - connect (101: Network is unreachable) Cannot initiate the connection to ny-mirrors.evowise.com:80 (2606:4700:10::6816:5b3). - connect (101: Network is unreachable)
Err:4 http://ny-mirrors.evowise.com/ubuntu bionic-backports InRelease
  Cannot initiate the connection to ny-mirrors.evowise.com:80 (2606:4700:10::6816:4b3). - connect (101: Network is unreachable) Cannot initiate the connection to ny-mirrors.evowise.com:80 (2606:4700:10::6816:5b3). - connect (101: Network is unreachable)
Err:5 http://ny-mirrors.evowise.com/ubuntu bionic-security InRelease
  Cannot initiate the connection to ny-mirrors.evowise.com:80 (2606:4700:10::6816:4b3). - connect (101: Network is unreachable) Cannot initiate the connection to ny-mirrors.evowise.com:80 (2606:4700:10::6816:5b3). - connect (101: Network is unreachable)
Err:6 http://ppa.launchpad.net/samoilov-lex/aftl-stable/ubuntu artful InRelease
  Cannot initiate the connection to ppa.launchpad.net:80 (2001:67c:1560:8008::15). - connect (101: Network is unreachable) Could not connect to ppa.launchpad.net:80 (91.189.95.83), connection timed out
Err:7 http://ppa.launchpad.net/vikoadi/ppa/ubuntu bionic InRelease
  Cannot initiate the connection to ppa.launchpad.net:80 (2001:67c:1560:8008::15). - connect (101: Network is unreachable)
Err:8 http://packages.microsoft.com/repos/vscode stable InRelease
  Connection failed [IP: 104.214.230.139 80]
Err:9 http://archive.canonical.com/ubuntu bionic InRelease
  Connection failed [IP: 91.189.91.15 80]
Reading package lists... Done
W: Failed to fetch http://ny-mirrors.evowise.com/ubuntu/dists/bionic/InRelease  Cannot initiate the connection to ny-mirrors.evowise.com:80 (2606:4700:10::6816:4b3). - connect (101: Network is unreachable) Cannot initiate the connection to ny-mirrors.evowise.com:80 (2606:4700:10::6816:5b3). - connect (101: Network is unreachable) Could not connect to ny-mirrors.evowise.com:80 (104.22.5.179), connection timed out Could not connect to ny-mirrors.evowise.com:80 (104.22.4.179), connection timed out
W: Failed to fetch http://ny-mirrors.evowise.com/ubuntu/dists/bionic-updates/InRelease  Cannot initiate the connection to ny-mirrors.evowise.com:80 (2606:4700:10::6816:4b3). - connect (101: Network is unreachable) Cannot initiate the connection to ny-mirrors.evowise.com:80 (2606:4700:10::6816:5b3). - connect (101: Network is unreachable)
W: Failed to fetch http://ny-mirrors.evowise.com/ubuntu/dists/bionic-backports/InRelease  Cannot initiate the connection to ny-mirrors.evowise.com:80 (2606:4700:10::6816:4b3). - connect (101: Network is unreachable) Cannot initiate the connection to ny-mirrors.evowise.com:80 (2606:4700:10::6816:5b3). - connect (101: Network is unreachable)
W: Failed to fetch http://archive.canonical.com/ubuntu/dists/bionic/InRelease  Connection failed [IP: 91.189.91.15 80]
W: Failed to fetch http://ny-mirrors.evowise.com/ubuntu/dists/bionic-security/InRelease  Cannot initiate the connection to ny-mirrors.evowise.com:80 (2606:4700:10::6816:4b3). - connect (101: Network is unreachable) Cannot initiate the connection to ny-mirrors.evowise.com:80 (2606:4700:10::6816:5b3). - connect (101: Network is unreachable)
W: Failed to fetch http://ppa.launchpad.net/samoilov-lex/aftl-stable/ubuntu/dists/artful/InRelease  Cannot initiate the connection to ppa.launchpad.net:80 (2001:67c:1560:8008::15). - connect (101: Network is unreachable) Could not connect to ppa.launchpad.net:80 (91.189.95.83), connection timed out
W: Failed to fetch http://repo.mysql.com/apt/ubuntu/dists/bionic/InRelease  Could not connect to repo.mysql.com:80 (23.213.169.17), connection timed out
W: Failed to fetch http://ppa.launchpad.net/vikoadi/ppa/ubuntu/dists/bionic/InRelease  Cannot initiate the connection to ppa.launchpad.net:80 (2001:67c:1560:8008::15). - connect (101: Network is unreachable)
W: Failed to fetch http://packages.microsoft.com/repos/vscode/dists/stable/InRelease  Connection failed [IP: 104.214.230.139 80]
W: Some index files failed to download. They have been ignored, or old ones used instead.

I tried some solution but nothing help.


text:
Q: Error when trying to Sandbox with codesign command I am trying to Sandbox my OS X app using the codesign command (this is a common lisp app and does not use Xcode).  I have created a very basic enitlements plist that looks like this:
<?xml version="1.0" encoding="utf-8"?>
<plist version="1.0">
    <dict>
        <key>com.apple.security.app-sandbox</key>
        <true/>
    </dict>
</plist>

and I am calling the codesign command:
codesign -s - -f --entitlements "/path/to/my/app/MyApp.app/Contents/entitlements.plist" "/path/to/my/app/MyApp.app/"

But this command returns the following error:
/path/to/my/app/MyApp.app/Contents/entitlements.plist: cannot read entitlement data

Does this error mean that I have used the wrong command?  If so what is wrong with the command?

A: The Xcode generated plist is binary format and looks like this for a fairly standard limited sandbox setup:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.developer.ubiquity-container-identifiers</key>
    <array>
        <string>$(TeamIdentifierPrefix)com.company.appanme</string>
    </array>
    <key>com.apple.developer.ubiquity-kvstore-identifier</key>
    <string>$(TeamIdentifierPrefix)com.company.appname</string>
    <key>com.apple.security.app-sandbox</key>
    <true/>
    <key>com.apple.security.assets.movies.read-only</key>
    <true/>
    <key>com.apple.security.assets.music.read-only</key>
    <true/>
    <key>com.apple.security.assets.pictures.read-only</key>
    <true/>
    <key>com.apple.security.files.user-selected.read-write</key>
    <true/>
    <key>com.apple.security.network.client</key>
    <true/>
    <key>com.apple.security.print</key>
    <true/>
    <key>com.apple.security.files.bookmarks.document-scope</key>
    <true/>
</dict>
</plist>

All I can suggest is use Xcode to construct the plist and stripping those keys that you dont want manually. In your case...
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.security.app-sandbox</key>
    <true/>
    <key>com.apple.security.files.user-selected.read-write</key>
    <true/>
    <key>com.apple.security.network.client</key>
    <true/>
</dict>
</plist>

I'm just wondering if the !DOCTYPE element is required for some reason by the signing tool and the encoding attribute should be upper case.
I've also left in a couple of keys which may be needed even if as you say its a basic lisp app in particular the com.apple.security.files.user-selected.read-write key which will give your process file access.

A: For people that find this from a Google search:
I got an almost-identical error:
~/Desktop/Instagram.xcent: cannot read entitlement data
The solution was to not use ~ in the path, but instead /Users/...


text:
Q: ALWAYS Getting the same ID from the different dropped images I have 7 different divs (From #rang1 to #rang7) and I can drop images on them.
The images with the class .DraggedItem come from a database and all of them have different ID's. I display these images by the normal fetch_assoc. If it's necessary for you to see the code of doing this please tell me so I can post it. But it's really the regular fetch_assoc method.
With no further talking let's jump into the code
The JS:

The HTML:
<form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="POST">
<input type="hidden" value="<?php echo $row["IDBewoner"] ?>" name="bewoner">

    <input type="hidden" value="" id="rang1input" name="rang1value">

    <input type="hidden" value="" id="rang2input" name="rang2value">

    <input type="hidden" value="" id="rang3input" name="rang3value">

    <input type="hidden" value="" id="rang4input" name="rang4value">

    <input type="hidden" value="" id="rang5input" name="rang5value">

    <input type="hidden" value="" id="rang6input" name="rang6value">

    <input type="hidden" value="" id="rang7input" name="rang7value">

<input type="submit" value="Save">
</form>

The PHP code:
<?php

if($_SERVER["REQUEST_METHOD"] == "POST") {
    $rang1 = $_POST["rang1value"];
    $rang2 = $_POST["rang1value"];
    $rang3 = $_POST["rang1value"];
    $rang4 = $_POST["rang1value"];
    $rang5 = $_POST["rang1value"];
    $rang6 = $_POST["rang1value"];
    $rang7 = $_POST["rang1value"];
    $bewonerID = $_POST["bewoner"];

    echo "";
    echo "";
    echo "";
    echo "";
    echo "";
    echo "";
    echo "";
    }
?>

The problem is that I'm always getting the same ID when i submit the form.
I think it's something wrong with the script not the php code. I tried to get the id of the dropped images in different ways.
I do have different images with different id's but I'm always getting the same id over and over again.

A: I think you are always looking for the same POST value, try this:
$rang1 = $_POST["rang1value"];
$rang2 = $_POST["rang2value"];
$rang3 = $_POST["rang3value"];
$rang4 = $_POST["rang4value"];
$rang5 = $_POST["rang5value"];
$rang6 = $_POST["rang6value"];
$rang7 = $_POST["rang7value"];


text:
Q: CSS Footer color! Can`t change it! I'm trying to change the footer color for my site. I've tried everything, but it does not seem to work!
Here's the link for my CSS: http://pp.atoanavida.com.br/style2.css
Here's the page: http://pp.atoanavida.com.br
Thanks!!!!

A: You got some invalid css in your code.
Under #footer, change background: { #77aadd !important;} to:
either background: #77aadd !important;
or background-color: #77aadd !important;
edit
In your HTML, add

 right before closing the
 (right after closing
).

A: Replace
#footer {
    clear: both;
    background: { #77aadd !important;}
    margin: 0; padding: 0;
    font: normal .95em/1.5em 'Tahoma', Trebuchet MS, Sans-serif;
    width:100%;

}

with
#footer {
    clear: both;
    background-color:  #77aadd !important;
    margin: 0; padding: 0;
    font: normal .95em/1.5em 'Tahoma', Trebuchet MS, Sans-serif;
    width:100%;

}

#footer-content also has the same problem with syntax, replace
#footer-content {
    border-top: 0px solid #EAEAEA;
    margin: 0 auto;
    padding-left: 15px auto;
    background: { #77aadd !important;}
    width:100%;
}

with
#footer-content {
    border-top: 0px solid #EAEAEA;
    margin: 0 auto;
    padding-left: 15px;
    background-color: #77aadd !important;
    width:100%;
}

A: You need to clear the floated elements inside #footer-content.
An easy way to do this is to add overflow: hidden to the CSS for #footer-content.
I recommend you read an article like this one, to learn more: http://css-tricks.com/all-about-floats/


text:
Q: CSS change style base on valid input I'm trying to style the asterisk ("*") inside the span element of a required field based on the "input:valid" property.
<apex:input value="{!firstName}" id="firstnameId" required="true" />
      First Name

      *

I want to change the color of the "*" From Red to Green, If the input is valid.
How can I achive it using css?
I tried this :
input:valid .ddff {
      color: palegreen;
 }

But it not working.
I know I can do it in JS as well, but I have a lot of fields to change so I would like a css way if it is possible.
Thanks!

A: You can use below css and html for your problem. It will work.

    <apex:input id="firstnameId" required="true" />
      First Name
    *

A: Create Custom label put the custom label value * and use it this custom label on vfpage.
for eg:
  {!$Label.**your_custom_label_name**}

A: Eventually what I did is :
input:valid + label .ddff {
   color: palegreen;
}

.ddff{
   color: red;
}

And I removed the inline CSS in my span :
<apex:input value="{!firstName}" id="firstnameId" required="true" />
      First Name

      *


text:
Q: Can't insert a row in database I've got a little problem.
My php script won't insert a row in the database.
Here is my script:
INSERT INTO Keys (Key, Id1, Id2, Id3, Id4, Id5)
VALUES ('kjlkjl', 986, 87, 7, 8, 5)

Hastebin script
I always get the error:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Keys (Key, Id1, Id2, Id3, Id4, Id5) VALUES ('kjlkjl', 986, 87, 7, 8, 5)' at line 1

Is there a way that I can fix this? I've tried all the possibilities to do it (MySQLi Object-oriented, MySQLi Procedural and PDO)
Thanks for your time,
Jonas

A: The reason is that you are using a reserved keyword for mySQL (key : the name of first column), try to change it to another keyword ('identifiant' for example), remember that there's some keywords reserved for mySQL like table, column, row, avoid using them as names.


text:
Q: How Do I Target Only One Button To Change Text When Clicked? I'm using Clipboard.js to copy text on a site I'm building. I have everything working well but in the instance where there are multiple buttons, all buttons fire with the success message of text copied.
I have this in my footer:

The following code is in the article itself:
Example Text <button class="btn" data-clipboard-text="Example Text"> Copy to Clipboard </button>

It works perfectly with one button to copy and paste. Once copied the text of the button changes to "Copied! To Clipboard." However, when there are multiple buttons and one is clicked they are all changed to "Copied! To Clipboard." How do I target only the button the user clicked?

A: The behavior you are experiencing is caused by a very vague (in your situation) CSS selector to target button text to be updated. This is because .btn span returns a collection of all the buttons with class .btn and a  for text inside.
You should benefit from the data available on the event object returned by Clipboard. Here's an example event object structure:
{
  "action": "copy",
  "text": "Example Text #1",
  "trigger": <button class="btn" data-clipboard-text="Example Text #1">…</button>,
  "clearSelection": function () { [native code] }
}

I took the liberty of updating your snippet to use the exact button you are clicking with a focus shift to an input element which is populated with clipboard value:

$(() => {
  const clipboard = new ClipboardJS('.btn');
  clipboard.on('success', e =>
    $(e.trigger)
    .html("Copied! To Clipboard")
    .parent()
    .find('input')
    .val(e.text)
    .focus());
});
label {
  display: block;
}

  Example Text #1
  <button class="btn" data-clipboard-text="Example Text #1">
    Copy to Clipboard
  </button>
  <input placeholder="Ctrl+V here..." />

  Example Text #2
  <button class="btn" data-clipboard-text="Example Text #2">
    Copy to Clipboard
  </button>
  <input placeholder="Ctrl+V here..." />


text:
Q: Firebase and Swift After Facebook Login and current user I am new to Swift and Firebase. I am trying to build an app with a facebook login. I have implement some code and try to learn for the tutorial but I am not really understand that how the login can be save and "know" the current user data. So i tried to implement this code in the login method and to save the user id
NSUserDefaults.standardUserDefaults().setValue(result ["uid"], forKey: "uid")
and this:
 var REF_USER_CURRENT: Firebase {
    let userID = NSUserDefaults.standardUserDefaults().valueForKey("uid") as! String
    let currentUser = Firebase(url: "\(baseUrl)").childByAppendingPath("users").childByAppendingPath(userID)
    return currentUser!
}

After the login it will move to other view and display the user name. I use this code to retrieve the username data
   func displayName()  {

    FirebaseHelper.fbh.REF_USER_CURRENT.observeEventType(.Value, withBlock: {
        snapshot in
        let currentUser = snapshot.value.objectForKey("name") as! String
        self.currentUsername = currentUser
        self.facebookUserName.text = currentUser as String
        print("Username: \(currentUser)")
        }, withCancelBlock: { error in
            print(error.description)
    })

}

However, every time i logged in and it will show this error fatal error: unexpectedly found nil while unwrapping an Optional value with highlighting the REF_USER_CURRENT. I think the reason is because it cannot probably save the uid in NSUserDefault. It is my login method
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {

    if error != nil{
        print("Facebook login failed. Error \(error)")
    }else if result.isCancelled {
        print("Facebook login was cancelled")
    }else if result.grantedPermissions.contains("email"){
          let accessToken = FBSDKAccessToken.currentAccessToken().tokenString
        FirebaseHelper.fbh.REF_BASE.authWithOAuthProvider("facebook", token: accessToken, withCompletionBlock: { error, authData in

            if(error != nil){
                print("Login failed. \(error)")
            }else{
                print("Logged in! \(authData)")
                self.saveUserToFirebase(authData)
                print("User Saved Successfully! \(authData.uid)")
                self.processLogin(accessToken, authData: authData)
                let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("profileSetup") as! UIViewController
                self.presentViewController(viewController, animated: true, completion: nil)

            }

        })
    }

}

   func processLogin(accessToken: String, authData: FAuthData) {
    FirebaseHelper.fbh.REF_USER_CURRENT.childByAppendingPath(authData.uid).observeSingleEventOfType(.Value, withBlock: { snapshot in
        if snapshot.value is NSNull {
            print("fail")
        } else {
            print("no")
        }
    })
}

private func createUser(authData: FAuthData!){

    let displayName = authData.providerData["displayName"] as! String
    let email = authData.providerData["email"] as! String
    var imageUrl = ""

    if let url = authData.providerData["profileImageURL"] as? String {
        imageUrl = url
    }

    let request = FBSDKGraphRequest(graphPath: "me/picture", parameters: ["fields": "url", "redirect": false, "type": "large"], HTTPMethod: nil)
    request.startWithCompletionHandler { connection, result, facebookerror in

        if facebookerror != nil{
            print("Graph API Call failed. \(facebookerror)")
        }else{

            //let userData = (result as! NSDictionary).copy()

            let user = ["name": displayName, "email": email,"profilePicUrl": imageUrl]
            FirebaseHelper.fbh.createFirebaseUser(authData.uid, user: user)
            if facebookerror != nil{
                print("Error occured! \(facebookerror)")
            }else{
                print("User Saved Successfully! \(authData.uid) \(displayName)")
                NSUserDefaults.standardUserDefaults().setValue(result ["uid"], forKey: "uid")

            }
            self.facebookLoginBtn.hidden = true
        }
    }

}

I don't understand how the NSUserdafult will work for current user and do i need to write any code in each page to check the current user data to retrieve the data? Please modify my code for more understanding in this issue.

A: If the goal is to authenticate a user, and if that is successful, store their login credentials locally on the device, it's pretty straightforward.
The login process varies a bit by provider (make sure it's enabled in your Firebase dashboard) but they all have the same flow.
Once authenticated, authData variable contains information about that specific user. The uid property on the FAuthData object is how you uniquely identify the user.
let email = "dude@thing.com"
let pw = "password"

ref.authUser(email, pw) {
    error, authData in

    if error != nil {
        // eh, something went wrong, handle it

    } else {

       let myAppData = NSUserDefaults.standardUserDefaults()
       myAppData.setValue(auth.uid, forKey: "uid")
       myAppData.setValue(email, forKey: "email")
       myAppData.setValue(pw, forKey: "password")
    }
}

Moving on from that, you will probably want to create a /users node within Firebase that contains other information about the user
users
  uid_0
   name: "Pete"
   shoe_size: "13"
  uid_1
   name: "Larry"
   shoe_size: "2"

You can find a lot more information on this topic on the Firebase guide in the User Authentication section, along with sample code.


text:
Q: List that grows upwards (not downward) inside a div, then scrolls I want to have a list grow upwards (not downward) inside a div. Then to scroll the list within that div when there are too many li items. Is this combination possible?
The scrolling is easy - fix the height of the div and set the style of that div to overflow-y: scroll;
The bottom vertical aligned li was tricky and I chose the simplest solution which was to style the containing div as position: relative; and the ul within as position: absolute; bottom: 0;
But I want both behaviours.  Unfortunately achieving the bottom vertical aligned li breaks the scrolling.  Or rather, the scrolling happens but I can't drag scroll with the mouse anymore - the scrollbar doesn't appear either.
Here is the fiddle http://jsfiddle.net/tcab/Am3uL/
Here is my html

six

five

four

three

two

one

and here are the relevant styles
div.scroll {
    overflow-y: scroll;
}
.bottomalign_ul {
    position: absolute;
    bottom: 0;
}
.bottomalign {
    position: relative;
}

Basically I want to apply all three styles at once - and get the desired effect.
$('div').addClass('bottomalign');
$('ul').addClass('bottomalign_ul');
$('div').height(100);
$('div').addClass('scroll');

Though this sort of works, the list is merely clipped within the div and I can't scroll it with the mouse anymore.

A: A workaround is to always scroll to bottom when you load the list. So it looks as if its growing bottom up. Is that right? If so check the following solution
dive bottom up scroll
Edit:
I slightly modified following bits of your fiddle and got scroll bar to bottom in scenario 'both'
css:
.bottomalign_ul {
    position: absolute;
 }

JQuery:
function scroll() {
    $('div').height(100);
    $('div').addClass('scroll');
    $('div').scrollTop(200);
}


text:
Q: How to calculate number of working days between two months like from Jan to May in excel? Suppose a user selects a From month from a dropdown (e.g. January) and a To month from a second dropdown (e.g. May). I have to show number of working days from jan to may in a third column..how can we calculate it?

A: I believe the name of the function is NETWORKDAYS

A: Here's one way I have done this work in the past. Start with a table that lists for every day whether or not it's a work day during the timeframe you are interested int.
date    workday?
1/1/15  1
1/2/15  1
1/3/15  0
1/4/15  0
1/5/15  1
1/6/15  1
1/7/15  1
1/8/15  1
1/9/15  1
1/10/15 0
1/11/15 0
1/12/15 1
1/13/15 1
1/14/15 1
1/15/15 1
1/16/15 1
1/17/15 0
1/18/15 0
1/19/15 1
...

in a second sheet, use a function like this:
SUMPRODUCT(--(A2<=MONTH('workdays 2015'!A$2:A$366)),--(B2>=MONTH('workdays 2015'!A$2:A$366)),('workdays 2015'!B$2:B$366))

where A2 is the beginning month as an integer (jan = 1 feb = 2 etc) and b2 is the end month. the array A2:A366 is where you put the dates and the array b2:B366 is where you put ones for workdays and 0 for weekends/holidays.


text:
Q: Django: the post isn't selected automatically of particular user hi am working on a project where am using multiple user data
a user did a post onto the site and when driver see that post he adds their offer to that post but when driver submit the post ...at the admin level the particular is selected automatically but the post  is not selected on which he adds price
this is my post model.py
class Loader_post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="Loader")
    pick_up_station = models.CharField(max_length=150)
    destination_station = models.CharField(max_length=150)
    sender_name = models.CharField(max_length=150)
    phone_number = PhoneNumberField(null=False, blank=False, unique=True)
    receiver_name = models.CharField(max_length=150)

this is my second model of adding price to a particular post
class price(models.Model):
    my_post = models.ManyToManyField(Loader_post, related_name='prices')
    user = models.ForeignKey(User, on_delete=models.CASCADE,  null=True, default='')
    driver_price = models.CharField(max_length=150, null=True)
    driver_name = models.CharField(max_length=150, null=True)
    approved_price = models.BooleanField(default=False)
    status = models.BooleanField(default=False)

this is my adding price to the post views.py
@login_required
def add_price_to_post(request, pk):
    post = get_object_or_404(Loader_post, pk=pk)
    user = request.user
    if request.method == "POST":
        form = price_form(request.POST)
        if form.is_valid():
            ps = form.save(commit=False)
            ps.user = request.user
            ps.status = True
            ps.post =  post
            ps.save()
            return redirect('Driver:Driverview')
    else:
        form = price_form()
    return render(request, 'price_form.html', {'form': form})

this is my html  add post button
{% for loader in Loader %}

this is loop
and this is button
add price

A: It is a ManyToMany relation between price and Loader_post model, hence ps.post =  post won't work. You need to use add() method to add new post. Like this:
ps.save()
ps.my_post.add(post)


text:
Q: Alternate definitions of Thermal states The definition of thermal states I'm used to is:
$$\tau_{\beta} = \frac{1}{Z}\,e^{-\beta H}$$
where $Z$ is the partition function defined as $Z= \mathrm{Tr}(e^{-\beta H})$, $\beta$ the inverse temperature and H the system's Hamiltonian. I think if the Hamiltonian is not time dependent $H=\sum_n \varepsilon_n |n\rangle\langle n|$ I can rewrite the thermal state
$$\tau_{\beta_1} = \frac{1}{Z}e^{-\beta H} = \frac{1}{Z}\exp\left(-\beta \sum_n \varepsilon_n |n\rangle\langle n|\right) = \frac{1}{Z}\sum_ne^{-\beta  \varepsilon_n} |n\rangle\langle n| .$$
Is this calculation correct?
In case it is correct, I just came across another version of it (I believe)
$$\tau_{\beta_2} = (1-e^{-\beta \omega}) \sum_n e^{-n\beta\omega}| n\rangle\langle n|$$
where $\omega$ is the frequency of some harmonic oscillator.
Can someone explain to me how these two definitions $(\tau_{\beta_1}$ and $\tau_{\beta_2})$ relate to each other?

A: Your second version of the density operator is the specific case in which the Hamiltonian is that of a simple quantum harmonic oscillator, namely
$$H=\hbar\omega\left(a^{\dagger}a+\frac{1}{2}\right).$$
In terms of this Hamiltonian, the energy levels are (setting $\hbar=1$) $\varepsilon_n=\omega(n+1/2)$. Thus, the partition function is
$$Z=\sum_{n\geq 0}e^{-\beta\omega(n+1/2)}=\frac{e^{-\beta\omega/2}}{1-e^{-\beta\omega}}.$$
Thus, the density operator is given by
$$\tau_{\beta}=\frac{1}{Z}\sum_{n\geq 0}e^{-\beta\omega(n+1/2)}\,|n\rangle\langle n|=(1-e^{-\beta\omega})\sum_{n\geq 0}e^{-\beta\omega n}\,|n\rangle\langle n|,$$
as stated.

A: I would call this the (normalized) density operator (or density matrix), in which case, yes, I think the expressions are correct.
For the quantum harmonic oscillator, in units where $\hbar=1$, and measuring energies from the ground state energy, the energy levels are $\varepsilon_n=n\omega$ for $n=0,1,2,\ldots$ and the partition function is
$$
Z=\sum_{n=0}^\infty \exp(-n\beta\omega) = \frac{1}{1-\exp(-\beta\omega)} .
$$
So everything is fine: the second formula is a particular example of the first.