text:
Q: Ascii range regards binary files? ive been reading about this topic and didnt get the specific info for my question :
(maybe the following is incorrect - but please do correct me)
Every file( text/binary) is saving BYTES.
byte is 8 bits hence max value is 2^8-1 = 255 codes.
those 255 codes divides to 2 groups:
0..127 : textual chars
128:..255 : special chars.

so binary file contains char codes from the whole range : 0..255 ( ascii chars+special chars).
1 ) correct ?
2) NOw , lets say im saving one INT in binary file. ( 4 byte in 32 bit system)
how does the file tells the progem reads it :  its not 4 single unrelated bytes but an int which is 4 bytes ?

A: Underlying all files are being stored as bytes, so in a sense what you're saying is correct. However, if you open a file that's intended to be read as binary and try to read it in a text editor, it will look like gibberish.
How does a program know whether to read a file as text or as binary? (ie as special sets of ASCII or other encoded bytes, or just as the underlying bytes with a different representation)?
Well, it doesn't know - it just does what it's told.
In Windows, you open .txt files in notepad - notepad expects to be reading text. Try opening a binary file in notepad. It will open, you will see stuff, but it will be rubbish.
If you're writing your own program you can write using BinaryWriter and read using BinaryReader if you want to store everything as binary. What would happen if you wrote using BinaryWriter and read using StringReader?

To answer your specific example:
using (var test = new BinaryWriter(new FileStream(@"c:\test.bin", FileMode.Create)))
{
    test.Write(10);
    test.Write("hello world");
}

using (var test = new BinaryReader(new FileStream(@"c:\test.bin", FileMode.Open)))
{
    var out1 = test.ReadInt32();
    var out2 = test.ReadString();

    Console.WriteLine("{0} {1}", out1, out2);
}

See how you have to read in the same order that's written? The file doesn't tell you anything.
Now switch the second part around:
using (var test = new BinaryReader(new FileStream(@"c:\test.bin", FileMode.Open)))
{
    var out1 = test.ReadString();
    var out2 = test.ReadInt32();

    Console.WriteLine("{0} {1}", out1, out2);
}

You'll get gibberish out (if it works at all). Yet there is nothing you can read in the file that will tell you that beforehand. There is no special information there. The program must know what to do based on some out of band information (a specification of some sort).

A:
so binary file contains char codes from the whole range : 0..255 ( ascii chars+special chars).

No, a binary file just contains bytes. Values between 0 and 255. They should only be considered as character at all if you decide to ascribe that meaning to them. If it's a binary file (e.g. a JPEG) then you shouldn't do that - a byte 65 in image data isn't logically an 'A' - it's whatever byte 65 means at that point in the file.
(Note that even text files aren't divided into "ASCII characters" and "special characters" - it depends on the encoding. In UTF-16, each code unit takes two bytes regardless of its value. In UTF-8 the number of bytes depends on the character you're trying to represent.)

how does the file tells the progem reads it : its not 4 single unrelated bytes but an int which is 4 bytes ?

The file doesn't tell the program. The program has to know how to read the file. If you ask Notepad to open a JPEG file, it won't show you an image - it will show you gibberish. Likewise if you try to force an image viewer to open a text file as if it were a JPEG, it will complain that it's broken.
Programs reading data need to understand the structure of the data they're going to read - they have to know what to expect. In some cases the format is quite flexible, like XML: there are well-specified layers, but then the program reads the values with higher-level meaning - elements, attributes etc. In other cases, the format is absolutely precise: first you'll start with a 4 byte integer, then two 2-byte integers or whatever. It depends on the format.
EDIT: To answer your specific (repeated) comment:

Im Cmd shell....youve written your binary file. I have no clue what did you do there. how am i suppose to know whether to read 4 single bytes or 4 bytes as once ?

Either the program reading the data needs to know the meaning of the data or it doesn't. If it's just copying the file from one place to another, it doesn't need to know the meaning of the data. It doesn't matter whether it copies it one byte at a time or all four bytes at once.
If it does need to know the meaning of the data, then just knowing that it's a four byte integer doesn't really help much - it would need to know what that integer meant to do anything useful with it. So your file written from the command shell... what does it mean? If I don't know what it means, what does it matter whether I know to read one byte at a time or four bytes as an integer?
(As I mentioned above, there's an intermediate option where code can understand structure without meaning, and expose that structure to other code which then imposes meaning - XML is a classic example of that.)

A: It's all a matter of interpretation. Neither the file nor the system know what's going on in your file, they just see your storage as a sequence of bytes that has absolutely no meaning in itself. The same thing happens in your brain when you read a word (you attempt to choose a language to interpret it in, to give the sequence of characters a meaning).
It is the responsibility of your program to interpret the data the way you want it, as there is no single valid interpretation. For example, the sequence of bytes 48 65 6C 6C 6F 20 53 6F 6F 68 6A 75 6E can be interpreted as:

*

*A string (Hello Soohjun)

*A sequence of 12 one-byte characters (H, e, l, l, o, , S, o, o, h, j, u, n)

*A sequence of 3 unsigned ints followed by a character (1214606444, 1864389487, 1869113973, 110)

*A character followed by a float followed by an unsigned int followed by a float (72, 6.977992E22, 542338927, 4.4287998E24), and so on...

You are the one choosing the meaning of those bytes, another program would make a different interpretation of the very same data, much the same a combination of letters has a different interpretation in say, English and French.
PS: By the way, that's the goal of reverse engineering file formats: find the meaning of each byte.


text:
Q: Is there a way to map the NUMBER field in Oracle to multiple numeric fields in SQL Server in SSIS I'm trying to move data from Oracle to SQL Server.  We have a large number of NUMBER fields in the original Oracle 11g schema.  In SSIS, we are using an OLE destination control.  Most of the NUMBER fields are mapping to float fields.
We are using the attunity connectors.  I understand that there are mapping xml files in SSIS that will map numeric data types to SSIS data types; however, I need something that will take a sample of the data and infer the correct numeric, sql server destination data type.
Is there a solution for this problem?  There are a lot of fields, we are worried about manually mapping them.
Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: NSURLConnection closes early on GET I'm working on a method to centralize my URL connections for sending and receiving JSON data from a server. It works with POST, but not GET. I'm using a Google App Engine server and on my computer it'll handle the POST requests and return proper results (and log appropriately), but I get the following error when I try the request with a GET method:
Error Domain=kCFErrorDomainCFNetwork Code=303 "The operation couldn't be completed. (kCFErrorDomainCFNetwork error 303.)" UserInfo=0xd57e400 {NSErrorFailingURLKey=http://localhost:8080/api/login, NSErrorFailingURLStringKey=http://localhost:8080/api/login}

In addition, the GAE dev server shows a "broken pipe" error, indicating that the client closed the connection before the server was finished sending all data.
Here's the method:
/* Connects to a given URL and sends JSON data via HTTP request and returns the result of the request as a dict */
- (id) sendRequestToModule:(NSString*) module ofType:(NSString*) type function:(NSString*) func params:(NSDictionary*) params {

    NSString *str_params = [NSDictionary dictionaryWithObjectsAndKeys:func, @"function", params, @"params", nil];
    NSString *str_url = [NSString stringWithFormat:@"%@%@", lds_url, module];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:str_url]];
    NSData *data = [[NSString stringWithFormat:@"action=%@", [str_params JSONString]] dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPMethod:type];
    [request setHTTPBody:data];
    [request setValue:[NSString stringWithFormat:@"%d", [data length]] forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    NSError *error = nil;
    NSURLResponse *response = nil;
    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    NSLog(@"Error: %@", error);
    NSLog(@"Result: %@", [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding]);
    return [result objectFromJSONData];
}

A sample call would be:
NSDictionary *response = [fetcher sendRequestToModule:@"login" ofType:@"GET" function:@"validate_email" params:dict];

Again, this works with a POST but not a GET. How can I fix this?

A: In my case i was not calling [request setHTTPMethod: @"POST" ]

A: I think the root cause is you have an invalid URL.
JSON encoding will include things like '{', '}', '[' and ']'. All of these need to be URL encoded before being added to a URL.
NSString *query = [NSString stringWithFormat:@"?action=%@", [str_params JSONString]];
query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", str_url, query]];

To directly answer your question:
According to CFNetwork Error Codes Reference the error is kCFErrorHTTPParseFailure. This means the client failed to correctly parse the HTTP response.

A: The reason why is that a GET doesn't include a body. Why would you want to submit JSON in a GET anyways?
If the target api returns data only you pass it in the url params.
If you want to send data and "get" a response use a post and examine the body on return.
Sample Post:
NSError *error;
NSString *urlString = [[NSString alloc] initWithFormat:@"http://%@:%@/XXXX/MVC Controller Method/%@",self.ServerName, self.Port, sessionId  ];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];

// hydrate the remote object
NSString *returnString = [rdc JSONRepresentation];
NSData *s10 = [returnString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:s10];
NSURLResponse *theResponse = [[NSURLResponse alloc] init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&error];
NSString *message = [[NSString alloc] initWithFormat: @"nothing"];

if (error) {
    message = [[NSString alloc] initWithFormat:@"Error: %@", error];

} else {
    message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

}

NSLog(@"%@", message);

return message;


text:
Q: Why I get Unexpected token export Error on nodejs with vue cli and ssr? I just created a vue project using the vue/cli v3.10.0
I add ssr to the project like vue-cli-ssr-example example.
But after I build and run the server side (nodejs) and I try to browse to http://localhost:8080:
But The following error occurs :
error during render : /
C:\sandbox3\vuecli-with-ssr\node_modules\register-service-worker\index.js:18
export function register (swUrl, hooks) {
^^^^^^

SyntaxError: Unexpected token export
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)
    at Module._compile (internal/modules/cjs/loader.js:656:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
    at Module.load (internal/modules/cjs/loader.js:598:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
    at Function.Module._load (internal/modules/cjs/loader.js:529:3)
    at Module.require (internal/modules/cjs/loader.js:636:17)
    at require (internal/modules/cjs/helpers.js:20:18)
error during render : /favicon.ico
C:\sandbox3\vuecli-with-ssr\node_modules\register-service-worker\index.js:18
export function register (swUrl, hooks) {
^^^^^^

SyntaxError: Unexpected token export
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)
    at Module._compile (internal/modules/cjs/loader.js:656:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
    at Module.load (internal/modules/cjs/loader.js:598:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
    at Function.Module._load (internal/modules/cjs/loader.js:529:3)
    at Module.require (internal/modules/cjs/loader.js:636:17)
    at require (internal/modules/cjs/helpers.js:20:18)

Any ideas how to fix it?
Steps to reproduce
$ Clone my github repo: git clone https://github.com/wizardnet972/vuecli-with-ssr.git

$ npm i

$ npm run build:prod && node server.js

$ open http://localhost:8080/

Here My Github repo code and this is how I create my repo:

*

*First I create a new app using vue/cli: $ vue create vuecli-with-ssr

*I edit and add the files: vue.config.js
tsconfig.json
server.js
babel.config.js
entry-client.ts
entry-server.ts
main.ts
index.template.html

*Run the project in production mode (not the dev server) : npm run build:prod && node server.js
Any help would be appreciated.


text:
Q: Can I change the scroll speed using css or jQuery? In the example below, I would like to reduce the scroll speed of the div's content, especially when using the mouse wheel, as one wheel tick scrolls approximately the div's height.
Is it possible to control that with CSS, and if not, javascript (perhaps using jQuery) ?

.scrollable {
    width: 500px;
    height: 70px;
    overflow: auto;
}

    Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?

Note: I realize that the scroll speed might differ between os/browers and browser settings. But I think that in the majority of the cases, the scroll speed (when using the mouse wheel) is too fast, so I would like to slow it down.

A: The scroll speed CAN be changed, adjusted, reversed, all of the above - via javascript (or a js library such as jQuery).
WHY would you want to do this? Parallax is just one of the reasons. I have no idea why anyone would argue against doing so -- the same negative arguments can be made against hiding DIVs, sliding elements up/down, etc. Websites are always a combination of technical functionality and UX design -- a good designer can use almost any technical capability to improve UX. That is what makes him/her good.
Toni Almeida of Portugal created a brilliant demo, reproduced below:
jsFiddle Demo
HTML:

    Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops.

javascript/jQuery:
  function wheel(event) {
      var delta = 0;
      if (event.wheelDelta) {(delta = event.wheelDelta / 120);}
      else if (event.detail) {(delta = -event.detail / 3);}

      handle(delta);
      if (event.preventDefault) {(event.preventDefault());}
      event.returnValue = false;
  }

  function handle(delta) {
      var time = 1000;
      var distance = 300;

      $('html, body').stop().animate({
          scrollTop: $(window).scrollTop() - (distance * delta)
      }, time );
  }

  if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false);}
    window.onmousewheel = document.onmousewheel = wheel;

Source:
How to change default scrollspeed,scrollamount,scrollinertia of a webpage

A: I just made a pure Javascript function based on that code.
Javascript only version demo: http://jsbin.com/copidifiji
That is the independent code from jQuery
if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false);
window.onmousewheel = document.onmousewheel = wheel;}

function wheel(event) {
    var delta = 0;
    if (event.wheelDelta) delta = (event.wheelDelta)/120 ;
    else if (event.detail) delta = -(event.detail)/3;

    handle(delta);
    if (event.preventDefault) event.preventDefault();
    event.returnValue = false;
}

function handle(sentido) {
    var inicial = document.body.scrollTop;
    var time = 1000;
    var distance = 200;
  animate({
    delay: 0,
    duration: time,
    delta: function(p) {return p;},
    step: function(delta) {
window.scrollTo(0, inicial-distance*delta*sentido);
    }});}

function animate(opts) {
  var start = new Date();
  var id = setInterval(function() {
    var timePassed = new Date() - start;
    var progress = (timePassed / opts.duration);
    if (progress > 1) {progress = 1;}
    var delta = opts.delta(progress);
    opts.step(delta);
    if (progress == 1) {clearInterval(id);}}, opts.delay || 10);
}

A: The mouse scroll even can be overwritten using JS within the browser using an event listener. It is possible to prevent default scrolling behavior this way, and implement your own behavior (see cssyphus's answer).
However, I think doing so is a HORRIBLE idea in terms of usability, accessibility, and respect for your users.


text:
Q: Programatically modifying DLL references inside project file I need to force all of my projects to use dll's that are stored in a common location. I am starting by refactoring existing projects to point to the dll's source folder of my preference. So I decided to try a programmatic way for changing these references.
I read dll references as following:
 XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
            XDocument projDefinition = XDocument.Load(filePath);
            IEnumerable<string> references = projDefinition
                .Element(msbuild + "Project")
                .Elements(msbuild + "ItemGroup")
                .Elements(msbuild + "Reference")
                .Elements(msbuild + "HintPath")
                .Select(refElem => refElem.Value);

The next step is to change reference HintPath based on reference name. I plan on creating a dictionary of references and then run through them to update each of the project files.
However, I cannot find any solid way of reading and changing HintPath based on Reference inside csproj.

A: I am likely quite late to this and i am yet to test out this particular application but you should be able to take the code you have and remove the .Select(refElem => refElem.Value) before iterating the references.
This will give you access to the element itself and should allow for an update of the value for the element. Once you have changed all values you need to, you can write the XMLdoc back to the proj file.
XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
        XDocument projDefinition = XDocument.Load(filePath);
        IEnumerable<string> references = projDefinition
            .Element(msbuild + "Project")
            .Elements(msbuild + "ItemGroup")
            .Elements(msbuild + "Reference")
            .Elements(msbuild + "HintPath");
        foreach(var element in references)
        {
            // do what you need to in order to update the reference
        }
        projDefinition.Save(filePath);


text:
Q: foobar.withgoogle.com task Please Pass the Coded Messages java Test 4 fail I'm working on foobar.withgoogle task "Please Pass the Coded Messages". I got correct calculations on my computer for every possible number but foobar prints

Test 4 failed [Hidden]

Not sure where to go from here. Tried multiple inputs including ones with only 0 in it, negative numbers, more than 9 digits. All of which result in failing test 4.
Visible test cases all pass.
Does anyone have any ideas? No need to tell me the exact solution, just point me in the right direction please.
Thank you in advance.
Problem:

You have L, a list containing some digits (0 to 9). Write a function solution(L) which finds the largest number that can be made from some or all of these digits and is divisible by 3. If it is not possible to make such a number, return 0 as the solution. L will contain anywhere from 1 to 9 digits. The same digit may appear multiple times in the list, but each element in the list may only be used once.

See below for code:
import java.util.Arrays;

public class Solution {

/*To achieve the goal the program follows the below logic:
 * 1. sort the array with built in sort method
 * 2. Reverse the sorted array so we get the largest number possible
 * 3. Check if the number is divisible by 3 by adding together the individual digits
 * and checking if it is divisible by 3. If yes, generate a string from the array,
 * convert it into an int and return the result.
 * 4. If the initial number is not divisible by 3, starting with the smallest number
 * (right to left), so we are checking the largest number possible, we remove a digit until
 * we get to the first (largest) digit, checking if the sum of the remaining digits is
 * divisible by 3. If so, the number is returned.
 * 5. If we iterated through the array and no solution was found, return 0.
 *
*/
public static int solution (int[] l) {
    if(l.length==0) {return 0;}
    if(hasNegativeValue(l)){return 0;}
    if(l.length==1&&l[0]%3==0) {return l[0];}
    if(l.length==1&&l[0]%3!=0) {return 0;}
    Arrays.sort(l); // sort the array in ascending order
    l=reverseArray(l);
    int elementToRemove = l.length-1;
    if(sumArray(l)%3==0) {
        return Integer.parseInt(Arrays.toString(l).replaceAll("[^0-9]+",""));
    }else {
        while(elementToRemove>=0) {
            int[] testArray = removeElement(l,elementToRemove);
            if(sumArray(testArray)%3==0) {
                return Integer.parseInt(Arrays.toString(testArray).replaceAll("[^0-9]+",""));
            }
            elementToRemove--;
        }
        if(elementToRemove==0) {return 0;}else {return 0;}
    }
}

// Method to reverse  the array
public static int[] reverseArray(int[] arrayToReverse){
    if(arrayToReverse.length==1) {return arrayToReverse;}
    else {
        int[] reversedArray=new int[arrayToReverse.length];
        int j=arrayToReverse.length;
        for (int i=0;i<arrayToReverse.length;i++) {
            reversedArray[j-1]=arrayToReverse[i];
            j--;
        }
        return reversedArray;
    }
}

//Method to sum all elements of the array
public static int sumArray(int[] arrayToSum) {
    if(arrayToSum.length==1) {return arrayToSum[0];}
    else {
        int result=0;
        for (int i=0;i<arrayToSum.length;i++) {
            result+=arrayToSum[i];
        }
        return result;
    }
}

//Method to remove a specific element of an array
public static int[] removeElement(int [] initialArray,int index) {
    if(index<0||index>initialArray.length-1) {return initialArray;}
    else {
        int [] result = new int[initialArray.length-1];
        int j=0;
        for (int i=0;i<initialArray.length;i++) {
            if(i!=index) {
                result[j]=initialArray[i];
                j++;
            }else {continue;}
        }
        return result;
    }
}

//Method to check for negative element of an array
public static boolean hasNegativeValue(int[] i) {
    boolean isNegative=false;
    for(int number : i) {
        if(number<0) { isNegative=true;}
    }
    return isNegative;
}
}

A: I was solving the same FooBar problem and was facing the same issue. Then I realized you have to consider a case where you have to remove 2 digits at a time.
For Example: {9,6,3,1,1} or {3,3,4,4}
In these examples, if you remove 1 digit then you won't get a number which is divisible by 3. But if you remove 2 digits i.e. 963 or 33 are divisible by 3.
I got the approach but I am not sure how to code this.


text:
Q: PHP creating multiple images from single image using imagecreatefrompng function in a loop I am creating multiple partial images from a single image to use for a map overlay. The issue I am having is that the first image is created successfully, but the rest are black. I suspect that the imagecreatefrompng is the culprit and it is not able to run multiple times with out clearing it and so my images are black because the image is nil. Please help me find a suitable solution to my code below. Thanks in advance.
Everything in my code works, except the image creation. As I said before it creates the image successfully once. The output of my loop says everything that it should say.
for($x = 0; $x <= $loop; $x++)
{
    //Check for direcotory for X
    $x_directory = 'generated_images/' . $dbn . '/' . $zoom . '/' . $x;
    if (!file_exists($x_directory))
    {
        mkdir($x_directory, 0777, true);
    }//end if

    //Set Starting Y Copy Values
    $startY = 0;
    $endY = 1;

    for($y = 0; $y <= $loop; $y++)
    {
        //Do not need to check for Y images, we will replace any exsisting images
        //Set a time limit for each Y image
        set_time_limit(15);
        $time = time();

        $src_image = imagecreatefrompng('generated_images/pre'. $dbn .'.png') or die('Problem with source');
        $y_image = imagecreatetruecolor($image_w,$image_h) or die('Problem In Creating image');

        if(($x >= 2 && $x <= 5) && ($y >= 5 && $y <= 6)) {
            ?>

            Start X: <?=$startX?>

            Start Y: <?=$startY?>

            End X: <?=$endX?>

            End Y: <?=$endY?>

            <?

            //imagecopyresized($y_image, $src_image, 0, 0, $startX, $startY, $image_w, $image_h, 1024, 1024);

            //Set the blending mode for an image
            imagealphablending($y_image, false);
            imagesavealpha($y_image, true);

            // scan image pixels
            for ($pix_y = ($startY * $multiplier); $pix_y < ($endY * $multiplier) ; $pix_y++) {

                for ($pix_x = ($startX *$multiplier); $pix_x < ($endX * $multiplier) ; $pix_x++) {

                    $out_pix = imagecolorat($src_image,$pix_x,$pix_y);
                    $colors = imagecolorsforindex($y_image, $out_pix);
                    //$src_pix_array = rgb_to_array($src_pix);

                    if($colors['red'] == 0 && $colors['green'] == 0 && $colors['blue'] == 0) $alpha = 127;
                    else $alpha = 80;

                    imagesetpixel($y_image, $pix_x, $pix_y, imagecolorallocatealpha($y_image, $colors['red'], $colors['green'], $colors['blue'], $alpha));

                }//end for

            }//end for

            $startY++;
            $endY++;

            imagepng($y_image,$x_directory . '/' . $y . '.png') or die('Problem saving image: ' . $x_directory . '/' . $y . '.png');
            imagedestroy($y_image);
            //imagedestroy($src_image);

        }//end if
        else
        {
            $black = imagecolorallocate($y_image, 0, 0, 0);
            // Make the background transparent
            imagecolortransparent($y_image, $black);

            imagepng($y_image,$x_directory . '/' . $y . '.png') or die('Problem saving image: ' . $x_directory . '/' . $y . '.png');
            imagedestroy($y_image);

        }

        $time = time() - $time;
        ?>
        Image <?=$x?>,<?=$y?> time: <?=$time?> Seconds

        <?

    }
    //end for y

    if(($x >= 2 && $x <= 5)) {
    $startX++;
    $endX++;
    }

}//end for x

A: If you're trying to split the big image into smaller images, i suggest you just call imagecreatefrompng() once, then create images with imagecreatetruecolor() and use imagecopyresampled() for each of the bits copying in new image objects (or use same one and save the parts after you extract them)
Here is how i would do it:
$main_image = imagecreatefrompng($path); //assuming you know the path
//do your for's and every time your loop runs, you use an $part_image like this

//LOOP START
$part_image = imagecreatetruecolor(you know your parameters, atleast you should);
//do the imagecopyresampled with your coordinates
imagejpeg($part_image, $part_path); //save the image, make sure each time you do a different filename in order not to overwrite the first part - maybe increment a $counter variable and append it to the filename like "part1.jpg" and so on
//or imagepng, see php docs for these functions
imagedestroy($part_image);
//LOOP END


text:
Q: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty on Linux, or why is the default truststore empty When you google for this exception: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty, multiple results appear. However there is no definitive solution, only guesses.
The problem arises (in my case at least) when I try to use open a connection over SSL. It works fine on my windows machine, but when I deploy it to the linux machine (with sun's jre installed) it fails with the above exception.
The problem is that the default truststore of the JRE is empty for some reason (size of only 32 bytes, whereas it is 80kb on windows).
When I copied my jre/lib/security/cacerts file from windows to linux, it worked fine.
The question is - why is the linux jre having an empty trust store?
Note that this happens on an Amazon EC2 instance, with the AMI linux, so it might be due to some amazon policies (I think java was pre-installed, but I'm not sure)

A: Not the answer to the original question but when trying to resolve a similar issue, I found that the Mac OS X update to Maverics screwed up the java install (the cacert actually). Remove sudo rm -rf /Library/Java/JavaVirtualMachines/*.jdk and reinstall from http://www.oracle.com/technetwork/java/javase/downloads/index.html

A: My solution on Windows was to either run console window as Administrator or change the environment variable MAVEN_OPTS to use a hardcoded path to trust.jks (e.g. 'C:\Users\oddros') instead of '%USERPROFILE%'. My MAVEN_OPTS now looks like this:
-Djavax.net.ssl.trustStore=C:\Users\oddros\trust.jks -Djavax.net.ssl.trustStorePassword=changeit

A: My cacerts file was totally empty.  I solved this by copying the cacerts file off my windows machine (that's using Oracle Java 7) and scp'd it to my Linux box (OpenJDK).
cd %JAVA_HOME%/jre/lib/security/
scp cacerts mylinuxmachin:/tmp

and then on the linux machine
cp /tmp/cacerts /etc/ssl/certs/java/cacerts

It's worked great so far.

A: The standard Sun JDK for linux has an absolutely ok cacerts and overall all files in the specified directory. The problem is the installation you use.

A: If this happens to you with an OpenJDK install on Mac OS X (as opposed to Linux), and you do have the official Mac OS X Java (i.e. latest Java 6) installed through Software Update, you can just do this:
cd $OPENJDK_HOME/Contents/Home/jre/lib/security
ln -s /System/Library/Java/Support/CoreDeploy.bundle/Contents/Home/lib/security/cacerts
ln -s /System/Library/Java/Support/Deploy.bundle/Contents/Home/lib/security/blacklist
ln -s /System/Library/Java/Support/Deploy.bundle/Contents/Home/lib/security/trusted.libraries

where $OPENJDK_HOME is the root directory of your OpenJDK install, typically OPENJDK_HOME=/Library/Java/JavaVirtualMachines/1.7.0u.jdk. This is identical to how official Java installs on Mac OS X acquire these files - they also just symlink them from those system bundles. Works for Lion, not sure for earlier versions of the OS.

A: Make sure that you have valid cacerts in the JRE/security, otherwise you will not bypass the invalid empty trustAnchors error.
In my Amazon EC2 Opensuse12 installation, the problem was that the file pointed by the cacerts in the JRE security directory was invalid:
$ java -version
java version "1.7.0_09"
OpenJDK Runtime Environment (IcedTea7 2.3.4) (suse-3.20.1-x86_64)
OpenJDK 64-Bit Server VM (build 23.2-b09, mixed mode)

$ ls -l /var/lib/ca-certificates/
-rw-r--r-- 1 root    363 Feb 28 14:17 ca-bundle.pem

$ ls -l /usr/lib64/jvm/jre/lib/security/
lrwxrwxrwx 1 root    37 Mar 21 00:16 cacerts -> /var/lib/ca-certificates/java-cacerts
-rw-r--r-- 1 root  2254 Jan 18 16:50 java.policy
-rw-r--r-- 1 root 15374 Jan 18 16:50 java.security
-rw-r--r-- 1 root    88 Jan 18 17:34 nss.cfg

So I solved installing an old Opensuse 11 valid certificates.  (sorry about that!!)
$ ll
total 616
-rw-r--r-- 1 root 220065 Jan 31 15:48 ca-bundle.pem
-rw-r--r-- 1 root    363 Feb 28 14:17 ca-bundle.pem.old
-rw-r--r-- 1 root 161555 Jan 31 15:48 java-cacerts

I understood that you could use the keytool to generate a new one (http://mail.openjdk.java.net/pipermail/distro-pkg-dev/2010-April/008961.html). I'll probably have to that soon.
regards
  lellis

A: I have avoided this error (Java 1.6.0 on OSX 10.5.8) by putting a dummy cert in the keystore, such as
keytool -genkey -alias foo -keystore cacerts -dname cn=test -storepass changeit -keypass changeit

Surely the question should be "Why can't java handle an empty trustStore?"

A: I can generate this error by setting system property trustStore to a missing jks file.  For example
    System.setProperty("javax.net.ssl.keyStore", "C:/keystoreFile.jks");
    System.setProperty("javax.net.ssl.keyStorePassword", "mypassword");
    System.setProperty("javax.net.ssl.trustStore", "C:/missing-keystore.jks");
    System.setProperty("javax.net.ssl.trustStorePassword", "mypassword");

This code does not generate a FileNotFound exception for some reason, but exactly the InvalidAlgorithmParameter exception listed above.
Kind of a dumb answer, but I can reproduce.

A: Had the same issue on Ubuntu 14.10 with java-8-oracle installed.
Solved installing ca-certificates-java package:
sudo apt-get install ca-certificates-java

A: I got this error in Ubuntu. I saw that
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts
was a broken link to /etc/ssl/certs/java/cacerts. That lead me to this bug:
https://bugs.launchpad.net/ubuntu/+source/ca-certificates-java/+bug/983302
The README for ca-certificates-java eventually showed the actual fix:
run
update-ca-certificates -f

apt-get install ca-certificates-java didn't work for me. It just marked it as manually installed.

A: Have the same issue. Resolved it by installing ca-certificate bundle from Mozilla:
$ zypper in ca-certificates-mozilla
The following NEW package is going to be installed:
ca-certificates-mozilla

1 new package to install.
Retrieving package ca-certificates-mozilla-1.85-8.8.1.noarch
(1/1), 143.7 KiB (239.1 KiB unpacked)
Retrieving: ca-certificates-mozilla-1.85-8.8.1.noarch.rpm.....................[done]
Installing: ca-certificates-mozilla-1.85-8.8.1 ...............................[done]
Additional rpm output:
Updating certificates in /etc/ssl/certs...
144 added, 0 removed.
creating /var/lib/ca-certificates/ca-bundle.pem ...
creating /var/lib/ca-certificates/java-cacerts ...
144 added, 0 removed.

$ ll /var/lib/ca-certificates/
total 392
drwxr-xr-x  2 root root   4096 Apr 26 07:25 ./
drwxr-xr-x 30 root root   4096 Apr 25 15:00 ../
-rw-r--r--  1 root root 220196 Apr 26 07:25 ca-bundle.pem
-rw-r--r--  1 root root 161555 Apr 26 07:25 java-cacerts

P.S.
$ cat /etc/SuSE-release
openSUSE 12.2 (x86_64)
VERSION = 12.2
CODENAME = Mantis
$ java -version
java version "1.7.0_09"
OpenJDK Runtime Environment (IcedTea7 2.3.4) (suse-3.20.1-x86_64)
OpenJDK 64-Bit Server VM (build 23.2-b09, mixed mode)

A: This happens because Access Privilege varies from OS to OS. Windows access hierarchy is different from Unix. However, this could be overcome by following these simple steps:

*

*Increase accessibility with AccessController.doPrivileged(java.security.PrivilegedAction subclass)

*Set your own java.security.Provider subclass as security property.
a.  Security.insertProviderAt(new , 2);

*Set your Algorythm with Security.setProperty("ssl.TrustManagerFactory.algorithm" ,  "XTrust509");

A: I get this same error on my Windows 7 machine when the permissions on my cacerts file in my C:\Program Files\Java\jdk1.7.0_51\jre\lib\security folder are not set correctly.
To resolve the issue, I allow the SERVICE and INTERACTIVE users to have all modify permissions on cacerts except "change permissions" and "take ownership" (from Advanced Settings, in the Security properties).  I assume that allowing these services to both read and write extended attributes may have something to do with the error going away.


text:
Q: Aliquot results after division I'm trying to get results with no aliquot + addig the percent mark to them.
I'm using below row code:
(cast(step_out_quantity as float) / step_in_quantity *100.00) as Yield

My output column looks like this:
Yield
57.1428571428571
100
100
100
87.5
100
90.9090909090909
98.1132075471698
99.1525423728814
93.3333333333333

What is my best option to achieve the next results:
Yield
57%
100%
100%
100%
87%
100%

A: In standard SQL you can do:
select concat(cast(cast(step_out_quantity*100 as int
                       ) / step_in_quantity as varchar(255)
                  ), '%'
             ) as Yield

In SQL Server, you can do:
select cast(floor(step_out_quantity * 100) as varchar(255)) + '%'


text:
Q: How many numbers $x$ less than $30030$ are there such that $30030$ divides $x^3-1$ How would you tackle this problem? I am looking for hints. The things I have observed so far: $30030 = 2\cdot3\cdot5\cdot7\cdot11\cdot13$. So none of these prime numbers can divide $x$. This gets rid of a significant number of candidates but still leaves a merry number of them hanging.
EDIT: I didn't mention it but we are looking for positive solutions.

A: Here is a start. The Chinese Remainder Theorem tells us that we can deal with each of the primes separately. Let's take some examples:
For the prime $2$ it is obvious that $x$ must be odd.
Modulo the prime $5$ the cubes are $0^3=0, 1^3=1, 2^3=3, 3^3=2, 4^3=4$ so we must have $x\equiv 1 \bmod 5$
Modulo the prime $7$ we find that $1^3=2^3=4^3=1$ so $\frac 37$ of the possibilities work modulo $7$.
See if you can work it out from here before you read on.

Now the difference between $5$ and $7$ is that $7-1=2\times 3$ where $3$ is the power we are interested in. Modulo $7$ we have $x^6-1=0=(x^3-1)(x^3+1)$ (little Fermat) and there are three cube roots of $1$ rather than just the one.

With these clues you should be able to work it out (if in doubt try $70$ instead of $30030$ to start with)


text:
Q: How to extract some part of a string? I have a string = "C:\Users\Desktop\bin\data\so on"
I want to extract just the "C:\Users\Desktop\" part..
what is the easiest way to get the result ?

A: string s = @"C:\Users\Desktop\bin\data\so on";
string result = String.Join("\\",s.Split('\\').Take(3));

Result
C:\Users\Desktop

A: Take in to account that there're two possible directory separators (your input looks like a path):
  String s = "C:\Users\Desktop\bin\data\so on";

  String result = String.Join(Path.DirectorySeparatorChar.ToString(),
                              s.Split(Path.DirectorySeparatorChar,
                                      Path.AltDirectorySeparatorChar).Take(3));

Or if you want to keep on until "/bin" or "\bin" is found you should change Take to TakeWhile:
  String result = String.Join(Path.DirectorySeparatorChar.ToString(),
                          s.Split(Path.DirectorySeparatorChar,
                                  Path.AltDirectorySeparatorChar).TakeWhile(
                                    x => !String.Equals(x, "bin", StringComparison.OrdinalIgnoreCase)));

Naive soultion as Substring(@"\bin") can be dangerous on inputs like that "C:\Windows\MyBins\Bin\SomeStaff"


text:
Q: Beamer - Compile each section into a separate PDF including complete Table of Contents in each file Let us suppose I have a Beamer presentation structured roughly like this:
Title page

Table of contents
    sec1
    sec2
    sec3
    ...

\section{sec1}
  \frametitle{frame1}
  \frametitle{frame2}
  \frametitle{frame3}
  ....

\section{sec2}
  \frametitle{frame1}
  \frametitle{frame2}
  \frametitle{frame3}
  ....

\section{sec3}
  \frametitle{frame1}
  \frametitle{frame2}
  \frametitle{frame3}
  ....
...

I would like to compile each single section into a separate PDF, but each PDF should include the title page and the complete table of contents.
Is that possible? How can I achieve that?


text:
Q: Can someone please show me how to add an image/file upload to this code and then save it to the firebase firestore? import React from 'react';
    import {
      SafeAreaView,
      TextInput,
      Button,
      ActivityIndicator,
      Text,
      View,
    } from 'react-native';
    import {Formik} from 'formik';
    import * as yup from 'yup';
    import StyledInput from './styledInput';
    import validationSchema from './validationSchema';

    const ProductListingForm = () => (
      <SafeAreaView style={{marginTop: 90}}>
        <Formik
          initialValues={{
            listingTheme: '',
            size: '',
            barcode: '',
            description: '',
            units: '',
            listingName: '',
            quantity: '',
          }}
          onSubmit={(values, actions) => {
            alert(JSON.stringify(values));
            setTimeout(() => {
              actions.setSubmitting(false);
            }, 1000);
          }}
          validationSchema={validationSchema}>
          {formikProps => (
            <React.Fragment>
              <StyledInput
                label={'Product Name'}
                formikProps={formikProps}
                formikKey="listingName"
                placeholderText={'Enter Product Name'}
                autoFocus
              />
              <StyledInput
                label={'Product Theme'}
                formikProps={formikProps}
                formikKey="listingTheme"
                placeholderText={'Enter a theme that describes your product'}
              />
              <StyledInput
                label={'Barcode'}
                formikProps={formikProps}
                formikKey="barcode"
                placeholderText={'Scan/Enter Barcode'}
              />
              <StyledInput
                label={'Size'}
                formikProps={formikProps}
                formikKey="size"
                placeholderText={'Enter Product Size'}
              />
              <StyledInput
                label={'Units'}
                formikProps={formikProps}
                formikKey="units"
                placeholderText={'Enter Product Units'}
              />
              <StyledInput
                label={'Description'}
                formikProps={formikProps}
                formikKey="description"
                placeholderText={'Describe your product'}
              />

              {formikProps.isSubmitting ? (
                <ActivityIndicator />
              ) : (
                <Button title="Submit" onPress={formikProps.handleSubmit} />
              )}
            </React.Fragment>
          )}
        </Formik>
      </SafeAreaView>
    );
    export default ProductListingForm;

Above is my product listing form I created using Formik. I would love to be able to add photos to this form as an array as well as saving the form data values so I can load them on a product listing card. If anyone knows how or has any guides on Formik and Firebase please help me. I just need a little guidance and then I can take it from there.


text:
Q: How to relayout content of NSTextView so that my tab characters are drawn with width of 4 characters I'm working with an NSTextView and one of the requirements I have is that a tab character, '\t', shall have the same width as four spaces.
So the text-content would look like this:
AAAA
    AAAA - 1 tab
    AAAA - 4 spaces

And this is how I accomplish this:
// done when NSTextView first loaded and when
// delegate's textDidBeginEditing gets called: (perhaps overkill, but is a work in progress).
- (void)updateMyTextViewTextAttributes
{
    NSMutableParagraphStyle* paragraphStyle = [[myTextView defaultParagraphStyle] mutableCopy];
    if (paragraphStyle == nil) {
        paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    }
    float charWidth = [[myFont screenFontWithRenderingMode:NSFontDefaultRenderingMode] advancementForGlyph:(NSGlyph) ' '].width;
    [paragraphStyle setDefaultTabInterval:(charWidth * 4)];
    [paragraphStyle setTabStops:[NSArray array]];
    [myTextView setDefaultParagraphStyle:paragraphStyle];

    NSMutableDictionary* typingAttributes = [[myTextView typingAttributes] mutableCopy];
    [typingAttributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
    [typingAttributes setObject:scriptFont forKey:NSFontAttributeName];
    [myTextView setTypingAttributes:typingAttributes];
}

This allows the appropriate layout to be shown with the initial text as well as keep the typing attributes the same.
The problem is that the end-user can change the font. And when that happens, the sample text becomes misaligned. Much like the below:
[smaller font]
AAAA
     AAAA - 1 tab
    AAAA - 4 spaces

[larger font]
AAAA
   AAAA - 1 tab
    AAAA - 4 spaces

I've tried calling myTextView's setNeedsDisplay:YES as I read that it ends up calling NSTextView's setNeedsDisplayInRect:avoidAdditionalLayout with a NO for the avoidAdditionalLayout parameter. This didn't change anything.
I've tried calling my updateMyTextViewTextAttributes call when myTextView has the new myFont set. That doesn't change a thing.
I've also tried telling the layoutManager of myTextView to ensureLayoutForTextContainer for the textContainer of myTextView. No change.
At this point, I'm not sure what to try next. Any suggestions?

A: Douglas Davidson of Apple provided me with the clues to get to the answer via the cocoa-dev@apple.lists.com email list.
I've resolved the problem by updating the updateMyTextViewTextAttributes function like so:
- (void)updateMyTextViewTextAttributes
{
   NSMutableParagraphStyle* paragraphStyle = [[myTextView defaultParagraphStyle] mutableCopy];

   if (paragraphStyle == nil) {
       paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
   }

   float charWidth = [[myFont screenFontWithRenderingMode:NSFontDefaultRenderingMode] advancementForGlyph:(NSGlyph) ' '].width;
   [paragraphStyle setDefaultTabInterval:(charWidth * 4)];
   [paragraphStyle setTabStops:[NSArray array]];

   [myTextView setDefaultParagraphStyle:paragraphStyle];

   NSMutableDictionary* typingAttributes = [[myTextView typingAttributes] mutableCopy];
   [typingAttributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
   [typingAttributes setObject:scriptFont forKey:NSFontAttributeName];
   [myTextView setTypingAttributes:typingAttributes];

   /** ADDED CODE BELOW **/
   NSRange rangeOfChange = NSMakeRange(0, [[myTextView string] length]);
   [myTextView shouldChangeTextInRange:rangeOfChange replacementString:nil];
   [[myTextView textStorage] setAttributes:typingAttributes range:rangeOfChange];
   [myTextView didChangeText];

   [paragraphStyle release];
   [typingAttributes release];
}

A: Have you tried to compute space advancement with advancementForGlyph: directly on the font instead of the screen font ?
float charWidth = [myFont advancementForGlyph:(NSGlyph) ' '].width;

Screen font are not meant to be used directly outside the window server:

Screen fonts are for direct use with
  the window server only. Never use them
  with Application Kit objects, such as
  in setFont: methods. Internally, the
  Application Kit automatically uses the
  corresponding screen font for a font
  object as long as the view is not
  rotated or scaled.


text:
Q: ORACLE constraints based on 2+ tables I have the following three tables:
CREATE TABLE Flights (
  route_number INT NOT NULL PRIMARY KEY,
  operated_by INT NOT NULL,
  airplane_model  VARCHAR(30) NOT NULL,
  source VARCHAR(20),
  destination VARCHAR(20),
  FOREIGN KEY (operated_by) REFERENCES Airline(airline_id),
  FOREIGN KEY (airplane_model) REFERENCES Airplanes(airplane_id)
  );
CREATE TABLE outgoing (
  route_number INT NOT NULL PRIMARY KEY,
  poTime Date NOT NULL,
  FOREIGN KEY (route_number) REFERENCES Flights(route_number)
);

    CREATE TABLE incoming (
    route_number INT NOT NULL PRIMARY KEY,
    paTime date NOT NULL,
    FOREIGN KEY (route_number) REFERENCES Flights(route_number)
  );
  CREATE TABLE departures(
    depid int not null PRIMARY KEY,
  route_number INT NOT NULL,
   gate VARCHAR(3) NOT NULL,
    depT date NOT NULL,
    depD date NOT NULL,
status VARCHAR(10),
    FOREIGN KEY (route_number) REFERENCES Flights(route_number)
);

      CREATE TABLE ARRIVALS(
  route_number INT NOT NULL,
   gate VARCHAR(3) NOT NULL,
    arrT date NOT NULL,
    arrD date NOT NULL,
status VARCHAR(10),
    arrid int not null PRIMARY KEY,
    FOREIGN KEY (route_number) REFERENCES Flights(route_number)
);

I am trying to create a constraint that no two flights can have the same gate during a planned time (paTime and poTime) interval of -1,+1 hour around their planned time.
I thought I should create a view and insert into the view...But apparently you are not allowed to have Subqueries in an updateable view table?
how would i go about adding this constraint?
Note: PaTime and PoTime are planned arrival time and planned departure times whereas arrT and depT are actual arrival and actual departure times, and they are allowed to be different.
SO basically:
1. A flight is added to the flight table (no extra constraints needed)
2. If it's an incoming flight, its Planned arrival time is added to the Arrivals table (again no constraints to worry about).
3. In the Arrivals table, it's Actual arrival time (can be different from planned arrival time), status, and gate is added to the table. This is where I need a constraint! To check if that gate number exists in this table and the Departures table -1 to +1 hours from their Planned arrival/departure times.
So for this table I need a way of joining Incoming (for Patime) Outgoing (for Potime) time and check for constraints

A: A constraint can only reference one table.  If you are required to use this data model, you cannot create a constraint that does what you want.
You have a few options

*

*Instead of creating a constraint, you can create a stored procedure that does the INSERT of a new flight and that implements whatever validations you want.  You then restrict the application from issuing a direct INSERT on the tables and require it to use the stored procedure instead.

*You can keep the existing data model and create an ON COMMIT materialized view that combines the data from departures and arrivals and then create a constraint on that materialized view.

*You can modify the data model so that all the information you need for the constraint is in a single table.


text:
Q: How to Separate When updateSearchResultsForSearchController Is Called Due to the Edit or Due to the First Responder In the documentation it is written that the method
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController
is called in two cases: when the search bar becomes the first responder or when the user makes changes inside the search bar.
It is possible to resign the first responder with:
[complaintSearchController.searchBar resignFirstResponder];

However, is there any possibility to call customMethod only in the cases if the user edits the text in the search bar?
The code is above:
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    [self customMethod];
}

Perhaps it is possible to detect the state with any conditional statement:
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
  if (condition){
      [self customMethod];
  }
}

For example, if([complaintSearchController.searchBar isFirstResponder]) does not cover it.
Basically, I need to separate these two cases when this method is called.

A: I would try an NSNotification that triggers on the protocol UISearchResultsUpdating for your search controller. You can then set that method in your target for the NSNotification.
 - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
    {
       [[NSNotificationCenter defaultCenter] postNotificationName:@"CustomName" object:nil];
      //or potentially you could just call your custom method directly
    }

This method is automatically called whenever the search bar becomes the first responder or changes are made to the text in the search bar. Perform any required filtering and updating inside of this method.
[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(customMethod)
                                                 name:@"CustomName"
                                               object:nil];

Maybe save the last state of the user input and check if the text has then changed by doing a isEqualToString:

A: I would add a state in the View Controller:
private var vmSearchBarInputDidChange: Bool = false

Set this to true in the "-DidChange" UISearchBarDelegate methods, i.e.:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)
func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int)

Now in the updateSearchResults func, we can:
guard vmSearchBarInputDidChange else { return }

before doing actual searching.
After performing searching, reset the state before exiting:
vmSearchBarInputDidChange = false // reset


text:
Q: How to access nested values in JSON using X-SuperObject I want to get all the users from this json.
{
  "status": "ok",
  "next_max_id": "AQAmA1l9NAQXa",
  "sections": [
    {
      "module": null,
      "show_view_all": null,
      "title": null,
      "users": [
        {
          "pk": 48165888,
          "is_verified": false,
          "profile_pic_url": "http://scontent-sit4-1.cdninstagram.com/t51.2885-19/s150x150/17332306_1915592632007479a.jpg",
          "full_name": "Jason Giovany Castro Morales",
          "is_private": false,
          "has_anonymous_profile_picture": false,
          "username": "jasongiovanycastromorales",
          "profile_pic_id": "14699765111792881_48165888"
        }
      ]
    }
  ]
}

Now, my attempt to get all usernames.
procedure TForm2.Button6Click(Sender: TObject);
var
  json : ISuperObject;
  node : ISuperObject;
  item : IMember;
begin
  try
    json := TSuperObject.Create(list.Text);

    for item in json['sections.users'].AsArray do
    begin
      node := item.AsObject;
      Memo4.Lines.Add(node.S['username']);
    end;
  finally
  end;
end;

2nd attempt.. i get an AV !
var
    json         : ISuperObject;
    node         : ISuperObject;
    item, item2         : IMember;
  begin
     json := SO(list.Text);

   for item in json['sections'].AsArray do
    begin
       for item2 in json['users'].AsArray do
        begin
        node := item.AsObject;

        Memo1.Lines.Add(node.S['username']);
       end;
     end;
  end;

there are 200 username value in this JSON
I get nothing, sometimes AV when i try to play around withthe json code,  my question is, how to parse this json correctly to get the value username? Thank You.

A: Your example is broken and you didn't specify the format of input data, like I don't know, if all objects in sections array contains users array. Anyway, this example should be working for your snippet.
SuperObject
procedure TForm2.Button6Click(Sender: TObject);
var
  json, user, section : ISuperObject;
begin
  json := SO(list.Text);
  for section in json['sections'] do
  begin
    if Assigned(section['users']) then
    begin
      for user in section['users'] do
      begin
        if user.S['username'] <> '' then
          Memo4.Lines.Add(user.S['username']);
      end;
    end;
  end;
end;

EDIT :
In fact, you are not using SuperObject, but X-SuperObject, which is something different. Even though I've never used that library, I was able to find the problem only with examples from their website, because u make simple mistakes like using item instead of item2 or json and item in second loop.
X-SuperObject
procedure TForm2.Button6Click(Sender: TObject);
var
  json : ISuperObject;
  item, item2 : IMember;
begin
  json := TSuperObject.Create(list.Text);
  for item in json['sections'].AsArray do
  begin
    for item2 in item.AsObject['users'].AsArray do
      Memo1.Lines.Add(item2.AsObject['username'].ToString);
  end;
end;

A: DISCLAIMER: this answer relates to SuperObject. At the time, this answer was given, it was unknown that the question actually refers to XSuperObject.

I get nothing

This is unlikely because you should at least get an access violation. This is because, you are not creating the superobject the right way.
I recommend you to use the factory function SO() instead of calling the constructor TSuperObject.Create.
Then you have to remember that both sections and users are arrays. Thus, you need to iterate both arrays in a nested iteration:
var
  json: ISuperObject;
  section: ISuperObject;
  user: ISuperObject;
begin
  json := SO(list.Text);
  for section in json['sections'] do // iterate sections
    for user in section['users'] do  // iterate users
      Memo4.Lines.Add(user.S['username']);
 end;

Note: This example is a minimal approach. You should add further checking (e.g. Assigned()) to prevent exceptions.


text:
Q: Как сделать высоту тега text равной высоте svg

.card-header__title {
    width: 850px;
    height: 125px;
    margin: 0 auto 130px;
    font-size: 146px;
    display: block;
    font-family: 'Open Sans Condensed', sans-serif;
    font-weight: 300;
    text-transform: uppercase;
    letter-spacing: .05em;
}
<svg class="card-header__title sm-hidden" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
            <defs>
                <linearGradient id="textgradient" x1="0%" x2="0%" y1="0%" y2="100%">
                    <stop stop-color="#6dc1df" offset="0%"></stop>
                    <stop stop-color="#63b4dd" offset="20%"></stop>
                    <stop stop-color="#9fd5e7" offset="70%"></stop>
                    <stop stop-color="#E8F3F5" offset="100%"></stop>
                </linearGradient>
            </defs>
            <text x="0" y="120" fill="url(#textgradient)">Карта клиента</text>
        </svg>

Ссылка на код: jsfiddle.net/ye6ct5qz
код выше

Можно как нибудь регулировать высоту тега text?

A: Вам нужно не высоту шрифта менять, а описать в каком масштабе у Вас отображается SVG, для этого используется атрибут viewBox.
Допустим, шрифт у меня будет размером 10. 10 это относительная единица, пока мы не указали масштаб, мы точно не знаем сколько это. Поэтому укажем масштаб с помощью viewBox:
<svg class="card-header__title sm-hidden" viewBox="0 0 85 12.5 ">

viewBox содержит 4 цифры - Х Y координаты верхнего левого угла, ширину и высоту. С помощью этих цифр можно указать, какая именно часть SVG будет отображаться в SVG-контейнере. Я указал высоту шрифта 10, а высота viewBox 12.5 — высота шрифта чуть меньше высоты SVG
C учетом того, что вы указали размеры SVG:
.card-header__title {
    width: 850px;
    height: 125px;
    ...
}

Можно посчитать, что 1 единица SVG = 850px / 85 = 10px. Если вы уменьшите высоту SVG, допустим вдвое, то 1 единица SVG = 425px / 85 = 5px. Таким образом, при изменении размеров  SVG-контейнера масштаб будет автоматически изменятся, и высота шрифта будет относительна высоте SVG
Кстати, по умолчанию, масштаб по X и Y сохраняется, те картинку нельзя сжать только по одной оси. Этим управляет атрибут preserveAspectRatio
Если что-то осталось непонятным изучайте:
Как взаимодействуют между собой viewport и viewBox
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/preserveAspectRatio
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewBox

.card-header__title {
  width: 850px;
  height: 125px;
  margin: 0 auto 130px;
  display: block;
  font-family: 'Open Sans Condensed', sans-serif;
  font-weight: 300;
  text-transform: uppercase;
  letter-spacing: .05em;
}
<svg class="card-header__title sm-hidden" height="125" viewBox="0 0 85 12.5">
            <defs>
                <linearGradient id="textgradient" x1="0%" x2="0%" y1="0%" y2="100%">
                    <stop stop-color="#6dc1df" offset="0%"></stop>
                    <stop stop-color="#63b4dd" offset="20%"></stop>
                    <stop stop-color="#9fd5e7" offset="70%"></stop>
                    <stop stop-color="#E8F3F5" offset="100%"></stop>
                </linearGradient>
            </defs>
            <text x="0" y="10" fill="url(#textgradient)"  font-size="10" >Карта клиента</text>
</svg>


text:
Q: What is the advantage of using the use function in PHP? If write my callback-function this way ...
$direction = 'asc';
$compare = function ($a, $b) use ($direction) {
...

... then the script shows the same behaviour as with this:
$direction = 'asc';
$compare = function ($a, $b, $direction = 'asc') {
...

In both cases the variable is passed by value.
So, what's the advantage of using the use-function instead of passing the variable via standard function-parameter?

A: $compare = function ($a, $b, $direction = 'asc') { ... };

This is a normal function which accepts 3 parameters, the last of which is optional. It needs to be called like:
$compare('foo', 'bar', 'desc');

Here:
$direction = 'asc';
$compare = function ($a, $b, $direction = 'asc') { ... };

The two $direction variables have absolutely nothing to do with each other.
If you do:
usort($array, $compare)

then usort will only ever call $compare with two arguments, it will never ever pass the third argument which will always remain at its default value asc.
$direction = 'asc';
$compare = function ($a, $b) use ($direction) { ... };

Here the $direction variable is actually included in the function.
$direction = 'asc';  -----------------+
                                      |
$compare = function ($a, $b) use ($direction) {
                                      |
    echo $direction;  <-------------- +
};

You are extending the scope of the variable into the function. That's what use does. Also see Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?.

A: What is use?
use means to inherit variables or values from current scope. Parameter can be given from anywhere, but used variable can exist only under certain circumstances. So you might not be able to use closure outside a scope, where used variable is not set:
<?php
header('Content-Type: text/plain; charset=utf-8');

$fn = function($x)use($y){
    var_dump($x, $y);
};

$fn(1);
?>

Shows:
Notice:  Undefined variable: y in script.php on line 4
int(1)
NULL

However, you can use parametrized closure without such scope-dependecy:
<?php
header('Content-Type: text/plain; charset=utf-8');

$fn = function($x, $y = null){
    var_dump($x, $y);
};

$fn(1);
?>

See related question: In PHP 5.3.0, what is the function "use" identifier?.
What's an advantage?
One of the main use cases of use construct is using closures as a callback for other functions (methods). In this case you must follow fixed number of function parameters. So the only way to pass extra parameters (variables) to a callback is use construct.
<?php
header('Content-Type: text/plain; charset=utf-8');

$notWannaSeeThere = 15;
$array  = [ 1, 15, 5, 45 ];
$filter = function($value) use ($notWannaSeeThere){
    return $value !== $notWannaSeeThere;
};

print_r(array_filter($array, $filter));
?>

Shows:
Array
(
    [0] => 1
    [2] => 5
    [3] => 45
)

In this example, $filter closure is used by array_filter() and called with only one argument - array element value (and we "can not" force it to use additional arguments). Still, we can pass there additionl variables, which availible in parent scope.
Reference: anonymous functions.

Inheriting variables from the parent scope is not the same as using
  global variables.


text:
Q: Which UPDATE statement to change my TIMESTAMP only when i change my char to '1'? PHP, mysql This is my table in mysql db:
CREATE TABLE admins (
id int NOT NULL AUTO_INCREMENT,
bez varchar(55) DEFAULT 'unknown',
type varchar(7) NOT NULL DEFAULT 'unknown',
exist char NOT NULL DEFAULT '0',
tm TIMESTAMP default CURRENT_TIMESTAMP;

PRIMARY KEY ('id')
);

I want to update my timestamp only when i set exist to '1'.
Not when I change any column.
This is my UPDATE statement:
<?php
    if ( isset($_GET["id"]) ) {
        $id = $_GET["id"];

        $sql = "UPDATE admins SET exist='1' WHERE id=$id";
        $con->query($sql);
    }

    header("location: /index.php");
    exit;
    ?>

I tried different ways to combine it with tm but it didnt worked!
I tried stuff like this:
    if ( isset($_GET["id"]) ) {
        $id = $_GET["id"];

$tm = date('Y-m-d H:i:s');

        $sql = "UPDATE admins SET exist='0', tm=$tm WHERE id=$id";
}

using AND didnt worked.
I tried ON UPDATE CURRENT_TIMESTAMP in sql but it didnt works for me. Because i want only new tm if exist is '1'.
I tried this in sql:
DELIMITER $$

CREATE TRIGGER trigger_name
    AFTER UPDATE
    ON admins FOR EACH ROW
BEGIN
  IF NEW.exists = 1 THEN
    SET NEW.tm = NOW();
  END IF;
END$$

DELIMITER ;

but i get a sql error message:
ERROR 1362 (HY000): Updating of NEW row is not allowed in after trigger

so i tried to use BEFORE instead of AFTER but i didnt changed the tm at all.
Do you have any ideas?
What can i do to solve my issue?
Goal: UPDATE tm when setting exist to '1'
dont tell me that i am open to sql injections!
Thanks for your help!

A: Looks like a trigger will solve this for you.
If we make it a BEFORE UPDATE which is allowed to update the NEW values where an AFTER UPDATE trigger is not, as per your error message, and remove a couple of syntax errors, the trigger might look like this
DELIMITER $$
CREATE TRIGGER upd_date_if_exists_is_one
    BEFORE UPDATE ON admins FOR EACH ROW
    BEGIN
        IF NEW.`exist` = 1 AND old.`exist` <> 1 THEN
            SET NEW.tm = NOW();
    END IF;
END$$
DELIMITER ;

If you leave the tm TIMESTAMP default CURRENT_TIMESTAMP; so that will set the tm column when the initial INSERT is done, but not update the tm when any subsequent updates are done.

A: UPDATE: Added PDO to account for SQL Injection Attacks.
Change your AFTER UPDATE trigger above to BEFORE UPDATE:
DELIMITER $$

CREATE TRIGGER TR_admins_BU
    BEFORE UPDATE
    ON admins FOR EACH ROW
BEGIN
  IF NEW.exist = '1' THEN
    SET NEW.tm = CURRENT_TIMESTAMP;
  END IF;
END$$

DELIMITER ;

Declare a constant for exist so you can change it when you want. UPDATE your query, passing in your exist value by your id:
  <?php

    if (isset($_GET["id"]) ) {

    $id = $_GET["id"];
    $exist = '1'; //change this to '0' if you do not want to update the timestamp

    try {

        $conn = new PDO('mysql:host='.HOST.';dbname='.DATABASE,USERNAME,PASSWORD);

        $sql = "UPDATE `admins` SET `exist` = :exist WHERE `id` = :id";

        $statement = $conn->prepare($sql);
        $statement->bindValue(":exist", $exist);
        $statement->bindValue(":id", $id);
        $statement->execute();

        $conn = null; //Disconnect Connection

    } catch(PDOException $e) {
        echo $e->getMessage();
    }

header("location: /index.php");
exit;
?>

See Fiddle.


text:
Q: '&' character in a text automatically converted to '&' in SQL server while passing via parameter I am passing a text value say 'Test 1 & 2' to stored procedure via parameter.
While SQL server runs the SP, the parameter value '&' is automatically converted '&amp'.
I am basically searching for the text passed against table. In my table, I have records saved with '&'.
How to fix this?

A: Got into a similar issue used the below when using Stuff on sql server
The below query changes the & as '&amp'.
(SELECT STUFF((SELECT ';'+ Name FROM TABLE
FOR XML PATH(''),1,1,'')

The below query changes the & as &.
(SELECT STUFF((SELECT ';'+ Name FROM TABLE
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'')

This has sorted out the issue. The issue occurs when you merge & with other columns by default it converts the value to '&amp'.


text:
Q: Codename One class file for PrintWriter not found I have a problem, in the class generated by WebService Wizard of codename one.
I can do the import java.io.PrintWriter, but when I compile the project I get this error:

error: cannot access

PrintWriter PrintWriter out = response.getWriter();

class file for java.io.PrintWriter not found

screenshot
Any suggestions?

A: That class isn't included in CN1. See the Javadoc here: https://www.codenameone.com/javadoc/index.html

A: You generated the servlet portion into the Codename One project instead of generating it into a JavaEE project. As James said that class doesn't exist in Codename One and neither does servlets.
I'm guessing you "fixed" the latter by changing the classpath of the Codename One project which you shouldn't have!
The wizard uses the current project for generating the stubs/skeletons it then asks you for a path to the server project and you picked the Codename One project instead of a WAR (web) project.


text:
Q: How to minimize the number of edge crossings with diagrammer, R? When I plot a network graph with diagrammer, like the following toy example...
library(DiagrammeR)
Dia <- function(edg, nodesd) {
         nodes <-   create_node_df(  n=length(nodesd), label=nodesd,
         width=0.3)
         edges <- create_edge_df(from = edg$EveFrom, to = edg$EveTo,
                rel = "leading_to")
graph <-   create_graph(  nodes_df = nodes, edges_df = edges)
render_graph(graph)
}

niv <- c("A","B","C","D","E","X","Y")

temp <- data.table(EveFrom=factor(c("A","A","A","A","B","C","D","E",
     "X", "B"), levels=niv),
EveTo=factor(c("B","C","D","E","X","X","Y","Y","Y", "C"), levels=niv))

Dia(temp,niv)

How can I tell diagrammer to minimize the number of edge crossings automatically?
In this simple example if C and B positions were exchanged the result wouldn't have any edge crossing.
In more complex examples we cannot remove all crossings but at least minimize it.
With visnetwork I can relocate the nodes

But it has other drawbacks, for example it doesn't let you export it as a vector graphic.
PD: This is the output with bergant solution (with labels hidden):

A: I think the dot layout will produce it better. Add global attributes like this:
graph <- create_graph(  nodes_df = nodes, edges_df = edges)
graph <- set_global_graph_attrs(graph, "layout", "dot", "graph")
graph <- add_global_graph_attrs(graph, "rankdir", "LR", "graph")

A: use dot layout option (made with inspiration from here)
# install.packages(c("DiagrammeR"), dependencies = TRUE)
library(DiagrammeR)

grViz("
digraph dot {

graph [layout = dot] # dot, neato, twopi, and circo

A -> {B C D E}
B -> {C X}
C -> {X}
D -> {Y}
E -> {Y}
X -> {Y}
}")


text:
Q: How to set default font, or default style in Graphviz's Dot language It seems, every tutorial every example scripts explicitly states what font should be used for each node/arrow.
Instead, I'd like to specify default font which all arrows and nodes use only once (may at the beginning of file, or maybe separate style file sheets)
link

A: Put something like this at the top level:
node [fontname="default-node-font"];
edge [fontname="default-edge-font"];

I can't find this explicitly in the online manual (it's alluded to under https://www.graphviz.org/doc/info/lang.html#lexical-and-semantic-notes) but it's clearly documented in the man page.


text:
Q: How to load CICS parameters update after defining DFHSIT SPOOL=YES system intialization parameter? I updated the DFHSIT$$ in CICSTS54.CICS.SDFHSAMP where I changed SPOOL=NO to SPOOL=YES. How can I make CICS to load the updated table?

A: Now that you have updated your SIT table in DFHSIT$$ you will need to compile it, see https://www.ibm.com/docs/en/cics-ts/5.4?topic=parameters-assembling-sit for details.
Once the compilation has been done you will need to restart your CICS region for it to pick up the changes.  I assume that you already have SIT=$$ specified within the SIT overrides in the CICS JCL, for example:
//SYSIN    DD *
SIT=$$
.
.
.
/*

A: what you have posted is a translate,compile and link edit for a COBOL program. The DFHSIT table is an assembler table which needs to be assembled using the assembler.
However, what would be easier for you in this case would be to not assemble a new version of the default DFHSIT table. Instead, just add a SPOOL=YES to the SIT overrides when you start CICS.
The sit overrides are set in SYSIN on your CICS startup JCL
e.g.
//SYSIN    DD *
SPOOL=NO


text:
Q: Why can't I run gpg in non-interactive mode successfully? I'm writing a script that uses gpg to encrypt a file. During testing/experimentation with gpg from the command-line, I found some odd behavior. This works perfectly fine:
$ cat myFile.txt | gpg --encrypt -r 'jdoe@gmail.com'
gpg: B2D17635: There is no assurance this key belongs to the named user

pub  4096R/B2D17635 2016-01-31 John Doe (I am now a real person.) <jdoe@gmail.com>
 Primary key fingerprint: B17F 98BA 1DA9 3FE1 A08F  1443 509D 87ED 32AF 2078
      Subkey fingerprint: BB63 42DA 8FAD 194A E1C9  1F6D 39BA 73B9 B2D1 7635

It is NOT certain that the key belongs to the person named
in the user ID.  If you *really* know what you are doing,
you may answer the next question with yes.

Use this key anyway? (y/N) y
�
Nϴ��[�mDZ.@�Bc���J������z�{p���%
<GIBBERISH SNIPPED>
i�)��/&N��t�Z�8�#�I<�Bq�!�K?�vQ�I�H6&+��(

But I don't like that because I interactively had to type 'y'. I would like it to assume "yes" and do the encryption without requiring any interactivity. So I ran the following command with the --batch and --yes switches. Why did it fail?
$ cat myFile.txt | gpg --encrypt --batch --yes -r 'jdoe@gmail.com'
gpg: B2D17635: There is no assurance this key belongs to the named user
gpg: [stdin]: encryption failed: unusable public key

A: The error you're receiving from GnuPG is because the public key isn't trusted/verified within your keyring. Because your OP stated that your running tests you may want to check out the code within a helper script written for my own experiments, GnuPG_Gen_Key.sh, specifically the functions copied/modded below.
#!/usr/bin/env bash
Var_gnupg_import_key="${1}"
Var_gnupg_import_key_trust="${2}"
Func_import_gnupg_key_edit_trust(){
    _gnupg_import_key="${1:-${Var_gnupg_import_key}}"
    gpg --no-tty --command-fd 0 --edit-key ${_gnupg_import_key} <<EOF
trust
${Var_gnupg_import_key_trust}
quit
EOF
}
Func_import_gnupg_key(){
    _gnupg_import_key="${1:-${Var_gnupg_import_key}}"
    if [ -f "${_gnupg_import_key}" ]; then
        echo "# ${Var_script_name} reports: importing key file [${_gnupg_import_key}]"
        gpg --no-tty --command-fd 0 --import ${_gnupg_import_key} <<EOF
 trust
${Var_gnupg_import_key_trust}
quit
EOF
    else
        _grep_string='not found on keyserver'
        gpg --dry-run --batch --search-keys ${_gnupg_import_key} --keyserver ${Var_gnupg_key_server} | grep -qE "${_grep_string}"
        _exit_status=$?
        if [ "${_exit_status}" != "0" ]; then
            _key_fingerprint="$(gpg --no-tty --batch --dry-run --search-keys ${_gnupg_import_key} | awk '/key /{print $5}' | tail -n1)"
            _key_fingerprint="${_key_fingerprint//,/}"
            if [ "${#_key_fingerprint}" != "0" ]; then
                echo "# ${Var_script_name} reports: importing key [${_key_fingerprint}] from keyserver [${Var_gnupg_key_server}]"
                gpg --keyserver ${Var_gnupg_key_server} --recv-keys ${_key_fingerprint}
                Func_import_gnupg_key_edit_trust "${_gnupg_import_key}"
            else
                echo "# ${Var_script_name} reports: error no public key [${_gnupg_import_key}] as file or on key server [${Var_gnupg_key_server}]"
            fi
        else
            echo "# ${Var_script_name} reports: error no public key [${_gnupg_import_key}] as file or on key server [${Var_gnupg_key_server}]"
        fi
    fi
}

One can either trust the public key with above or use the following command to have GnuPG ignore trust issues.
gpg --armor --always-trust -r 'jdoe@gmail.com' -e myFile.txt -o myFile.txt.gpg

Note I've added the --armor option because the output in the OP looks to have missed that based off the snipped output.

A: You have to add --always-trust to your command:
echo "test" | gpg --batch --yes --always-trust --encrypt --armor -r "mail@example.com"

A: Probably better than using --always-trust is to sign the keys your are relying on once with your private key.
Then gpg won't ask again.
Also you encrypted standard input, so the ciphertext will be sent to standard output.
In most cases you want to use option --armor to produce ASCII output.


text:
Q: AngularJs ngdocs: annotate that a method returns a promise Im am currently in the process of documenting my first real AngularJs app, for wich a am using ngdocs syntax with grunt-ngdocs
I was wondering if there is a better way to annotate that my service method returns a promise (so you know you should append a .then() instead of accessing the return object.
   * @returns {object} returns a promise

Full context of the service:
/**
 * @ngdoc service
 * @name appServices.Authentication
 * @requires $http
 * @description
 * Service used to authenticate request to an api. It injects a session parameter into each request if the token parameter is set.
 * (as a request param for a GET and as an extra body param for a POST)
 **/
module.factory('Authentication', ['$http', function ($http) {

    var token;

    /**
     * @ngdoc method
     * @name appServices.Authentication#login
     * @methodOf ng.service
     * @returns {object} returns a promise
     */
    function login(email, password) {
        return $http.post('/auth/login', {email: email, password: password})
            .then(function (response) {

                if (response.data.token) {
                    token = response.data.token;
                }
            });
    }

    function getToken() {
        return token;
    }

    return {
        login: login,
        token: getToken,
    };
}]);

A: You can simply write:
* @returns {Promise} returns a promise


text:
Q: npm run script returns "No such file or directory" when trying to bundle files I am trying to make all our Angular web components use the same build steps in our Bamboo build server. All projects must be built like this:

*

*npm install

*npm run build

*npm run bundle

npm run build works perfectly. It's simply executing this command:
ng build --prod --output-hashing=none --single-bundle

This creates a directory called dist that includes the following files:

*

*main-es5.js

*main-es2015.js

*polyfills-es5.js

*polyfills-es2015.js

*scripts.js

I need to bundle the *-es5.js and *-es2015.js files into their own single file, instead of two files. That is why I call npm run bundle, which is this command:
cat dist/{polyfills-es5,main-es5}.js > dist/element-es5.js && cat dist/{polyfills-es2015,main-es2015}.js > dist/element-es2015.js

However, it seems like it cannot find the files, because I get a

cat: dist/{polyfills-es5,main-es5}.js: No such file or directory

I'm not sure why this is happening, but I am in the correct directory when I call npm run bundle. dist/ and package.json are in the same directory.
If I directly copy the line cat: dist/{polyfills-es5,main-es5}.js and paste it into the terminal, all the content of the files gets output to the terminal. It seems like npm run bundle isn't being executed from the same path.
What could my problem be?

A: Aha, looking further into it, it seems like cat {file1,file2}.js isn't working properly. It's actually trying to look for a file called {file1,file2}.js instead of counting how many files there actually are.
Solved by going with:
cat dist/polyfills-es5.js dist/main-es5.js > dist/element-es5.js && cat dist/polyfills-es2015.js dist/main-es2015.js > dist/element-es2015.js


text:
Q: PHP/MySQL - Random semicolon output I have this script to output everything from table called Articles.
If I load this script there are random semicolons coming at front of my table like this ; ;
This is my code:
    if($_SESSION['rights'] == 2){
    include_once "scripts/mysql123.php";

    //menu
    echo "Pridať nový článok

";

    //Connect to MySQL Server
    mysql_connect($dbhost, $dbuser, $dbpass);

    //Select Database
    mysql_select_db($dbname);

    //display all users
    echo "
";
    echo "
";
        echo "
            Id
            Názov článku
            Vytvorené
            Upraviť
            Vymazať
        \n";
        echo "
\n";
    $qry_result = mysql_query("SELECT * FROM `Articles`") or die(mysql_error());
    while($qry = mysql_fetch_array( $qry_result )){
        echo "
\n";
        echo "
            ".$qry[id]."
            ".$qry[articlename]."
            ".date("d.m.Y H:m:i",$qry[created])."
            	;
            	;
        \n";
        echo "
\n";
    }

    echo "
\n";

    //Close connection
    mysql_close(mysql_connect($dbhost, $dbuser, $dbpass));
}
else{
    echo "Musíte mať administrátorské práva.";
}

A: You are outputting them yourself as part of the long string literal, at the ends of these lines:
	;
	;

Just remove the semicolons there.


text:
Q: Simple Ajax Request to Laravel Not Working Trying simple return and display of user info using ajax with laravel backend. Using latest JQuery and Laravel and MySQL. Here's the simple route:
Route::get('users', function()
{
    $users = User::all();
    return $users;
});

This works fine when calling by url in browser.
Here's the simple ajax request:
$().ready(function() {
  $.ajax({
    url: "http://xx.xxx.xxx.xxx/users",
    type: "GET",
    cache: false,
    dataType: "jsonp",
    jsonpCallback: "JsonpCallback"
  })
  .done(function( data )
  {
    JsonpCallback( data );
  })
  .fail(function( jqXHR, textStatus, errorThrown )
  {
    alert( "Request failed: " + textStatus + "   /   " + errorThrown );
  });
  function JsonpCallback( json )
  {
    $( '#mainContent' ).html( json.result );
  }
  return false;
});

The user records are being returned in to the dom and I can see them via dev tools network response, but the .fail kicks every time and the callback is never called. The fail is:
Request failed: parsererror / Error: JasonpCallback was never called.

I have tried every solution I can find for a few days now and could really use help. It has to be something simple that I'm missing.

A:
jQuery is expecting a jsonp response, but return $users is returning plain json. Either switch dataType to json, or instead:
return Response::json($users)->setCallback(Input::get('callback'));

...from your route.
See the Laravel docs under creating a JSONP response.


text:
Q: If the double type can handle the numbers 4.35 and 435, why do 4.35 * 100 evaluates to 434.99999999999994? As I understand this, some numbers can't be represented with exactitude in binary, and that's why floating-point arithmetic sometimes gives us unexpected results; like 4.35 * 100 = 434.99999999999994. Something similar to what happens with 1/3 in decimal.
That makes sense, but this induces another question. Seems that in binary both 4.35 and 435 can be represented with exactitude. That's when it stops making sense to me. Why does 4.35 * 100 evaluates to 434.99999999999994? 435 and 4.35 have an exact representation in the double type dynamics:
double number1 = 4.35;
double number2 = 435;
double number3 = 100;
System.out.println(number1); // 4.35
System.out.println(number2); // 435.0
System.out.println(number3); // 100.0
// So far so good. Everything ok.

System.out.println(number1 * number3); // 434.99999999999994 !!!
// But 4.35 * 100 evaluates to 434.99999999999994

Why?
Edit: this question was marked as duplicate, and it is not. As you can see in the accepted answer, my confusion was regarding the discrepancy between the actual value and the printed value.

A: You are right in that sometimes floating-point arithmetic gives unexpected results.
Your assertion that 4.35 can be represented exactly in floating-point is incorrect, because it can't be represented as a terminating binary decimal.  100 can obviously be represented exactly, so for the result to be 434.99999999999994, `4.35 must not be represented exactly.
To be represented exactly in floating-point, a number must be able to be converted to a fraction where the denominator is a power of two only (and it must not be so precise that it exceeds the maximum precision of the floating-point type you're using).  In this case, 4.35 is 4 7/20, and the denominator has a factor of 5, so the number can't be represented exactly in binary.

A:
Seems that in binary both 4.35 and 435 can be represented with exactitude.

I see that you understand how the floating point numbers are internally represented. As for your doubt, no 4.35 does not have an exact binary representation. So the issue is, why the 1st print statement prints 4.35.
That is happening because System.out.println() invokes the Double.toString(double) method, which in turns uses FloatingDecimal#toJavaFormatString() method, which performs some rounding internally on the passed double argument. You can go through the source code I linked.
For seeing the actual value of 4.35, try using this:
BigDecimal bd = new BigDecimal(number1);
System.out.println(bd);

This will print:
4.3499999999999996447286321199499070644378662109375

In this case, rather than printing the double value, you create a BigDecimal object passing double value as argument. BigDecimal represents arbitrary precision signed decimal number. So it gives you the exact value of 4.35.

A: Although from a hardware perspective each floating-point number represents some exact value of the form M * 2^E (where M and E are integers in a certain range), from a software perspective it is more helpful to think of each floating-point number as representing "Something for which M * 2^E has been deemed the best representation, and which is hopefully close to that".  Given a floating-point value (M * 2^E), one should figure that the actual number it's intended to represent may very easily be anywhere from (N - 1/2) * 2^E to (N + 1/2) * 2^E and in practice may extend a bit further beyond.
As a simple example, with type float, the value of M is limited to the range 0-16777215.  The best representation of 2000000.1f is thus 16000001 * 2^-3 [i.e. 16000001/8].  Although exact decimal value of 16000001/8 is 2000000.125, the last digit isn't necessary to define the value of the number, since 16000001/8 would the best representation of 2000000.120 and 2000000.129 (or, for that matter, all values between 2000000.0625 and 2000000.1875, non-inclusive).  Because the number of digits that would required to display the exact decimal value of a number of the form M * 2^E would often far exceed the number of meaningful digits, it is common to limit number of displayed digits to roughly those necessary to uniquely define the value.
Note that if one regards floating-point numbers as representing ranges, one will observe that casts from double to float--even though they must be explicitly specified--are actually safe since converting the double that best represents a particular value to float will yield either the best float representation of that value or something very close to it.  Conversely, conversion from float to double, even though it's allowed implicitly, is dangerous because such conversion is very unlikely to select the double which would best represent the number that the float was supposed to represent.

A: it is a bit hard to explain in English, because I have learned computer number representation in Hungarian. In short, 4.35, 435 nor 100 is not exactly these numbers, but mantissa * 2^k (k-characteristic from -k to +k, and t - is the length of the mantissa in the M = (t,-k,+k) ) although the print call does some rounding. So the number-line is not continuous, but near some famous points, denser ).

So as I think these numbers are not exactly what you expect, and after the operation (I suppose this is one or two simple binary operation) you get the multiple of error distance of the two float point number representation.


text:
Q: Reclassifying a DEM using ArcMap 10.1 I have a DEM that am reclassifying into two classes. One areas less than or equal to 1000 and the other areas greater than 1000.
Am accomplishing this using the reclassify Tool in ArcMap 10.1.
The results are a range that I don't understand,what could be the problem
The reclassify tool

A: Try splitting your raster into smaller parts. It seems to be really big.
I just found this post: http://forums.esri.com/Thread.asp?c=93&f=995&t=225045, someone had a similar problem as you:

Quote from link above: Any count exceeding 2^31-1 will therefore "roll over" into the most
  negative numbers; for instance, (2^31-1) + 1 will appear as -2^31. For
  some analyses this may make no difference provided the original count
  is less than 2^32, but for many analyses you will get incorrect
  results.

As your count of raster cells is negative, I suspect the size of the raster (and therefore the number of pixels) to cause the problem.


text:
Q: ggplot discrepancy between faceted and individual plots I think there is a discrepancy between the faceted plots and the individual plot.
Pay attention to mouse number 9214 in these plots:
# Make the faceted graph
fig1 = ggplot(raw, aes(raw$Bregma.)) + geom_density() + ggtitle("Fig. 1. Bregma Representation, by mouse (red = post-ex, green = post-rev)") +
  geom_density(data = raw_excluded, aes(raw_excluded$Bregma.), color = "red") +
  geom_density(data = raw_revised, aes(raw_revised$Bregma.), color = "green")+ facet_wrap(~Mouse.ID.)

fig1

When I run the individual ggplot for that data, it looks like this, which is NOT what it looks like in the faceted image:
temp_indiv_plot = function(x) {
  temp_mouse = x
  temp_mouse_original = filter(raw, raw$Mouse.ID == temp_mouse)
  temp_mouse_revised = filter(raw_revised, raw_revised$Mouse.ID. == temp_mouse)

  ggplot(temp_mouse_original, aes(x = temp_mouse_original$Bregma.)) + geom_density() +
    geom_density(data = temp_mouse_revised, aes(temp_mouse_revised$Bregma.), color = "green") +
    ggtitle(temp_mouse)
}

temp_indiv_plot("8350")
temp_indiv_plot("9214")

But I plotted another mouse (8350) to see if it was consistent, but it looks identical to the faceted graph (can't add more than 3 links until I have enough reputation, you'll have to take my word for it now).
So why is mouse 9214 different?


text:
Q: How to import a file from another folder in a package My project structure looks like this
pythonProject
|
|-__init__.py
|
|- a
|  |- file_a.py
|  |-__init__.py
|
|- b
   |- file_b.py
   |-__init__.py

I've also attached the image of my project's structure below.
enter image description here
My file_a.py looks like:
class class_a:
    def __init__(self):
        pass
    def show(self):
        print('class A')

if __name__ == "__main__":
    pass

My file_b.py looks like:
from pythonProject.a.file_a import class_a

class class_b:
    def __init__(self):
        pass

    def show(self):
        a = class_a()
        a.show()

if __name__ == "__main__":
    b = class_b()

But I keep getting an error  No module named 'pythonProject'. All the folders do have __init__.py file.  What am I doing wrong?
On the terminal, I run the command python b/file_b.py from inside the pythonProject.
Also, I would not like to add project path using sys library.
Thanks.
Things I've tried.

*

*I added all the __init__.py file in all the folders. But all of them are empty. Should they have any specific references?

*I tried the import line to ..a.file_a import class_a. Then I get the error: ImportError: attempted relative import with no known parent package

*I tried the import line to a.file_a import class_a but then the error is ModuleNotFoundError: No module named 'a'.

A: I think the problem appears to be with your if __name__ == "main" condition in files a.py and b.py. Instead of "main", the correct string is "__main__" (double underscores on each side)
Change the condition in both files to if __name__ == "__main__": and try running file b.py again. This should resolve the error

No module named 'pythonProject'.

In terms of imports, you can import class a from file a.py using the absolute import syntax in file b.py
from pythonProject.a.file_a import class_a
As long as you run file b.py from within the pythonProject directory, this should work.


text:
Q: How do I serve up a directory list from web.py I've written a little app in web.py and it works fine. It also delivers some images that are generated and dumped into a folder inside the static dir.
I also want to be able to show the list of files and folders inside static. How do I enable listview?

A: Typically you don't quite "enable" it. But there are a couple of choices you have.
1) Integrate it into your favorite webserver as a module. Here is how to run it as a FastCGI in lighttpd. There are also options for integrating with Apache.
see webpy.org for more info
server.modules   += ( "mod_fastcgi" )
server.modules   += ( "mod_rewrite" )

fastcgi.server = ( "/code.py" =>
(( "socket" => "/tmp/fastcgi.socket",
  "bin-path" => "/path-to/webpy-app/code.py",
  "max-procs" => 1,
 "bin-environment" => (
   "REAL_SCRIPT_NAME" => ""
 ),
 "check-local" => "disable"
))
)

url.rewrite-once = (
 "^/favicon.ico$" => "/static/favicon.ico",
 "^/static/(.*)$" => "/static/$1",
 "^/(.*)$" => "/code.py/$1",
)

2) Or write code in your python app to handle it.
class list:
  def GET(self,irl):
    thisfile = inspect.getfile(inspect.currentframe())
    thispath = os.path.dirname(os.path.abspath(thisfile))
    dir = os.listdir("%s/static/%s"%(thispath,irl))
    rel = irl
    files = []
    folds = []
    for item in dir:
      if os.path.isfile("%s/static/%s/%s"%(thispath,irl,item)):
        files.append(item)
      elif item!='res':
        folds.append(item)
    return render.list(rel,folds,files)

...and in the template...
$def with (rel,folds,files)
...
$if len(folds)>0:
  $for fold in folds:
    $fold
...
$if len(files)>0:
  $for file in files:
    $file