Programs & Examples On #Delay

Delay refers to amount of time between two events.

Delaying function in swift

You can use GCD (in the example with a 10 second delay):

Swift 2

let triggerTime = (Int64(NSEC_PER_SEC) * 10)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
    self.functionToCall()
})

Swift 3 and Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
    self.functionToCall()
})

Swift 5 or Later

 DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
        //call any function
    }

How can I use delay() with show() and hide() in Jquery

Why don't you try the fadeIn() instead of using a show() with delay(). I think what you are trying to do can be done with this. Here is the jQuery code for fadeIn and FadeOut() which also has inbuilt method for delaying the process.

$(document).ready(function(){
   $('element').click(function(){
      //effects take place in 3000ms
      $('element_to_hide').fadeOut(3000);
      $('element_to_show').fadeIn(3000);
   });
}

jQuery: Can I call delay() between addClass() and such?

You can create a new queue item to do your removing of the class:

$("#div").addClass("error").delay(1000).queue(function(next){
    $(this).removeClass("error");
    next();
});

Or using the dequeue method:

$("#div").addClass("error").delay(1000).queue(function(){
    $(this).removeClass("error").dequeue();
});

The reason you need to call next or dequeue is to let jQuery know that you are done with this queued item and that it should move on to the next one.

While variable is not defined - wait

Shorter way:

   var queue = function (args){
      typeof variableToCheck !== "undefined"? doSomething(args) : setTimeout(function () {queue(args)}, 2000);
};

You can also pass arguments

Adding delay between execution of two following lines

If you're targeting iOS 4.0+, you can do the following:

[executing first operation];
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    [executing second operation];
});

Delayed function calls

There is no standard way to delay a call to a function other than to use a timer and events.

This sounds like the GUI anti pattern of delaying a call to a method so that you can be sure the form has finished laying out. Not a good idea.

implement time delay in c

you can simply call delay() function. So if you want to delay the process in 3 seconds, call delay(3000)...

How can I perform a short delay in C# without using sleep?

If you're using .NET 4.5 you can use the new async/await framework to sleep without locking the thread.

How it works is that you mark the function in need of asynchronous operations, with the async keyword. This is just a hint to the compiler. Then you use the await keyword on the line where you want your code to run asynchronously and your program will wait without locking the thread or the UI. The method you call (on the await line) has to be marked with an async keyword as well and is usually named ending with Async, as in ImportFilesAsync.

What you need to do in your example is:

  1. Make sure your program has .Net Framework 4.5 as Target Framework
  2. Mark your function that needs to sleep with the async keyword (see example below)
  3. Add using System.Threading.Tasks; to your code.

Your code is now ready to use the Task.Delay method instead of the System.Threading.Thread.Sleep method (it is possible to use await on Task.Delay because Task.Delay is marked with async in its definition).

private async void button1_Click(object sender, EventArgs e)
{
    textBox1.Text += "\r\nThread Sleeps!";
    await Task.Delay(3000);
    textBox1.Text += "\r\nThread awakens!";
}

Here you can read more about Task.Delay and Await.

How to create a delay in Swift?

If you need to set a delay of less than a second, it is not necessary to set the .seconds parameter. I hope this is useful to someone.

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
        // your code hear
})

Xcode Objective-C | iOS: delay function / NSTimer help?

Try

NSDate *future = [NSDate dateWithTimeIntervalSinceNow: 0.06 ];
[NSThread sleepUntilDate:future];

How to put a delay on AngularJS instant search?

Another solution is to add a delay functionality to model update. The simple directive seems to do a trick:

app.directive('delayedModel', function() {
    return {
        scope: {
            model: '=delayedModel'
        },
        link: function(scope, element, attrs) {

            element.val(scope.model);

            scope.$watch('model', function(newVal, oldVal) {
                if (newVal !== oldVal) {
                    element.val(scope.model);        
                }
            });

            var timeout;
            element.on('keyup paste search', function() {
                clearTimeout(timeout);
                timeout = setTimeout(function() {
                    scope.model = element[0].value;
                    element.val(scope.model);
                    scope.$apply();
                }, attrs.delay || 500);
            });
        }
    };
});

Usage:

<input delayed-model="searchText" data-delay="500" id="searchText" type="search" placeholder="live search..." />

So you just use delayed-model in place of ng-model and define desired data-delay.

Demo: http://plnkr.co/edit/OmB4C3jtUD2Wjq5kzTSU?p=preview

How can I make a time delay in Python?

import time
time.sleep(5)   # Delays for 5 seconds. You can also use a float value.

Here is another example where something is run approximately once a minute:

import time
while True:
    print("This prints once a minute.")
    time.sleep(60) # Delay for 1 minute (60 seconds).

How to make java delay for a few seconds?

move the System.out statement to finally block.

How to create javascript delay function

Ah yes. Welcome to Asynchronous execution.

Basically, pausing a script would cause the browser and page to become unresponsive for 3 seconds. This is horrible for web apps, and so isn't supported.

Instead, you have to think "event-based". Use setTimeout to call a function after a certain amount of time, which will continue to run the JavaScript on the page during that time.

Proper way to wait for one function to finish before continuing?

The only issue with promises is that IE doesn't support them. Edge does, but there's plenty of IE 10 and 11 out there: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise (compatibility at the bottom)

So, JavaScript is single-threaded. If you're not making an asynchronous call, it will behave predictably. The main JavaScript thread will execute one function completely before executing the next one, in the order they appear in the code. Guaranteeing order for synchronous functions is trivial - each function will execute completely in the order it was called.

Think of the synchronous function as an atomic unit of work. The main JavaScript thread will execute it fully, in the order the statements appear in the code.

But, throw in the asynchronous call, as in the following situation:

showLoadingDiv(); // function 1

makeAjaxCall(); // function 2 - contains async ajax call

hideLoadingDiv(); // function 3

This doesn't do what you want. It instantaneously executes function 1, function 2, and function 3. Loading div flashes and it's gone, while the ajax call is not nearly complete, even though makeAjaxCall() has returned. THE COMPLICATION is that makeAjaxCall() has broken its work up into chunks which are advanced little by little by each spin of the main JavaScript thread - it's behaving asychronously. But that same main thread, during one spin/run, executed the synchronous portions quickly and predictably.

So, the way I handled it: Like I said the function is the atomic unit of work. I combined the code of function 1 and 2 - I put the code of function 1 in function 2, before the asynch call. I got rid of function 1. Everything up to and including the asynchronous call executes predictably, in order.

THEN, when the asynchronous call completes, after several spins of the main JavaScript thread, have it call function 3. This guarantees the order. For example, with ajax, the onreadystatechange event handler is called multiple times. When it reports it's completed, then call the final function you want.

I agree it's messier. I like having code be symmetric, I like having functions do one thing (or close to it), and I don't like having the ajax call in any way be responsible for the display (creating a dependency on the caller). BUT, with an asynchronous call embedded in a synchronous function, compromises have to be made in order to guarantee order of execution. And I have to code for IE 10 so no promises.

Summary: For synchronous calls, guaranteeing order is trivial. Each function executes fully in the order it was called. For a function with an asynchronous call, the only way to guarantee order is to monitor when the async call completes, and call the third function when that state is detected.

For a discussion of JavaScript threads, see: https://medium.com/@francesco_rizzi/javascript-main-thread-dissected-43c85fce7e23 and https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

Also, another similar, highly rated question on this subject: How should I call 3 functions in order to execute them one after the other?

How to add a delay for a 2 or 3 seconds

Use a timer with an interval set to 2–3 seconds.

You have three different options to choose from, depending on which type of application you're writing:

  1. System.Timers.Timer
  2. System.Windows.Forms.Timer
  3. System.Threading.Timer

Don't use Thread.Sleep if your application need to process any inputs on that thread at the same time (WinForms, WPF), as Sleep will completely lock up the thread and prevent it from processing other messages. Assuming a single-threaded application (as most are), your entire application will stop responding, rather than just delaying an operation as you probably intended. Note that it may be fine to use Sleep in pure console application as there are no "events" to handle or on separate thread (also Task.Delay is better option).

In addition to timers and Sleep you can use Task.Delay which is asynchronous version of Sleep that does not block thread from processing events (if used properly - don't turn it into infinite sleep with .Wait()).

 public async void ClickHandler(...)
 {
      // whatever you need to do before delay goes here         

      await Task.Delay(2000);

      // whatever you need to do after delay.
 }

The same await Task.Delay(2000) can be used in a Main method of a console application if you use C# 7.1 (Async main on MSDN blogs).

Note: delaying operation with Sleep has benefit of avoiding race conditions that comes from potentially starting multiple operations with timers/Delay. Unfortunately freezing UI-based application is not acceptable so you need to think about what will happen if you start multiple delays (i.e. if it is triggered by a button click) - consider disabling such button, or canceling the timer/task or making sure delayed operation can be done multiple times safely.

How can I delay a :hover effect in CSS?

You can use transitions to delay the :hover effect you want, if the effect is CSS-based.

For example

div{
    transition: 0s background-color;
}

div:hover{
    background-color:red;    
    transition-delay:1s;
}

this will delay applying the the hover effects (background-color in this case) for one second.


Demo of delay on both hover on and off:

_x000D_
_x000D_
div{_x000D_
    display:inline-block;_x000D_
    padding:5px;_x000D_
    margin:10px;_x000D_
    border:1px solid #ccc;_x000D_
    transition: 0s background-color;_x000D_
    transition-delay:1s;_x000D_
}_x000D_
div:hover{_x000D_
    background-color:red;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
_x000D_
_x000D_

Demo of delay only on hover on:

_x000D_
_x000D_
div{_x000D_
    display:inline-block;_x000D_
    padding:5px;_x000D_
    margin:10px;_x000D_
    border:1px solid #ccc;_x000D_
    transition: 0s background-color;_x000D_
}_x000D_
div:hover{_x000D_
    background-color:red;    _x000D_
    transition-delay:1s;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
_x000D_
_x000D_


Vendor Specific Extentions for Transitions and W3C CSS3 transitions

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

How to call a method after a delay in Android

Kotlin & Java Many Ways

1. Using Handler

Handler().postDelayed({
    TODO("Do something")
    }, 2000)

2. Using TimerTask

Timer().schedule(object : TimerTask() {
    override fun run() {
        TODO("Do something")
    }
}, 2000)

Or even shorter

Timer().schedule(timerTask {
    TODO("Do something")
}, 2000)

Or shortest would be

Timer().schedule(2000) {
    TODO("Do something")
}

3. Using Executors

Executors.newSingleThreadScheduledExecutor().schedule({
    TODO("Do something")
}, 2, TimeUnit.SECONDS)

In Java

1. Using Handler

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        //Do something
    }
}, 2000);

2. Using Timer

new Timer().schedule(new TimerTask() {          
    @Override
    public void run() {
        // Do something
    }
}, 2000);

3. Using ScheduledExecutorService

private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();

Runnable runnable = new Runnable() {
  public void run() {
      // Do something
  }
  };
worker.schedule(runnable, 2, TimeUnit.SECONDS);

jQuery: Wait/Delay 1 second without executing code

ES6 setTimeout

setTimeout(() => {
  console.log("we waited 204586560000 ms to run this code, oh boy wowwoowee!");
}, 204586560000);

Edit: 204586560000 ms is the approximate time between the original question and this answer... assuming I calculated correctly.

Javascript sleep/delay/wait function

You could use the following code, it does a recursive call into the function in order to properly wait for the desired time.

function exportar(page,miliseconds,totalpages)
{
    if (page <= totalpages)
    {
        nextpage = page + 1;
        console.log('fnExcelReport('+ page +'); nextpage = '+ nextpage + '; miliseconds = '+ miliseconds + '; totalpages = '+ totalpages );
        fnExcelReport(page);
        setTimeout(function(){
            exportar(nextpage,miliseconds,totalpages);
        },miliseconds);
    };
}

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

There's a huge difference. As has been mentioned, <%@ include is a static include, <jsp:include is a dynamic include. Think of it as a difference between a macro and a function call (if you are familiar with those terms). Another way of putting it, a static include is exactly the same thing as copy-pasting the exact content of the included file (the "code") at the location of the <%@ include statement (which is exactly what the JSP compiler will do.

A dynamic include will make a request (using the request dispatcher) that will execute the indicated page and then include the output from the page in the output of the calling page, in place of the <jsp:include statement.

The big difference here is that with a dynamic include, the included page will execute in it's own pageContext. And since it's a request, you can send parameters to the page the same way you can send parameters along with any other request. A static include, on the other hand, is just a piece of code that will execute inside the context of the calling page. If you statically include the same file more than once, the code in that file will exist in multiple locations on the calling page so something like

<%
int i = 0;
%>

would generate a compiler error (since the same variable can't be declared more than once).

Android: Color To Int conversion

R.color.black or some color are obviously integers. It needs a RGB value. You can give your own like #FF123454 which represents various primary colors

can't access mysql from command line mac

adding this code to my .profile worked for me: :/usr/local/mysql/bin

Thanks.

P.S This .profile is located in your user/ path. Its a hidden file so you will have to get to it either by a command in Terminal or using an html editor.

Git fails when pushing commit to github

I had the same issue and believe that it has to do with the size of the repo (edited- or the size of a particular file) you are trying to push.

Basically I was able to create new repos and push them to github. But an existing one would not work.

The HTTP error code seems to back me up it is a 'Length Required' error. So maybe it is too large to calc or greated that the max. Who knows.

EDIT

I found that the problem may be files that are large. I had one update that would not push even though I had successful pushes up to that point. There was only one file in the commit but it happened to be 1.6M

So I added the following config change

git config http.postBuffer 524288000

To allow up to the file size 500M and then my push worked. It may have been that this was the problem initially with pushing a big repo over the http protocol.

END EDIT

the way I could get it to work (EDIT before I modified postBuffer) was to tar up my repo, copy it to a machine that can do git over ssh, and push it to github. Then when you try to do a push/pull from the original server it should work over https. (since it is a much smaller amount of data than an original push).

Node.js global proxy setting

I finally created a module to get this question (partially) resolved. Basically this module rewrites http.request function, added the proxy setting then fire. Check my blog post: https://web.archive.org/web/20160110023732/http://blog.shaunxu.me:80/archive/2013/09/05/semi-global-proxy-setting-for-node.js.aspx

Get HTML code using JavaScript with a URL

For an external (cross-site) solution, you can use: Get contents of a link tag with JavaScript - not CSS

It uses $.ajax() function, so it includes jquery.

Delete directory with files in it?

As seen in most voted comment on PHP manual page about rmdir() (see http://php.net/manual/es/function.rmdir.php), glob() function does not return hidden files. scandir() is provided as an alternative that solves that issue.

Algorithm described there (which worked like a charm in my case) is:

<?php 
    function delTree($dir)
    { 
        $files = array_diff(scandir($dir), array('.', '..')); 

        foreach ($files as $file) { 
            (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file"); 
        }

        return rmdir($dir); 
    } 
?>

How to get numbers after decimal point?

5.55 % 1

Keep in mind this won't help you with floating point rounding problems. I.e., you may get:

0.550000000001

Or otherwise a little off the 0.55 you are expecting.

How to group by week in MySQL?

You can get the concatenated year and week number (200945) using the YEARWEEK() function. If I understand your goal correctly, that should enable you to group your multi-year data.

If you need the actual timestamp for the start of the week, it's less nice:

DATE_SUB( field, INTERVAL DAYOFWEEK( field ) - 1 DAY )

For monthly ordering, you might consider the LAST_DAY() function - sort would be by last day of the month, but that should be equivalent to sorting by first day of the month ... shouldn't it?

Hive query output to file

This command will redirect the output to a text file of your choice:

$hive -e "select * from table where id > 10" > ~/sample_output.txt

How to run mvim (MacVim) from Terminal?

If you already have macVim installed: /Applications/MacVim.app/Contents/MacOS/Vim -g will give you macVim GUI.

just add an alias.

i use gvim because that is what i use on linux for gnome-vim.

alias gvim='/Applications/MacVim.app/Contents/MacOS/Vim -g'

Update a column in MySQL

if you want to fill all the column:

update 'column' set 'info' where keyID!=0;

C# nullable string error

string cannot be the parameter to Nullable because string is not a value type. String is a reference type.

string s = null; 

is a very valid statement and there is not need to make it nullable.

private string typeOfContract
    {
      get { return ViewState["typeOfContract"] as string; }
      set { ViewState["typeOfContract"] = value; }
    }

should work because of the as keyword.

Emulator in Android Studio doesn't start

If you're getting

Failed on eglChooseConfig
Could not initialize emulated framebuffer

See this answer. You may not be in 32-bit color mode, which will cause android GPU emulation to fail.

https://stackoverflow.com/a/48529994/290072

How to test android apps in a real device with Android Studio?

Step 1: Firstly, Go to the Settings in your real device whose device are used to run android app.

Step 2: After that go to the “About phone” if Developer Options is not shown in your device

Step 3: Then Tap 7 times on Build number to create Developer Options.

Step 4: After that go back and Developer options will be created in your device.

Step 5: After that go to Developer options and Enable USB debugging in your device as shown in figure below.

Step 6: Connect your device with your system via data cable and after that allow USB debugging message shown on your device and press OK.

Step 7: After that Go to the menu bar and Run app as shown in figure below.

Step 8: If real device is connected to your system then it will show Online. Now click on your Mobile phone device and you App will be run in real device.

Step 9: After that your Android app run in Real device.

Regards, Guruji Softwares (https://gurujisoftwares.com)

functional way to iterate over range (ES6/7)

Here's an approach using generators:

function* square(n) {
    for (var i = 0; i < n; i++ ) yield i*i;
}

Then you can write

console.log(...square(7));

Another idea is:

[...Array(5)].map((_, i) => i*i)

Array(5) creates an unfilled five-element array. That's how Array works when given a single argument. We use the spread operator to create an array with five undefined elements. That we can then map. See http://ariya.ofilabs.com/2013/07/sequences-using-javascript-array.html.

Alternatively, we could write

Array.from(Array(5)).map((_, i) => i*i)

or, we could take advantage of the second argument to Array#from to skip the map and write

Array.from(Array(5), (_, i) => i*i)

A horrible hack which I saw recently, which I do not recommend you use, is

[...1e4+''].map((_, i) => i*i)

How can I read SMS messages from the device programmatically in Android?

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        final String myPackageName = getPackageName();
        if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {

            Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
            intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, myPackageName);
            startActivityForResult(intent, 1);
        }else {
            List<Sms> lst = getAllSms();
        }
    }else {
        List<Sms> lst = getAllSms();
    }

Set app as default SMS app

    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
    if (resultCode == RESULT_OK) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            final String myPackageName = getPackageName();
            if (Telephony.Sms.getDefaultSmsPackage(mActivity).equals(myPackageName)) {

                List<Sms> lst = getAllSms();
            }
        }
    }
}
}

Function to get SMS

public List<Sms> getAllSms() {
    List<Sms> lstSms = new ArrayList<Sms>();
    Sms objSms = new Sms();
    Uri message = Uri.parse("content://sms/");
    ContentResolver cr = mActivity.getContentResolver();

    Cursor c = cr.query(message, null, null, null, null);
    mActivity.startManagingCursor(c);
    int totalSMS = c.getCount();

    if (c.moveToFirst()) {
        for (int i = 0; i < totalSMS; i++) {

            objSms = new Sms();
            objSms.setId(c.getString(c.getColumnIndexOrThrow("_id")));
            objSms.setAddress(c.getString(c
                    .getColumnIndexOrThrow("address")));
            objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
            objSms.setReadState(c.getString(c.getColumnIndex("read")));
            objSms.setTime(c.getString(c.getColumnIndexOrThrow("date")));
            if (c.getString(c.getColumnIndexOrThrow("type")).contains("1")) {
                objSms.setFolderName("inbox");
            } else {
                objSms.setFolderName("sent");
            }

            lstSms.add(objSms);
            c.moveToNext();
        }
    }
    // else {
    // throw new RuntimeException("You have no SMS");
    // }
    c.close();

    return lstSms;
}

Sms class is below:

public class Sms{
private String _id;
private String _address;
private String _msg;
private String _readState; //"0" for have not read sms and "1" for have read sms
private String _time;
private String _folderName;

public String getId(){
return _id;
}
public String getAddress(){
return _address;
}
public String getMsg(){
return _msg;
}
public String getReadState(){
return _readState;
}
public String getTime(){
return _time;
}
public String getFolderName(){
return _folderName;
}


public void setId(String id){
_id = id;
}
public void setAddress(String address){
_address = address;
}
public void setMsg(String msg){
_msg = msg;
}
public void setReadState(String readState){
_readState = readState;
}
public void setTime(String time){
_time = time;
}
public void setFolderName(String folderName){
_folderName = folderName;
}

}

Don't forget to define permission in your AndroidManifest.xml

<uses-permission android:name="android.permission.READ_SMS" />

Get a particular cell value from HTML table using JavaScript

To get the text from this cell-

<table>
    <tr id="somerow">
        <td>some text</td>            
    </tr>
</table>

You can use this -

var Row = document.getElementById("somerow");
var Cells = Row.getElementsByTagName("td");
alert(Cells[0].innerText);

PHP Notice: Undefined offset: 1 with array when reading data

How to reproduce the above error in PHP:

php> $yarr = array(3 => 'c', 4 => 'd');

php> echo $yarr[4];
d

php> echo $yarr[1];
PHP Notice:  Undefined offset: 1 in 
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) : 
eval()'d code on line 1

What does that error message mean?

It means the php compiler looked for the key 1 and ran the hash against it and didn't find any value associated with it then said Undefined offset: 1

How do I make that error go away?

Ask the array if the key exists before returning its value like this:

php> echo array_key_exists(1, $yarr);

php> echo array_key_exists(4, $yarr);
1

If the array does not contain your key, don't ask for its value. Although this solution makes double-work for your program to "check if it's there" and then "go get it".

Alternative solution that's faster:

If getting a missing key is an exceptional circumstance caused by an error, it's faster to just get the value (as in echo $yarr[1];), and catch that offset error and handle it like this: https://stackoverflow.com/a/5373824/445131

How to symbolicate crash log Xcode?

Writing this answer as much for the community as for myself.

If there ever are problems symbolicating a crash report, one can overcome them as follows:

  1. Create a separate folder, copy Foo.app and Foo.app.dSYM from the corresponding .xcarchive into the folder. Also copy the .crash report into the folder.

  2. Open the crash report in TextEdit or elsewhere, go to the Binary Images: section, and copy the first address there (e.g. 0xd7000).

  3. cd into the folder. Now you can run the following command:

    xcrun atos -o Foo.app/Foo -arch arm64 -l 0xd7000 0x0033f9bb

This will symbolicate the symbol at address 0x0033f9bb. Please make sure to pick the correct value for the -arch option (can be obtaned from the first line in the Binary Images: section, or figured out from the Hardware Model: in the crash report and the app's supported archs).

You can also copy the necessary addresses (e.g. a thread call stack) from the crash report directly into a text file (in TextEdit, hold Option and select the necessary text block, or copy and cut), to get something like this:

0x000f12fb
0x002726b7
0x0026d415
0x001f933b
0x001f86d3

Now you can save this into a text file, e.g. addr.txt, and run the following command:

xcrun atos -o Foo.app/Foo -arch arm64 -l 0xd7000 -f addr.txt

This will give a nice symbolication for all the addresses at once.

P.S.

Before doing the above, it's worth checking that everything is set up correctly (as atos will happily report something for basically any supplied address).

To do the checking, open the crash report, and go to the end of the call stack for Thread 0. The first line from the end to list your app (usually the second one), e.g.:

34  Foo                    0x0033f9bb 0xd7000 + 2525627

should be the main() call. Symbolicating the address (0x0033f9bb in this case) as described above should confirm that this is indeed main() and not some random method or function.

If the address is not that of main(), check your load address (-l option) and arch (-arch option).

P.P.S.

If the above doesn't work due to bitcode, download the dSYM for your build from iTunes Connect, extract the executable binary from the dSYM (Finder > Show Package Contents), copy it into the directory, and use it (i.e. Foo) as the argument to atos, instead of the Foo.app/Foo.

Oracle query execution time

select LAST_LOAD_TIME, ELAPSED_TIME, MODULE, SQL_TEXT elapsed from v$sql
  order by LAST_LOAD_TIME desc

More complicated example (don't forget to delete or to substitute PATTERN):

select * from (
  select LAST_LOAD_TIME, to_char(ELAPSED_TIME/1000, '999,999,999.000') || ' ms' as TIME,
         MODULE, SQL_TEXT from SYS."V_\$SQL"
    where SQL_TEXT like '%PATTERN%'
    order by LAST_LOAD_TIME desc
  ) where ROWNUM <= 5;

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

What is happening here is that database route does not accept any url methods.

I would try putting the url methods in the app route just like you have in the entry_page function:

@app.route('/entry', methods=['GET', 'POST'])
def entry_page():
    if request.method == 'POST':
        date = request.form['date']
        title = request.form['blog_title']
        post = request.form['blog_main']
        post_entry = models.BlogPost(date = date, title = title, post = post)
        db.session.add(post_entry)
        db.session.commit()
        return redirect(url_for('database'))
    else:
        return render_template('entry.html')

@app.route('/database', methods=['GET', 'POST'])        
def database():
    query = []
    for i in session.query(models.BlogPost):
        query.append((i.title, i.post, i.date))
    return render_template('database.html', query = query)

Call child method from parent

You can achieve this easily in this way

Steps-

  1. Create a boolean variable in the state in the parent class. Update this when you want to call a function.
  2. Create a prop variable and assign the boolean variable.
  3. From the child component access that variable using props and execute the method you want by having an if condition.

    class Child extends Component {
       Method=()=>{
       --Your method body--
       }
       render() {
         return (
        //check whether the variable has been updated or not
          if(this.props.updateMethod){
            this.Method();
          }
         )
       }
    }
    
    class Parent extends Component {
    
    constructor(){
      this.state={
       callMethod:false
      }
    
    }
    render() {
       return (
    
         //update state according to your requirement
         this.setState({
            callMethod:true
         }}
         <Child updateMethod={this.state.callMethod}></Child>
        );
       }
    }
    

How using try catch for exception handling is best practice

The catch without any arguments is simply eating the exception and is of no use. What if a fatal error occurs? There's no way to know what happened if you use catch without argument.

A catch statement should catch more specific Exceptions like FileNotFoundException and then at the very end you should catch Exception which would catch any other exception and log them.

Use "ENTER" key on softkeyboard instead of clicking button

We can also use Kotlin lambda

editText.setOnKeyListener { _, keyCode, keyEvent ->
        if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
            Log.d("Android view component", "Enter button was pressed")
            return@setOnKeyListener true
        }
        return@setOnKeyListener false
    }

Returning the product of a list

Without using lambda:

from operator import mul
reduce(mul, list, 1)

it is better and faster. With python 2.7.5

from operator import mul
import numpy as np
import numexpr as ne
# from functools import reduce # python3 compatibility

a = range(1, 101)
%timeit reduce(lambda x, y: x * y, a)   # (1)
%timeit reduce(mul, a)                  # (2)
%timeit np.prod(a)                      # (3)
%timeit ne.evaluate("prod(a)")          # (4)

In the following configuration:

a = range(1, 101)  # A
a = np.array(a)    # B
a = np.arange(1, 1e4, dtype=int) #C
a = np.arange(1, 1e5, dtype=float) #D

Results with python 2.7.5


       |     1     |     2     |     3     |     4     |
-------+-----------+-----------+-----------+-----------+
 A       20.8 µs     13.3 µs     22.6 µs     39.6 µs     
 B        106 µs     95.3 µs     5.92 µs     26.1 µs
 C       4.34 ms     3.51 ms     16.7 µs     38.9 µs
 D       46.6 ms     38.5 ms      180 µs      216 µs

Result: np.prod is the fastest one, if you use np.array as data structure (18x for small array, 250x for large array)

with python 3.3.2:


       |     1     |     2     |     3     |     4     |
-------+-----------+-----------+-----------+-----------+
 A       23.6 µs     12.3 µs     68.6 µs     84.9 µs     
 B        133 µs      107 µs     7.42 µs     27.5 µs
 C       4.79 ms     3.74 ms     18.6 µs     40.9 µs
 D       48.4 ms     36.8 ms      187 µs      214 µs

Is python 3 slower?

Soft Edges using CSS?

It depends on what type of fading you are looking for.

But with shadow and rounded corners you can get a nice result. Rounded corners because the bigger the shadow, the weirder it will look in the edges unless you balance it out with rounded corners.

http://jsfiddle.net/tLu7u/

also.. http://css3pie.com/

Return a value if no rows are found in Microsoft tSQL

You should avoid using expensive methods. You don't need any column for TBL2.

SELECT COUNT(*) FROM(
         SELECT TOP 1     1 AS CNT  FROM  TBL1 
         WHERE ColumnValue ='FooDoo') AS TBL2

Or this code:

IF EXISTS (SELECT TOP 1 1 FROM TABLE1 AS T1 
                          WHERE T1.ColumnValue='VooDoo') 
   SELECT 1 
ELSE 
   SELECT 0
 

Replace words in a string - Ruby

sentence.sub! 'Robert', 'Joe'

Won't cause an exception if the replaced word isn't in the sentence (the []= variant will).

How to replace all instances?

The above replaces only the first instance of "Robert".

To replace all instances use gsub/gsub! (ie. "global substitution"):

sentence.gsub! 'Robert', 'Joe'

The above will replace all instances of Robert with Joe.

Node package ( Grunt ) installed but not available

If you did have installed Grunt package by running npm install -g grunt and it still say's No command 'grunt' found or grunt: command not found, a quick and dirty way to get this working is linking node binaries to your $PATH manually.

On MacOSX/Linux you can add this line to your ~/.bash_profile or ~/.bashrc file.

PATH=$PATH:/usr/local/Cellar/node/HEAD/bin # Add NPM binaries

You probably should replace /usr/local/Cellar/node/HEAD/bin by the path where your node binaries could be found.

If this is quick and dirty to me, it's because everything should work without doing this, but for an unknown reason, a link seem broken. As nobody on IRC could tell me why this happened, I found my own way to make it (grunt) work.

PS: This should help you make grunt works, this answer is not jquery-ui related.

Update 02/2013 : You should take a look at @tom-p's answer which explains better what is going on. Tom gives us the real solution instead of hacking your bashrc file : both should work, but you should try installing grunt-cli first.

jQuery - Check if DOM element already exists

This question is about whether an element exists and all answers check if it doesn't exist :) Minor difference but worth mentioning.

Based on jQuery documentation the recommended way to check for existence is

if ($( "#myDiv" ).length) {
    // element exists
}

If you prefer to check for missing element you could use either:

if (!$( "#myDiv" ).length) {
    // element doesn't exist
}

or

if (0 === $( "#myDiv" ).length) {
    // element doesn't exist
}

Note please that in the second option I've used === which is slightly faster than == and put the 0 on the left as a Yoda condition.

addEventListener, "change" and option selection

You need a click listener which calls addActivityItem if less than 2 options exist:

var activities = document.getElementById("activitySelector");

activities.addEventListener("click", function() {
    var options = activities.querySelectorAll("option");
    var count = options.length;
    if(typeof(count) === "undefined" || count < 2)
    {
        addActivityItem();
    }
});

activities.addEventListener("change", function() {
    if(activities.value == "addNew")
    {
        addActivityItem();
    }
});

function addActivityItem() {
    // ... Code to add item here
}

A live demo is here on JSfiddle.

The model backing the 'ApplicationDbContext' context has changed since the database was created

This can happen when you change the data annotation of a model property. for example: adding [Required] to a property will cause a pending change in the database design.

The safest solution is to run on the Package Manager Console:

add-migration myMirgrationName

which will display the exact changes in the Up() method. Therefore, you can decide if you really want to apply such changes via the:

update-database

Otherwise, you may just delete the latest migration from the __MigrationHistory table and from the Migrations folder the Solution Explorer.

Android, How to read QR code in my application?

Use a QR library like ZXing... I had very good experience with it, QrDroid is much buggier. If you must rely on an external reader, rely on a standard one like Google Goggles!

Sort collection by multiple fields in Kotlin

Use sortedWith to sort a list with Comparator.

You can then construct a comparator using several ways:

  • compareBy, thenBy construct the comparator in a chain of calls:

    list.sortedWith(compareBy<Person> { it.age }.thenBy { it.name }.thenBy { it.address })
    
  • compareBy has an overload which takes multiple functions:

    list.sortedWith(compareBy({ it.age }, { it.name }, { it.address }))
    

CREATE DATABASE permission denied in database 'master' (EF code-first)

Permission denied is a security so you need to add a "User" permission..

  1. Right click you database(which is .mdf file) and then properties
  2. Go to security tab
  3. Click Continue button
  4. Click Add button
  5. Click Advance button
  6. Another window will show, then you click the "Find Now" button on the right side.
  7. On the fields below, go to the bottom most and click the "Users". Click OK.
  8. Click the permission "Users" that you have been created, then Check the full control checkbox.

There you go. You have now permission to your database.

Note: The connection-string in the above questions is using SQL-server authentication. So, Before taking the above step, You have to login using windows-authentication first, and then you have to give permission to the user who is using sql-server authentication. Permission like "dbcreator".

if you login with SQL server authentication and trying to give permission to the user you logged in. it shows, permission denied error.

What are the differences between Mustache.js and Handlebars.js?

—In addition to using "this" for handlebars, and the nested variable within variable block for mustache, you can also use the nested dot in a block for mustache:

    {{#variable}}<span class="text">{{.}}</span>{{/variable}}

How can I profile C++ code running on Linux?

Use Valgrind, callgrind and kcachegrind:

valgrind --tool=callgrind ./(Your binary)

generates callgrind.out.x. Read it using kcachegrind.

Use gprof (add -pg):

cc -o myprog myprog.c utils.c -g -pg 

(not so good for multi-threads, function pointers)

Use google-perftools:

Uses time sampling, I/O and CPU bottlenecks are revealed.

Intel VTune is the best (free for educational purposes).

Others: AMD Codeanalyst (since replaced with AMD CodeXL), OProfile, 'perf' tools (apt-get install linux-tools)

Get width/height of SVG element

SVG has properties width and height. They return an object SVGAnimatedLength with two properties: animVal and baseVal. This interface is used for animation, where baseVal is the value before animation. From what I can see, this method returns consistent values in both Chrome and Firefox, so I think it can also be used to get calculated size of SVG.

How do relative file paths work in Eclipse?

You can always get your runtime path by using:

 String path = new File(".").getCanonicalPath();

This provides valuable information about where to put files and resources.

Remove duplicates from a dataframe in PySpark

It is not an import problem. You simply call .dropDuplicates() on a wrong object. While class of sqlContext.createDataFrame(rdd1, ...) is pyspark.sql.dataframe.DataFrame, after you apply .collect() it is a plain Python list, and lists don't provide dropDuplicates method. What you want is something like this:

 (df1 = sqlContext
     .createDataFrame(rdd1, ['column1', 'column2', 'column3', 'column4'])
     .dropDuplicates())

 df1.collect()

How to let an ASMX file output JSON

From WebService returns XML even when ResponseFormat set to JSON:

Make sure that the request is a POST request, not a GET. Scott Guthrie has a post explaining why.

Though it's written specifically for jQuery, this may also be useful to you:
Using jQuery to Consume ASP.NET JSON Web Services

Dynamically create checkbox with JQuery from text input

Put a global variable to generate the ids.

<script>
    $(function(){
        // Variable to get ids for the checkboxes
        var idCounter=1;
        $("#btn1").click(function(){
            var val = $("#txtAdd").val();
            $("#divContainer").append ( "<label for='chk_" + idCounter + "'>" + val + "</label><input id='chk_" + idCounter + "' type='checkbox' value='" + val + "' />" );
            idCounter ++;
        });
    });
</script>
<div id='divContainer'></div>
<input type="text" id="txtAdd" /> 
<button id="btn1">Click</button>

Python safe method to get value of nested dictionary

Little improvement to reduce approach to make it work with list. Also using data path as string divided by dots instead of array.

def deep_get(dictionary, path):
    keys = path.split('.')
    return reduce(lambda d, key: d[int(key)] if isinstance(d, list) else d.get(key) if d else None, keys, dictionary)

java.io.IOException: Broken pipe

Basically, what is happening is that your user is either closing the browser tab, or is navigating away to a different page, before communication was complete. Your webserver (Jetty) generates this exception because it is unable to send the remaining bytes.

org.eclipse.jetty.io.EofException: null
! at org.eclipse.jetty.http.HttpGenerator.flushBuffer(HttpGenerator.java:914)
! at org.eclipse.jetty.http.HttpGenerator.complete(HttpGenerator.java:798)
! at org.eclipse.jetty.server.AbstractHttpConnection.completeResponse(AbstractHttpConnection.java:642)
! 

This is not an error on your application logic side. This is simply due to user behavior. There is nothing wrong in your code per se.

There are two things you may be able to do:

  1. Ignore this specific exception so that you don't log it.
  2. Make your code more efficient/packed so that it transmits less data. (Not always an option!)

How do I apply a perspective transform to a UIView?

You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.

Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.

How to access the php.ini from my CPanel?

I had the same issue in cPanel 92.0.3 and it was solved through this solution:

In cPanel go to the below directory

software --> select PHP version--> option--> upload_max_filesize 

Then choose the optional size to upload your files.

Razor/CSHTML - Any Benefit over what we have?

Ex Microsoft Developer's Opinion

I worked on a core team for the MSDN website. Now, I use c# razor for ecommerce sites with my programming team and we focus heavy on jQuery front end with back end c# razor pages and LINQ-Entity memory database so the pages are 1-2 millisecond response times even on nested for loops with queries and no page caching. We don't use MVC, just plain ASP.NET with razor pages being mapped with URL Rewrite module for IIS 7, no ASPX pages or ViewState or server-side event programming at all. It doesn't have the extra (unnecessary) layers MVC puts in code constructs for the regex challenged. Less is more for us. Its all lean and mean but I give props to MVC for its testability but that's all.

Razor pages have no event life cycle like ASPX pages. Its just rendering as one requested page. C# is such a great language and Razor gets out of its way nicely to let it do its job. The anonymous typing with generics and linq make life so easy with c# and razor pages. Using Razor pages will help you think and code lighter.

One of the drawback of Razor and MVC is there is no ViewState-like persistence. I needed to implement a solution for that so I ended up writing a jQuery plugin for that here -> http://www.jasonsebring.com/dumbFormState which is an HTML 5 offline storage supported plugin for form state that is working in all major browsers now. It is just for form state currently but you can use window.sessionStorage or window.localStorage very simply to store any kind of state across postbacks or even page requests, I just bothered to make it autosave and namespace it based on URL and form index so you don't have to think about it.

Python Decimals format

Only first part of Justin's answer is correct. Using "%.3g" will not work for all cases as .3 is not the precision, but total number of digits. Try it for numbers like 1000.123 and it breaks.

So, I would use what Justin is suggesting:

>>> ('%.4f' % 12340.123456).rstrip('0').rstrip('.')
'12340.1235'
>>> ('%.4f' % -400).rstrip('0').rstrip('.')
'-400'
>>> ('%.4f' % 0).rstrip('0').rstrip('.')
'0'
>>> ('%.4f' % .1).rstrip('0').rstrip('.')
'0.1'

Using Python, find anagrams for a list of words

A set is an appropriate data structure for the output, since you presumably don't want redundancy in the output. A dictionary is ideal for looking up if a particular sequence of letters has been previously observed, and what word it originally came from. Taking advantage of the fact that we can add the same item to a set multiple times without expanding the set lets us get away with one for loop.

def return_anagrams(word_list):
    d = {}
    out = set()
    for word in word_list:
        s = ''.join(sorted(word))
        try:
            out.add(d[s])
            out.add(word)
        except:
            d[s] = word
    return out

A faster way of doing it takes advantage of the commutative property of addition:

import numpy as np

def vector_anagram(l):
    d, out = dict(), set()
    for word in l:
        s = np.zeros(26, dtype=int)
        for c in word:
            s[ord(c)-97] += 1
        s = tuple(s)
        try:
            out.add(d[s])
            out.add(word)
        except:
            d[s] = word
    return out

Setting a log file name to include current date in Log4j

I have created an appender that will do that. http://stauffer.james.googlepages.com/DateFormatFileAppender.java

/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software
 * License version 1.1, a copy of which has been included with this
 * distribution in the LICENSE.txt file.  */

package sps.log.log4j;

import java.io.IOException;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.*;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

/**
 * DateFormatFileAppender is a log4j Appender and extends 
 * {@link FileAppender} so each log is 
 * named based on a date format defined in the File property.
 *
 * Sample File: 'logs/'yyyy/MM-MMM/dd-EEE/HH-mm-ss-S'.log'
 * Makes a file like: logs/2004/04-Apr/13-Tue/09-45-15-937.log
 * @author James Stauffer
 */
public class DateFormatFileAppender extends FileAppender {

  /**
   * The default constructor does nothing.
   */
  public DateFormatFileAppender() {
  }

  /**
   * Instantiate a <code>DailyRollingFileAppender</code> and open the
   * file designated by <code>filename</code>. The opened filename will
   * become the ouput destination for this appender.
   */
  public DateFormatFileAppender (Layout layout, String filename) throws IOException {
    super(layout, filename, true);
  }

  private String fileBackup;//Saves the file pattern
  private boolean separate = false;

  public void setFile(String file) {
    super.setFile(file);
    this.fileBackup = getFile();
  }

  /**
   * If true each LoggingEvent causes that file to close and open.
   * This is useful when the file is a pattern that would often
   * produce a different filename.
   */
  public void setSeparate(boolean separate) {
    this.separate = separate;
  }

  protected void subAppend(LoggingEvent event) {
    if(separate) {
        try {//First reset the file so each new log gets a new file.
            setFile(getFile(), getAppend(), getBufferedIO(), getBufferSize());
        } catch(IOException e) {
            LogLog.error("Unable to reset fileName.");
        }
    }
    super.subAppend(event);
  }


  public
  synchronized
  void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize)
                                                            throws IOException {
    SimpleDateFormat sdf = new SimpleDateFormat(fileBackup);
    String actualFileName = sdf.format(new Date());
    makeDirs(actualFileName);
    super.setFile(actualFileName, append, bufferedIO, bufferSize);
  }

  /**
   * Ensures that all of the directories for the given path exist.
   * Anything after the last / or \ is assumed to be a filename.
   */
  private void makeDirs (String path) {
    int indexSlash = path.lastIndexOf("/");
    int indexBackSlash = path.lastIndexOf("\\");
    int index = Math.max(indexSlash, indexBackSlash);
    if(index > 0) {
        String dirs = path.substring(0, index);
//        LogLog.debug("Making " + dirs);
        File dir = new File(dirs);
        if(!dir.exists()) {
            boolean success = dir.mkdirs();
            if(!success) {
                LogLog.error("Unable to create directories for " + dirs);
            }
        }
    }
  }

}

Python Prime number checker

The two main problems with your code are:

  1. After designating a number not prime, you continue to check the rest of the divisors even though you already know it is not prime, which can lead to it printing "prime" after printing "not prime". Hint: use the `break' statement.
  2. You designate a number prime before you have checked all the divisors you need to check, because you are printing "prime" inside the loop. So you get "prime" multiple times, once for each divisor that doesn't go evenly into the number being tested. Hint: use an else clause with the loop to print "prime" only if the loop exits without breaking.

A couple pretty significant inefficiencies:

  1. You should keep track of the numbers you have already found that are prime and only divide by those. Why divide by 4 when you have already divided by 2? If a number is divisible by 4 it is also divisible by 2, so you would have already caught it and there is no need to divide by 4.
  2. You need only to test up to the square root of the number being tested because any factor larger than that would need to be multiplied with a number smaller than that, and that would already have been tested by the time you get to the larger one.

How to get the Mongo database specified in connection string in C#

In this moment with the last version of the C# driver (2.3.0) the only way I found to get the database name specified in connection string is this:

var connectionString = @"mongodb://usr:[email protected],srv2.acme.net,srv3.acme.net/dbName?replicaSet=rset";
var mongoUrl = new MongoUrl(connectionString);
var dbname = mongoUrl.DatabaseName;
var db = new MongoClient(mongoUrl).GetDatabase(dbname);
db.GetCollection<MyType>("myCollectionName");

Removing multiple classes (jQuery)

Separate classes by white space

$('element').removeClass('class1 class2');

Programmatically Add CenterX/CenterY Constraints

The ObjectiveC equivalent is:

    myView.translatesAutoresizingMaskIntoConstraints = NO;

    [[myView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor] setActive:YES];

    [[myView.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor] setActive:YES];

Can't install any packages in Node.js using "npm install"

This error might also occur due to proxy settings, once check that your proxy allow the access to npm commands.

It worked for me quite well.

PostgreSQL function for last inserted ID

See the below example

CREATE TABLE users (
    -- make the "id" column a primary key; this also creates
    -- a UNIQUE constraint and a b+-tree index on the column
    id    SERIAL PRIMARY KEY,
    name  TEXT,
    age   INT4
);

INSERT INTO users (name, age) VALUES ('Mozart', 20);

Then for getting last inserted id use this for table "user" seq column name "id"

SELECT currval(pg_get_serial_sequence('users', 'id'));

Get specific objects from ArrayList when objects were added anonymously?

Given the use of List, there's no way to "lookup" a value without iterating through it...

For example...

Cave cave = new Cave();

// Loop adds several Parties to the cave's party list
cave.parties.add(new Party("FirstParty")); // all anonymously added
cave.parties.add(new Party("SecondParty"));
cave.parties.add(new Party("ThirdParty"));

for (Party p : cave.parties) {
    if (p.name.equals("SecondParty") {
        p.index = ...;
        break;
    }
}

Now, this will take time. If the element you are looking for is at the end of the list, you will have to iterate to the end of the list before you find a match.

It might be better to use a Map of some kind...

So, if we update Cave to look like...

class Cave {
    Map<String, Party> parties = new HashMap<String, Party>(25);
}

We could do something like...

Cave cave = new Cave();

// Loop adds several Parties to the cave's party list
cave.parties.put("FirstParty", new Party("FirstParty")); // all anonymously added
cave.parties.put("SecondParty", new Party("SecondParty"));
cave.parties.put("ThirdParty", new Party("ThirdParty"));

if (cave.parties.containsKey("SecondParty")) {
    cave.parties.get("SecondParty").index = ...
}

Instead...

Ultimately, this will all depend on what it is you want to achieve...

How to style icon color, size, and shadow of Font Awesome Icons

inyour.css file:

    *.icon-white {color: white}
    *.icon-silver {color: silver}

inyour.html file:

    <a><i class="icon-book icon-white"></i> Book</a>
    <a><i class="icon-ok-sign icon-silver"></i> OK</a>

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

How to find rows in one table that have no corresponding row in another table

select tableA.id from tableA left outer join tableB on (tableA.id = tableB.id)
where tableB.id is null
order by tableA.id desc 

If your db knows how to do index intersections, this will only touch the primary key index

Video 100% width and height

This is a great way to make the video fit a banner, you might need to tweak this a little for full screen but should be ok. 100% CSS.

_x000D_
_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    z-index: 1;_x000D_
    min-width: 100%;_x000D_
    min-height: 100%;_x000D_
    width: auto;_x000D_
    height: auto;_x000D_
    transform: translate(-50%, -50%);
_x000D_
_x000D_
_x000D_

The operation couldn’t be completed. (com.facebook.sdk error 2.) ios6

This worked for me:

  • Go to the settings app of your iPhone.
  • Open your Facebook Settings
  • Scroll down to your app and make sure your app allows facebook interaction.

This could happen on any device, therefore in your app you will have to make sure to handle this error correctly. I reckon you give the user feedback why Login With Facebook failed and ask the user to check their Facebook settings on their device.

 - (void)facebookSessionStateChanged:(FBSession *)session state:(FBSessionState)state error:(NSError *)error
{
    switch (state) {
        case FBSessionStateOpen:
            // handle successful login here
        case FBSessionStateClosed:
        case FBSessionStateClosedLoginFailed:
            [FBSession.activeSession closeAndClearTokenInformation];

            if (error) {
                // handle error here, for example by showing an alert to the user
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Could not login with Facebook"
                                                                message:@"Facebook login failed. Please check your Facebook settings on your phone."
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
                [alert show];
            }
            break;
        default:
            break;
    }

With CSS, how do I make an image span the full width of the page as a background image?

If you're hoping to use background-image: url(...);, I don't think you can. However, if you want to play with layering, you can do something like this:

<img class="bg" src="..." />

And then some CSS:

.bg
{
  width: 100%;
  z-index: 0;
}

You can now layer content above the stretched image by playing with z-indexes and such. One quick note, the image can't be contained in any other elements for the width: 100%; to apply to the whole page.

Here's a quick demo if you can't rely on background-size: http://jsfiddle.net/bB3Uc/

Push JSON Objects to array in localStorage

var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item

Install msi with msiexec in a Specific Directory

Here's my attempt to install .msi using msiexec in Administrative PowerShell.

I've made it 7 times for each of 2 drives, C: and D: (14 total) with different arguments in place of ARG and the same desirable path value.

Template: PS C:\WINDOWS\system32> msiexec /a D:\users\username\downloads\soft\publisher\softwarename\software.msi /passive ARG="D:\Soft\publisher\softwarename"

ARGs:

  • TARGETDIR
    • Works OK-ish, but produces redundand ProgramFilesFolder (with an additional folders similar to the default installation path, e.g. D:\Soft\BlenderFoundation\Blender\ProgramFilesFolder\Blender Foundation\Blender\2.81\) and a copy of the .msi at the target folder.
  • INSTALLDIR, INSTALLPATH, INSTALLFOLDER, INSTALLLOCATION, APPLICATIONFOLDER, APPDIR
    • When running on the same drive as set in the parameter: installs on this drive in a default folder (e.g. D:\Blender Foundation\Blender\2.81\)
    • When running from a differnet drive: seems to do nothing

Static Initialization Blocks

static int B,H;
static boolean flag = true;
static{
    Scanner scan = new Scanner(System.in);
    B = scan.nextInt();
    scan.nextLine();
    H = scan.nextInt();

    if(B < 0 || H < 0){
        flag = false;
        System.out.println("java.lang.Exception: Breadth and height must be positive");
    } 
}

How to create Toast in Flutter?

https://pub.dev/packages/toast use this for toast this library is pretty easy to use and perfect work for ios and android,

Syntax for show Toast:

Toast.show("Toast plugin app", duration: Toast.LENGTH_SHORT, gravity:  Toast.BOTTOM);

PHP: Update multiple MySQL fields in single query

Add your multiple columns with comma separations:

UPDATE settings SET postsPerPage = $postsPerPage, style= $style WHERE id = '1'

However, you're not sanitizing your inputs?? This would mean any random hacker could destroy your database. See this question: What's the best method for sanitizing user input with PHP?

Also, is style a number or a string? I'm assuming a string, so it would need to be quoted.

How to end C++ code

Dude... exit() function is defined under stdlib.h

So you need to add a preprocessor.

Put include stdlib.h in the header section

Then use exit(); wherever you like but remember to put an interger number in the parenthesis of exit.

for example:

exit(0);

java.lang.ClassNotFoundException on working app

This is my observation with respect to the Error. I recently Updated the ADT to 22.0.1. I am getting following Error when i imported my previous Projects "E/AndroidRuntime(24807): Caused by: java.lang.ClassNotFoundException: com.sherl.sherlockfragmentsapp.StartActivity in loader dalvik.system.PathClassLoader[/data/app/com.sherl.sherlockfragmentsapp-1.apk]"

Then I changed "Properties->Java Build Path-> Order and Export" in the following manner [Unable to add the Image because of the Forum rules]

  1. Android Private Libraries - checked
  2. Android 4.2.2 - unchecked
  3. Android Dependencies - checked
  4. /src - selected
  5. /gen - selected

It resolved the issue. Hope this is Help you guys.

Python: How would you save a simple settings/config file?

ConfigParser Basic example

The file can be loaded and used like this:

#!/usr/bin/env python

import ConfigParser
import io

# Load the configuration file
with open("config.yml") as f:
    sample_config = f.read()
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.readfp(io.BytesIO(sample_config))

# List all contents
print("List all contents")
for section in config.sections():
    print("Section: %s" % section)
    for options in config.options(section):
        print("x %s:::%s:::%s" % (options,
                                  config.get(section, options),
                                  str(type(options))))

# Print some contents
print("\nPrint some contents")
print(config.get('other', 'use_anonymous'))  # Just get the value
print(config.getboolean('other', 'use_anonymous'))  # You know the datatype?

which outputs

List all contents
Section: mysql
x host:::localhost:::<type 'str'>
x user:::root:::<type 'str'>
x passwd:::my secret password:::<type 'str'>
x db:::write-math:::<type 'str'>
Section: other
x preprocessing_queue:::["preprocessing.scale_and_center",
"preprocessing.dot_reduction",
"preprocessing.connect_lines"]:::<type 'str'>
x use_anonymous:::yes:::<type 'str'>

Print some contents
yes
True

As you can see, you can use a standard data format that is easy to read and write. Methods like getboolean and getint allow you to get the datatype instead of a simple string.

Writing configuration

import os
configfile_name = "config.yaml"

# Check if there is already a configurtion file
if not os.path.isfile(configfile_name):
    # Create the configuration file as it doesn't exist yet
    cfgfile = open(configfile_name, 'w')

    # Add content to the file
    Config = ConfigParser.ConfigParser()
    Config.add_section('mysql')
    Config.set('mysql', 'host', 'localhost')
    Config.set('mysql', 'user', 'root')
    Config.set('mysql', 'passwd', 'my secret password')
    Config.set('mysql', 'db', 'write-math')
    Config.add_section('other')
    Config.set('other',
               'preprocessing_queue',
               ['preprocessing.scale_and_center',
                'preprocessing.dot_reduction',
                'preprocessing.connect_lines'])
    Config.set('other', 'use_anonymous', True)
    Config.write(cfgfile)
    cfgfile.close()

results in

[mysql]
host = localhost
user = root
passwd = my secret password
db = write-math

[other]
preprocessing_queue = ['preprocessing.scale_and_center', 'preprocessing.dot_reduction', 'preprocessing.connect_lines']
use_anonymous = True

XML Basic example

Seems not to be used at all for configuration files by the Python community. However, parsing / writing XML is easy and there are plenty of possibilities to do so with Python. One is BeautifulSoup:

from BeautifulSoup import BeautifulSoup

with open("config.xml") as f:
    content = f.read()

y = BeautifulSoup(content)
print(y.mysql.host.contents[0])
for tag in y.other.preprocessing_queue:
    print(tag)

where the config.xml might look like this

<config>
    <mysql>
        <host>localhost</host>
        <user>root</user>
        <passwd>my secret password</passwd>
        <db>write-math</db>
    </mysql>
    <other>
        <preprocessing_queue>
            <li>preprocessing.scale_and_center</li>
            <li>preprocessing.dot_reduction</li>
            <li>preprocessing.connect_lines</li>
        </preprocessing_queue>
        <use_anonymous value="true" />
    </other>
</config>

Oracle Error ORA-06512

The variable pCv is of type VARCHAR2 so when you concat the insert you aren't putting it inside single quotes:

 EXECUTE IMMEDIATE  'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('''||pCv||''', '||pSup||', '||pIdM||')';

Additionally the error ORA-06512 raise when you are trying to insert a value too large in a column. Check the definiton of the table M_pNum_GR and the parameters that you are sending. Just for clarify if you try to insert the value 100 on a NUMERIC(2) field the error will raise.

I want to execute shell commands from Maven's pom.xml

Thanks! Tomer Ben David. it helped me. as I am doing pip install in demo folder as you mentioned npm install

<groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.3.2</version>
            <executions>
              <execution>
                <goals>
                  <goal>exec</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <executable>pip</executable>
              <arguments><argument>install</argument></arguments>                            
             <workingDirectory>${project.build.directory}/Demo</workingDirectory>
            </configuration>

How do I disable log messages from the Requests library?

I'm not sure if the previous approaches have stopped working, but in any case, here's another way of removing the warnings:

PYTHONWARNINGS="ignore:Unverified HTTPS request" ./do-insecure-request.py

Basically, adding an environment variable in the context of the script execution.

From the documentation: https://urllib3.readthedocs.org/en/latest/security.html#disabling-warnings

HTML radio buttons allowing multiple selections

I've done it this way in the past, JsFiddle:

CSS:

.radio-option {
    cursor: pointer;
    height: 23px;
    width: 23px;
    background: url(../images/checkbox2.png) no-repeat 0px 0px;
}

.radio-option.click {
    background: url(../images/checkbox1.png) no-repeat 0px 0px;
}

HTML:

<li><div class="radio-option"></div></li>
<li><div class="radio-option"></div></li>
<li><div class="radio-option"></div></li>
<li><div class="radio-option"></div></li>
<li><div class="radio-option"></div></li>

jQuery:

<script>
    $(document).ready(function() {
        $('.radio-option').click(function () {
            $(this).not(this).removeClass('click');
            $(this).toggleClass("click");
        });
    });
</script>

500 internal server error at GetResponse()

For me this error occurred because I had 2 web API actions that had the exact same signatures and both had the same verbs, HttpPost, what I did was change one of the verbs (the one used for updating) to PUT and the error was removed. The following in my catch statement helped in getting to the root of the problem:

catch (WebException webex)
{
                WebResponse errResp = webex.Response;
                using (Stream respStream = errResp.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(respStream);
                    string text = reader.ReadToEnd();
                }
}

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

I had the exact same problem, unfortunately, adding the primary key doesn't solve the issue. So here's how I solve mine:

  1. Make sure you have a primary key on the table so I alter my table and add a primary key.
  2. Delete the ADO.NET Entity Data Model (edmx file) where I use to map and connect with my database.
  3. Add again a new file of ADO.NET Entity Data Model to connect with my database and for mapping my model properties.
  4. Clean and rebuild the solution.

Problem solved.

Setting Android Theme background color

Open res -> values -> styles.xml and to your <style> add this line replacing with your image path <item name="android:windowBackground">@drawable/background</item>. Example:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowBackground">@drawable/background</item>
    </style>

</resources>

There is a <item name ="android:colorBackground">@color/black</item> also, that will affect not only your main window background but all the component in your app. Read about customize theme here.

If you want version specific styles:

If a new version of Android adds theme attributes that you want to use, you can add them to your theme while still being compatible with old versions. All you need is another styles.xml file saved in a values directory that includes the resource version qualifier. For example:

res/values/styles.xml        # themes for all versions
res/values-v21/styles.xml    # themes for API level 21+ only

Because the styles in the values/styles.xml file are available for all versions, your themes in values-v21/styles.xml can inherit them. As such, you can avoid duplicating styles by beginning with a "base" theme and then extending it in your version-specific styles.

Read more here(doc in theme).

Press TAB and then ENTER key in Selenium WebDriver

In javascript (node.js) this works for me:

describe('UI', function() {

describe('gets results from Bing', function() {
    this.timeout(10000);

    it('makes a search', function(done) {
        var driver = new webdriver.Builder().
        withCapabilities(webdriver.Capabilities.chrome()).
        build();


        driver.get('http://bing.com');
        var input = driver.findElement(webdriver.By.name('q'));
        input.sendKeys('something');
        input.sendKeys(webdriver.Key.ENTER);

        driver.wait(function() {
            driver.findElement(webdriver.By.className('sb_count')).
                getText().
                then(function(result) {
                  console.log('result: ', result);
                  done();
            });
        }, 8000);


    });
  });
});

For tab use webdriver.Key.TAB

how to download image from any web page in java

You are looking for a web crawler. You can use JSoup to do this, here is basic example

How to remove all MySQL tables from the command-line without DROP database permissions?

You can drop the database and then recreate it with the below:-

mysql> drop database [database name];
mysql> create database [database name];

Passing Variable through JavaScript from one html page to another page

You have a few different options:

  • you can use a SPA router like SammyJS, or Angularjs and ui-router, so your pages are stateful.
  • use sessionStorage to store your state.
  • store the values on the URL hash.

PHP XML how to output nice format

// ##### IN SUMMARY #####

$xmlFilepath = 'test.xml';
echoFormattedXML($xmlFilepath);

/*
 * echo xml in source format
 */
function echoFormattedXML($xmlFilepath) {
    header('Content-Type: text/xml'); // to show source, not execute the xml
    echo formatXML($xmlFilepath); // format the xml to make it readable
} // echoFormattedXML

/*
 * format xml so it can be easily read but will use more disk space
 */
function formatXML($xmlFilepath) {
    $loadxml = simplexml_load_file($xmlFilepath);

    $dom = new DOMDocument('1.0');
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML($loadxml->asXML());
    $formatxml = new SimpleXMLElement($dom->saveXML());
    //$formatxml->saveXML("testF.xml"); // save as file

    return $formatxml->saveXML();
} // formatXML

Count frequency of words in a list and sort by frequency

Using Counter would be the best way, but if you don't want to do that, you can implement it yourself this way.

# The list you already have
word_list = ['words', ..., 'other', 'words']
# Get a set of unique words from the list
word_set = set(word_list)
# create your frequency dictionary
freq = {}
# iterate through them, once per unique word.
for word in word_set:
    freq[word] = word_list.count(word) / float(len(word_list))

freq will end up with the frequency of each word in the list you already have.

You need float in there to convert one of the integers to a float, so the resulting value will be a float.

Edit:

If you can't use a dict or set, here is another less efficient way:

# The list you already have
word_list = ['words', ..., 'other', 'words']
unique_words = []
for word in word_list:
    if word not in unique_words:
        unique_words += [word]
word_frequencies = []
for word in unique_words:
    word_frequencies += [float(word_list.count(word)) / len(word_list)]
for i in range(len(unique_words)):
    print(unique_words[i] + ": " + word_frequencies[i])

The indicies of unique_words and word_frequencies will match.

fatal: The current branch master has no upstream branch

1. A computer and your github associated. Use SSH. Computer code so you do not need to submit verified enter image description here

2. git can not manage empty folder. So you have to write such a readme.md saved in a file. Otherwise you will not find the file.

3. Your local project is nothing new projects move over. Please

git init

git remote add origin +"githublink"

git add .

git commit -m "" go again.

4. then git pull origin master (the key)

5. At last git push origin master (solve all problem).

http://my.oschina.net/psuyun/blog/123005 ????

How can I compare time in SQL Server?

One (possibly small) issue I have noted with the solutions so far is that they all seem to require a function call to process the comparison. This means that the query engine will need to do a full table scan to seek the rows you are after - and be unable to use an index. If the table is not going to get particularly large, this probably won't have any adverse affects (and you can happily ignore this answer).

If, on the other hand, the table could get quite large, the performance of the query could suffer.

I know you stated that you do not wish to compare the date part - but is there an actual date being stored in the datetime column, or are you using it to store only the time? If the latter, you can use a simple comparison operator, and this will reduce both CPU usage, and allow the query engine to use statistics and indexes (if present) to optimise the query.

If, however, the datetime column is being used to store both the date and time of the event, this obviously won't work. In this case if you can modify the app and the table structure, separate the date and time into two separate datetime columns, or create a indexed view that selects all the (relevant) columns of the source table, and a further column that contains the time element you wish to search for (use any of the previous answers to compute this) - and alter the app to query the view instead.

read word by word from file in C++

I have edited the function for you,

void readFile()
{
    ifstream file;
    file.open ("program.txt");
    if (!file.is_open()) return;

    string word;
    while (file >> word)
    {
        cout<< word << '\n';
    }
}

Postgresql 9.2 pg_dump version mismatch

The answer sounds silly but if you get the above error and wanna run the pg_dump for earlier version go to bin directory of postgres and type

./pg_dump servername > out.sql ./ ignores the root and looks for pg_dump in current directory

jquery fill dropdown with json data

If your data is already in array form, it's really simple using jQuery:

 $(data.msg).each(function()
 {
     alert(this.value);
     alert(this.label);

     //this refers to the current item being iterated over

     var option = $('<option />');
     option.attr('value', this.value).text(this.label);

     $('#myDropDown').append(option);
 });

.ajax() is more flexible than .getJSON() - for one, getJson is targeted specifically as a GET request to retrieve json; ajax() can request on any verb to get back any content type (although sometimes that's not useful). getJSON internally calls .ajax().

Inconsistent accessibility: property type is less accessible

Your class Delivery has no access modifier, which means it defaults to internal. If you then try to expose a property of that type as public, it won't work. Your type (class) needs to have the same, or higher access as your property.

More about access modifiers: http://msdn.microsoft.com/en-us/library/ms173121.aspx

How can I shrink the drawable on a button?

Use a ScaleDrawable as Abhinav suggested.

The problem is that the drawable doesn't show then - it's some sort of bug in ScaleDrawables. you'll need to change the "level" programmatically. This should work for every button:

// Fix level of existing drawables
Drawable[] drawables = myButton.getCompoundDrawables();
for (Drawable d : drawables) if (d != null && d instanceof ScaleDrawable) d.setLevel(1);
myButton.setCompoundDrawables(drawables[0], drawables[1], drawables[2], drawables[3]);

Python strip() multiple characters?

strip only strips characters from the very front and back of the string.

To delete a list of characters, you could use the string's translate method:

import string
name = "Barack (of Washington)"
table = string.maketrans( '', '', )
print name.translate(table,"(){}<>")
# Barack of Washington

Set a thin border using .css() in javascript

Maybe just "border-width" instead of "border-weight"? There is no "border-weight" and this property is just ignored and default width is used instead.

How can I check whether an array is null / empty?

An int array is initialised with zero so it won't actually ever contain nulls. Only arrays of Object's will contain null initially.

Using regular expression in css?

An ID is meant to identify the element uniquely. Any styles applied to it should also be unique to that element. If you have styles you want to apply to many elements, you should add a class to them all, rather than relying on ID selectors...

<div id="sections">
   <div id="s1" class="sec">...</div>
   <div id="s2" class="sec">...</div>
   ...
</div>

and

.sec {
    ...
}

Or in your specific case you could select all divisions inside your parent container, if nothing else is inside it, like so:

#sections > div {
    ...
}

Javascript close alert box

You actually can do this you can basically listen for this pop up to happen and then confirm true before it ever "pops up",

if(window.alert){
  return true
}

Disable scrolling in all mobile devices

cgvector answer didn't work for me, but this did:

document.body.addEventListener('touchstart', function(e){ e.preventDefault(); });

I wouldn't leave it just like that, a smarter logic is needed to select when to prevent the scrolling, but this is a good start.

Taken from here: Disable scrolling in an iPhone web application?

Checking oracle sid and database name

As has been mentioned above,

select global_name from global_name;

is the way to go.

You couldn't query v$database/v$instance/v$thread because your user does not have the required permissions. You can grant them (via a DBA account) with:

grant select on v$database to <username here>;

Could not load file or assembly or one of its dependencies. Access is denied. The issue is random, but after it happens once, it continues

Check the IIS settings. I use IIS 7.5 with 32 or 64 bit compilation within the .NET framework. If you have an app that uses 32-bit mode, make sure to enable the App Pool to be able to use 32-bit instruction. Otherwise, nothing seems to work no matter how much you set the security or strong sign the DLL.

How to get the hostname of the docker host from inside a docker container on that host without env vars

Another option that worked for me was to bind the network namespace of the host to the docker.

By adding:

docker run --net host

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

When you installed composer pretty sure you used $ sudo command because of that the ~/.composer folder was created by the root.

Run this to fix the issue:

$ sudo chown -R $USER $HOME/.composer

How can I get the last day of the month in C#?

DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)

How can I create numbered map markers in Google Maps V3?

This how I do it in V3:

I start by loading the google maps api and within the callback method initialize() I load MarkerWithLabel.js that I found here:

function initialize() {

            $.getScript("/js/site/marker/MarkerWithLabel.js#{applicationBean.version}", function(){

            var mapOptions = {
                zoom: 8,
                center: new google.maps.LatLng(currentLat, currentLng),
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                streetViewControl: false,
                mapTypeControl: false
            };

            var map = new google.maps.Map(document.getElementById('mapholder'),
                    mapOptions);

            var bounds = new google.maps.LatLngBounds();

            for (var i = 0; i &lt; mapData.length; i++) {
                createMarker(i+1, map, mapData[i]); <!-- MARKERS! -->
                extendBounds(bounds, mapData[i]);
            }
            map.fitBounds(bounds);
            var maximumZoomLevel = 16;
            var minimumZoomLevel = 11;
            var ourZoom = defaultZoomLevel; // default zoom level

            var blistener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
                if (this.getZoom(map.getBounds) &gt; 16) {
                    this.setZoom(maximumZoomLevel);
                }
                google.maps.event.removeListener(blistener);
            });
            });
        }

        function loadScript() {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&amp;libraries=places&amp;sensor=false&amp;callback=initialize";
            document.body.appendChild(script);
        }

        window.onload = loadScript;

    </script> 

I then create the markers with createMarker():

function createMarker(number, currentMap, currentMapData) {

   var marker = new MarkerWithLabel({
       position: new google.maps.LatLng(currentMapData[0], currentMapData[1]),
                 map: currentMap,
                 icon: '/img/sticker/empty.png',
                 shadow: '/img/sticker/bubble_shadow.png',
                 transparent: '/img/sticker/bubble_transparent.png',
                 draggable: false,
                 raiseOnDrag: false,
                 labelContent: ""+number,
                 labelAnchor: new google.maps.Point(3, 30),
                 labelClass: "mapIconLabel", // the CSS class for the label
                 labelInBackground: false
                });
            }

Since I added mapIconLabel class to the marker I can add some css rules in my css:

.mapIconLabel {
    font-size: 15px;
    font-weight: bold;
    color: #FFFFFF;
    font-family: 'DINNextRoundedLTProMediumRegular';
}

And here is the result:

MarkerWithIconAndLabel

How to properly seed random number generator

It's nano seconds, what are the chances of getting the same seed twice.
Anyway, thanks for the help, here is my end solution based on all the input.

package main

import (
    "math/rand"
    "time"
)

func init() {
    rand.Seed(time.Now().UTC().UnixNano())
}

// generates a random string
func srand(min, max int, readable bool) string {

    var length int
    var char string

    if min < max {
        length = min + rand.Intn(max-min)
    } else {
        length = min
    }

    if readable == false {
        char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    } else {
        char = "ABCDEFHJLMNQRTUVWXYZabcefghijkmnopqrtuvwxyz23479"
    }

    buf := make([]byte, length)
    for i := 0; i < length; i++ {
        buf[i] = char[rand.Intn(len(char)-1)]
    }
    return string(buf)
}

// For testing only
func main() {
    println(srand(5, 5, true))
    println(srand(5, 5, true))
    println(srand(5, 5, true))
    println(srand(5, 5, false))
    println(srand(5, 7, true))
    println(srand(5, 10, false))
    println(srand(5, 50, true))
    println(srand(5, 10, false))
    println(srand(5, 50, true))
    println(srand(5, 10, false))
    println(srand(5, 50, true))
    println(srand(5, 10, false))
    println(srand(5, 50, true))
    println(srand(5, 4, true))
    println(srand(5, 400, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
}

Materialize CSS - Select Doesn't Seem to Render

The solution that worked for me is by calling the 'material_select' function after the options data has been loaded. If you print out the value of OptionsList.find().count() to the console it's first 0 then a few milliseconds later the list gets populated with data.

Template.[name].rendered = function() {
    this.autorun(function() {
        var optionsCursor = OptionsList.find().count();
        if(optionsCursor > 0)
        {
            $('select').material_select();
        }
    });
};

Git diff --name-only and copy that list

The following should work fine:

git diff -z --name-only commit1 commit2 | xargs -0 -IREPLACE rsync -aR REPLACE /home/changes/protected/

To explain further:

  • The -z to with git diff --name-only means to output the list of files separated with NUL bytes instead of newlines, just in case your filenames have unusual characters in them.

  • The -0 to xargs says to interpret standard input as a NUL-separated list of parameters.

  • The -IREPLACE is needed since by default xargs would append the parameters to the end of the rsync command. Instead, that says to put them where the later REPLACE is. (That's a nice tip from this Server Fault answer.)

  • The -a parameter to rsync means to preserve permissions, ownership, etc. if possible. The -R means to use the full relative path when creating the files in the destination.

Update: if you have an old version of xargs, you'll need to use the -i option instead of -I. (The former is deprecated in later versions of findutils.)

How do I schedule a task to run at periodic intervals?

timer.scheduleAtFixedRate( new Task(), 1000,3000); 

SQLite string contains other string query

While LIKE is suitable for this case, a more general purpose solution is to use instr, which doesn't require characters in the search string to be escaped. Note: instr is available starting from Sqlite 3.7.15.

SELECT *
  FROM TABLE  
 WHERE instr(column, 'cats') > 0;

Also, keep in mind that LIKE is case-insensitive, whereas instr is case-sensitive.

Searching a string in eclipse workspace

Press Ctrl + H, should bring up the search that will include options to search via project, directory, etc.

Ctrl + Alt + G can be used to find selected text across a workspace in eclipse.

Can I set the height of a div based on a percentage-based width?

<div><p>some unnecessary content</p></div>

div{
    border: 1px solid red;
    width: 40%;
    padding: 40%;
    box-sizing: border-box;
    position: relative;
}
p{
    position: absolute;
    top: 0;
    left: 0;
}

For this to work i think you need to define the padding to ex. top? like this:

<div><p>some unnecessary content</p></div>

div{
    border: 1px solid red;
    width: 40%;
    padding-top: 40%;
    box-sizing: border-box;
    position: relative;
}
p{
    position: absolute;
    top: 0;
    left: 0;
}

anyways, thats how i got it to work, since with just padding all arround it would not be a square.

What does the Ellipsis object do?

This came up in another question recently. I'll elaborate on my answer from there:

Ellipsis is an object that can appear in slice notation. For example:

myList[1:2, ..., 0]

Its interpretation is purely up to whatever implements the __getitem__ function and sees Ellipsis objects there, but its main (and intended) use is in the numpy third-party library, which adds a multidimensional array type. Since there are more than one dimensions, slicing becomes more complex than just a start and stop index; it is useful to be able to slice in multiple dimensions as well. E.g., given a 4x4 array, the top left area would be defined by the slice [:2,:2]:

>>> a
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12],
       [13, 14, 15, 16]])

>>> a[:2,:2]  # top left
array([[1, 2],
       [5, 6]])

Extending this further, Ellipsis is used here to indicate a placeholder for the rest of the array dimensions not specified. Think of it as indicating the full slice [:] for all the dimensions in the gap it is placed, so for a 3d array, a[...,0] is the same as a[:,:,0] and for 4d, a[:,:,:,0], similarly, a[0,...,0] is a[0,:,:,0] (with however many colons in the middle make up the full number of dimensions in the array).

Interestingly, in python3, the Ellipsis literal (...) is usable outside the slice syntax, so you can actually write:

>>> ...
Ellipsis

Other than the various numeric types, no, I don't think it's used. As far as I'm aware, it was added purely for numpy use and has no core support other than providing the object and corresponding syntax. The object being there didn't require this, but the literal "..." support for slices did.

POST an array from an HTML form without javascript

You can also post multiple inputs with the same name and have them save into an array by adding empty square brackets to the input name like this:

<input type="text" name="comment[]" value="comment1"/>
<input type="text" name="comment[]" value="comment2"/>
<input type="text" name="comment[]" value="comment3"/>
<input type="text" name="comment[]" value="comment4"/>

If you use php:

print_r($_POST['comment']) 

you will get this:

Array ( [0] => 'comment1' [1] => 'comment2' [2] => 'comment3' [3] => 'comment4' )

Combine two (or more) PDF's

I've done this with PDFBox. I suppose it works similarly to iTextSharp.

Converting Swagger specification JSON to HTML documentation

For Swagger API 3.0, generating Html2 client code from online Swagger Editor works great for me!

no operator "<<" matches these operands

It looks like you're comparing strings incorrectly. To compare a string to another, use the std::string::compare function.

Example

     while ((wrong < MAX_WRONG) && (soFar.compare(THE_WORD) != 0)) 

What is the Java equivalent of PHP var_dump?

Your alternatives are to override the toString() method of your object to output its contents in a way that you like, or to use reflection to inspect the object (in a way similar to what debuggers do).

The advantage of using reflection is that you won't need to modify your individual objects to be "analysable", but there is added complexity and if you need nested object support you'll have to write that.

This code will list the fields and their values for an Object "o"

Field[] fields = o.getClass().getDeclaredFields();
for (int i=0; i<fields.length; i++)
{
    System.out.println(fields[i].getName() + " - " + fields[i].get(o));
}

How does C#'s random number generator work?

I've been searching the internet for RNG for a while now. Everything I saw was either TOO complex or was just not what I was looking for. After reading a few articles I was able to come up with this simple code.

{
  Random rnd = new Random(DateTime.Now.Millisecond);
  int[] b = new int[10] { 5, 8, 1, 7, 3, 2, 9, 0, 4, 6 };
  textBox1.Text = Convert.ToString(b[rnd.Next(10)])
}

Simple explanation,

  1. create a 1 dimensional integer array.
  2. full up the array with unordered numbers.
  3. use the rnd.Next to get the position of the number that will be picked.

This works well.

To obtain a random number less than 100 use

{
  Random rnd = new Random(DateTime.Now.Millisecond);
  int[] b = new int[10] { 5, 8, 1, 7, 3, 2, 9, 0, 4, 6 };
  int[] d = new int[10] { 9, 4, 7, 2, 8, 0, 5, 1, 3, 4 };
  textBox1.Text = Convert.ToString(b[rnd.Next(10)]) + Convert.ToString(d[rnd.Next(10)]);
}

and so on for 3, 4, 5, and 6 ... digit random numbers.

Hope this assists someone positively.

How to create two columns on a web page?

i recommend to look this article

http://www.456bereastreet.com/lab/developing_with_web_standards/csslayout/2-col/

see 4. Place the columns side by side special

To make the two columns (#main and #sidebar) display side by side we float them, one to the left and the other to the right. We also specify the widths of the columns.

    #main {
    float:left;
    width:500px;
    background:#9c9;
    }
    #sidebar {
    float:right;
    width:250px;
   background:#c9c;
   }

Note that the sum of the widths should be equal to the width given to #wrap in Step 3.

How to get a complete list of object's methods and attributes?

For the complete list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the getattr built-in function. As the user can reimplement __getattr__, suddenly allowing any kind of attribute, there is no possible generic way to generate that list. The dir function returns the keys in the __dict__ attribute, i.e. all the attributes accessible if the __getattr__ method is not reimplemented.

For the second question, it does not really make sense. Actually, methods are callable attributes, nothing more. You could though filter callable attributes, and, using the inspect module determine the class methods, methods or functions.

Command to list all files in a folder as well as sub-folders in windows

Following commands we can use for Linux or Mac. For Windows we can use below on git bash.

List all files, first level folders, and their contents

ls * -r

List all first-level subdirectories and files

file */*

Save file list to text

file */* *>> ../files.txt
file */* -r *>> ../files-recursive.txt

Get everything

find . -type f

Save everything to file

find . -type f > ../files-all.txt

How to format number of decimal places in wpf using style/template?

The accepted answer does not show 0 in integer place on giving input like 0.299. It shows .3 in WPF UI. So my suggestion to use following string format

<TextBox Text="{Binding Value,  StringFormat={}{0:#,0.0}}" 

How do I run Redis on Windows?

If you're happy with a bit of Powershell, you can also get very up-to-date Windows binaries using Powershell and chocolatey.

First, add chocolatey to Powershell following the instructions here (one simple command line as admin): https://chocolatey.org/

@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin

Then, use Powershell to get the redis package from chocolatey: http://chocolatey.org/packages/redis-64

choco install redis-64

Redis will be installed in something like C:\ProgramData\chocolatey\lib\redis-64.2.8.9

Windows PowerShell Copyright (C) 2013 Microsoft Corporation. All rights reserved.

PS C:\windows\system32> choco install redis-64 Chocolatey (v0.9.8.27) is installing 'redis-64' and dependencies. By installing you accept the license for 'redis-64' an d each dependency you are installing.

redis-64 v2.8.9 Added C:\ProgramData\chocolatey\bin\redis-benchmark.exe shim pointed to '..\lib\redis-64.2.8.9\redis-benchmark.exe'. Added C:\ProgramData\chocolatey\bin\redis-check-aof.exe shim pointed to '..\lib\redis-64.2.8.9\redis-check-aof.exe'. Added C:\ProgramData\chocolatey\bin\redis-check-dump.exe shim pointed to '..\lib\redis-64.2.8.9\redis-check-dump.exe'. Added C:\ProgramData\chocolatey\bin\redis-cli.exe shim pointed to '..\lib\redis-64.2.8.9\redis-cli.exe'. Added C:\ProgramData\chocolatey\bin\redis-server.exe shim pointed to '..\lib\redis-64.2.8.9\redis-server.exe'. Finished installing 'redis-64' and dependencies - if errors not shown in console, none detected. Check log for errors if unsure

Then run the server with

redis-server

Or the CLI with

redis-cli

Follow the instructions in C:\ProgramData\chocolatey\lib\redis-64.2.8.9\RedisService.docx to install the redis service

How can I remove a key from a Python dictionary?

You can use a dictionary comprehension to create a new dictionary with that key removed:

>>> my_dict = {k: v for k, v in my_dict.items() if k != 'key'}

You can delete by conditions. No error if key doesn't exist.

Store JSON object in data attribute in HTML jQuery

For the record, I found the following code works. It enables you to retrieve the array from the data tag, push a new element on, and store it back in the data tag in the correct JSON format. The same code can therefore be used again to add further elements to the array if desired. I found that $('#my-data-div').attr('data-namesarray', names_string); correctly stores the array, but $('#my-data-div').data('namesarray', names_string); doesn't work.

<div id="my-data-div" data-namesarray='[]'></div>

var names_array = $('#my-data-div').data('namesarray');
names_array.push("Baz Smith");
var names_string = JSON.stringify(names_array);
$('#my-data-div').attr('data-namesarray', names_string);

How do you configure HttpOnly cookies in tomcat / java webapps?

For session cookies it doesn't seem to be supported in Tomcat yet. See the bug report Need to add support for HTTPOnly session cookie parameter. A somewhat involved work-around for now can be found here, which basically boils down to manually patching Tomcat. Can't really find an easy way to do it at this moment at this point I'm affraid.

To summarize the work-around, it involves downloading the 5.5 source, and then change the source in the following places:

org.apache.catalina.connector.Request.java

//this is what needs to be changed
//response.addCookieInternal(cookie);

//this is whats new
response.addCookieInternal(cookie, true);
}

org.apache.catalina.connectorResponse.addCookieInternal

public void addCookieInternal(final Cookie cookie) {
addCookieInternal(cookie, false);
}

public void addCookieInternal(final Cookie cookie, boolean HTTPOnly) {

if (isCommitted())
return;

final StringBuffer sb = new StringBuffer();
//web application code can receive a IllegalArgumentException
//from the appendCookieValue invokation
if (SecurityUtil.isPackageProtectionEnabled()) {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run(){
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(),
cookie.getValue(), cookie.getPath(),
cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
return null;
}
});
} else {
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(), cookie.getValue(),
cookie.getPath(), cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
}
//of course, we really need to modify ServerCookie
//but this is the general idea
if (HTTPOnly) {
sb.append("; HttpOnly");
}

//if we reached here, no exception, cookie is valid
// the header name is Set-Cookie for both "old" and v.1 ( RFC2109 )
// RFC2965 is not supported by browsers and the Servlet spec
// asks for 2109.
addHeader("Set-Cookie", sb.toString());

cookies.add(cookie);
}

How to make ng-repeat filter out duplicate results

Here's a template-only way to do it (it's not maintaining the order, though). Plus, the result will be ordered as well, which is useful in most cases:

<select ng-model="orderProp" >
   <option ng-repeat="place in places | orderBy:'category' as sortedPlaces" data-ng-if="sortedPlaces[$index-1].category != place.category" value="{{place.category}}">
      {{place.category}}
   </option>
</select>

Why do we have to specify FromBody and FromUri?

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).

At most one parameter is allowed to read from the message body. So this will not work:

// Caution: Will not work!    
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }

The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.

Please go through the website for more details: https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Run a controller function whenever a view is opened/shown

I faced at the same problem, and here i leave the reason of this behavior for everyone else with the same issue.

View LifeCycle

In order to improve performance, we've improved Ionic's ability to cache view elements and scope data. Once a controller is initialized, it may persist throughout the app’s life; it’s just hidden and removed from the watch cycle. Since we aren’t rebuilding scope, we’ve added events for which we should listen when entering the watch cycle again.

To see full description and $ionicView events go to: http://ionicframework.com/blog/navigating-the-changes/

Java Webservice Client (Best way)

Some ideas in the following answer:

Steps in creating a web service using Axis2 - The client code

Gives an example of a Groovy client invoking the ADB classes generated from the WSDL.

There are lots of web service frameworks out there...

Iterating through struct fieldnames in MATLAB

You have to use curly braces ({}) to access fields, since the fieldnames function returns a cell array of strings:

for i = 1:numel(fields)
  teststruct.(fields{i})
end

Using parentheses to access data in your cell array will just return another cell array, which is displayed differently from a character array:

>> fields(1)  % Get the first cell of the cell array

ans = 

    'a'       % This is how the 1-element cell array is displayed

>> fields{1}  % Get the contents of the first cell of the cell array

ans =

a             % This is how the single character is displayed

How do I remove lines between ListViews on Android?

If this android:divider="@null" doesn't work, maybe changing your ListViews for Recycler Views? 

How to search in array of object in mongodb

as explained in above answers Also, to return only one field from the entire array you can use projection into find. and use $

db.getCollection("sizer").find(
  { awards: { $elemMatch: { award: "National Medal", year: 1975 } } },
  { "awards.$": 1, name: 1 }
);

will be reutrn

{
    _id: 1,
    name: {
        first: 'John',
        last: 'Backus'
    },
    awards: [
        {
            award: 'National Medal',
            year: 1975,
            by: 'NSF'
        }
    ]
}

Change One Cell's Data in mysql

UPDATE only changes the values you specify:

UPDATE table SET cell='new_value' WHERE whatever='somevalue'

What is parsing in terms that a new programmer would understand?

Have them try to write a program that can evaluate arbitrary simple arithmetic expressions. This is a simple problem to understand but as you start getting deeper into it a lot of basic parsing starts to make sense.

Java Garbage Collection Log messages

I just wanted to mention that one can get the detailed GC log with the

-XX:+PrintGCDetails 

parameter. Then you see the PSYoungGen or PSPermGen output like in the answer.

Also -Xloggc:gc.log seems to generate the same output like -verbose:gc but you can specify an output file in the first.

Example usage:

java -Xloggc:./memory.log -XX:+PrintGCDetails Memory

To visualize the data better you can try gcviewer (a more recent version can be found on github).

Take care to write the parameters correctly, I forgot the "+" and my JBoss would not start up, without any error message!

Convert timedelta to total seconds

You have a problem one way or the other with your datetime.datetime.fromtimestamp(time.mktime(time.gmtime())) expression.

(1) If all you need is the difference between two instants in seconds, the very simple time.time() does the job.

(2) If you are using those timestamps for other purposes, you need to consider what you are doing, because the result has a big smell all over it:

gmtime() returns a time tuple in UTC but mktime() expects a time tuple in local time.

I'm in Melbourne, Australia where the standard TZ is UTC+10, but daylight saving is still in force until tomorrow morning so it's UTC+11. When I executed the following, it was 2011-04-02T20:31 local time here ... UTC was 2011-04-02T09:31

>>> import time, datetime
>>> t1 = time.gmtime()
>>> t2 = time.mktime(t1)
>>> t3 = datetime.datetime.fromtimestamp(t2)
>>> print t0
1301735358.78
>>> print t1
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=9, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=0) ### this is UTC
>>> print t2
1301700663.0
>>> print t3
2011-04-02 10:31:03 ### this is UTC+1
>>> tt = time.time(); print tt
1301736663.88
>>> print datetime.datetime.now()
2011-04-02 20:31:03.882000 ### UTC+11, my local time
>>> print datetime.datetime(1970,1,1) + datetime.timedelta(seconds=tt)
2011-04-02 09:31:03.880000 ### UTC
>>> print time.localtime()
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=20, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=1) ### UTC+11, my local time

You'll notice that t3, the result of your expression is UTC+1, which appears to be UTC + (my local DST difference) ... not very meaningful. You should consider using datetime.datetime.utcnow() which won't jump by an hour when DST goes on/off and may give you more precision than time.time()

SQL Server : Columns to Rows

The opposite of this is to flatten a column into a csv eg

SELECT STRING_AGG ([value],',') FROM STRING_SPLIT('Akio,Hiraku,Kazuo', ',')

How do I "Add Existing Item" an entire directory structure in Visual Studio?

Below is the icon for the 'Show All Files', just for easy reference.

Enter image description here

Iterating through a list to render multiple widgets in Flutter?

The Dart language has aspects of functional programming, so what you want can be written concisely as:

List<String> list = ['one', 'two', 'three', 'four'];
List<Widget> widgets = list.map((name) => new Text(name)).toList();

Read this as "take each name in list and map it to a Text and form them back into a List".

How to autoplay HTML5 mp4 video on Android?

Android actually has an API for this! The method is setMediaPlaybackRequiresUserGesture(). I found it after a lot of digging into video autoplay and a lot of attempted hacks from SO. Here's an example from blair vanderhoof:

package com.example.myProject;

import android.os.Bundle;
import org.apache.cordova.*;
import android.webkit.WebSettings;

public class myProject extends CordovaActivity 
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        super.init();
        // Set by <content src="index.html" /> in config.xml
        super.loadUrl(Config.getStartUrl());
        //super.loadUrl("file:///android_asset/www/index.html");

        WebSettings ws = super.appView.getSettings();
        ws.setMediaPlaybackRequiresUserGesture(false);
    }
}

jquery clear input default value

Try that:

  var defaultEmailNews = "Email address";
  $('input[name=email]').focus(function() {
    if($(this).val() == defaultEmailNews) $(this).val("");
  });

  $('input[name=email]').focusout(function() {
    if($(this).val() == "") $(this).val(defaultEmailNews);
  });

How do I initialize Kotlin's MutableList to empty MutableList?

I do like below to :

var book: MutableList<Books> = mutableListOf()

/** Returns a new [MutableList] with the given elements. */

public fun <T> mutableListOf(vararg elements: T): MutableList<T>
    = if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))

How to use XPath contains() here?

This is a new answer to an old question about a common misconception about contains() in XPath...

Summary: contains() means contains a substring, not contains a node.

Detailed Explanation

This XPath is often misinterpreted:

//ul[contains(li, 'Model')]

Wrong interpretation: Select those ul elements that contain an li element with Model in it.

This is wrong because

  1. contains(x,y) expects x to be a string, and
  2. the XPath rule for converting multiple elements to a string is this:

    A node-set is converted to a string by returning the string-value of the node in the node-set that is first in document order. If the node-set is empty, an empty string is returned.

Right interpretation: Select those ul elements whose first li child has a string-value that contains a Model substring.

Examples

XML

<r>
  <ul id="one">
    <li>Model A</li>
    <li>Foo</li>
  </ul>
  <ul id="two">
    <li>Foo</li>
    <li>Model A</li>
  </ul>
</r> 

XPaths

  • //ul[contains(li, 'Model')] selects the one ul element.

    Note: The two ul element is not selected because the string-value of the first li child of the two ul is Foo, which does not contain the Model substring.

  • //ul[li[contains(.,'Model')]] selects the one and two ul elements.

    Note: Both ul elements are selected because contains() is applied to each li individually. (Thus, the tricky multiple-element-to-string conversion rule is avoided.) Both ul elements do have an li child whose string value contains the Model substring -- position of the li element no longer matters.

See also

Remove all non-"word characters" from a String in Java, leaving accented characters?

I was trying to achieve the exact opposite when I bumped on this thread. I know it's quite old, but here's my solution nonetheless. You can use blocks, see here. In this case, compile the following code (with the right imports):

> String s = "äêìóblah"; 
> Pattern p = Pattern.compile("[\\p{InLatin-1Supplement}]+"); // this regex uses a block
> Matcher m = p.matcher(s);
> System.out.println(m.find());
> System.out.println(s.replaceAll(p.pattern(), "#"));

You should see the following output:

true

#blah

Best,

delete a column with awk or sed

GNU awk 4.1

awk -i inplace NF--

This will remove the last field of each line.

How to horizontally center a floating element of a variable width?

Assuming the element which is floated and will be centered is a div with an id="content" ...

<body>
<div id="wrap">
   <div id="content">
   This will be centered
   </div>
</div>
</body>

And apply the following CSS:

#wrap {
    float: left;
    position: relative;
    left: 50%;
}

#content {
    float: left;
    position: relative;
    left: -50%;
}

Here is a good reference regarding that.

APT command line interface-like yes/no input?

A very simple (but not very sophisticated) way of doing this for a single choice would be:

msg = 'Shall I?'
shall = input("%s (y/N) " % msg).lower() == 'y'

You could also write a simple (slightly improved) function around this:

def yn_choice(message, default='y'):
    choices = 'Y/n' if default.lower() in ('y', 'yes') else 'y/N'
    choice = input("%s (%s) " % (message, choices))
    values = ('y', 'yes', '') if choices == 'Y/n' else ('y', 'yes')
    return choice.strip().lower() in values

Note: On Python 2, use raw_input instead of input.

How to differentiate single click event and double click event?

Another simple Vanilla solution based on the A1rPun answer (see his fiddle for the jQuery solution, and both are in this one).

It seems that to NOT trigger a single-click handler when the user double-clicks, the single-click handler is necessarily triggered after a delay...

var single = function(e){console.log('single')},
    double = function(e){console.log('double')};

var makeDoubleClick = function(e) {

  var clicks = 0,
      timeout;

  return function (e) {

    clicks++;

    if (clicks == 1) {
      timeout = setTimeout(function () {
        single(e);
        clicks = 0;
      }, 250);
    } else {
      clearTimeout(timeout);
      double(e);
      clicks = 0;
    }
  };
}
document.getElementById('btnVanilla').addEventListener('click', makeDoubleClick(), false);

How to calculate sum of a formula field in crystal Reports?

(Assuming you are looking at the reports in the Crystal Report Designer...)

Your menu options might be a little different depending on the version of Crystal Reports you're using, but you can either:

  • Make a summary field: Right-click on the desired formula field in your detail section and choose "Insert Summary". Choose "sum" from the drop-down box and verify that the correct account grouping is selected, then click OK. You will then have a simple sum field in your group footer section.
  • Make a running total field: Click on the "Insert" menu and choose "Running Total Field..."*** Click on the New button and give your new running total field a name. Choose your formula field under "Field to summarize" and choose "sum" under "Type of Summary". Here you can also change when the total is evaluated and reset, leave these at their default if you're wanting a sum on each record. You can also use a formula to determine when a certain field should be counted in the total. (Evaluate: Use Formula)

React: "this" is undefined inside a component function

You should notice that this depends on how function is invoked ie: when a function is called as a method of an object, its this is set to the object the method is called on.

this is accessible in JSX context as your component object, so you can call your desired method inline as this method.

If you just pass reference to function/method, it seems that react will invoke it as independent function.

onClick={this.onToggleLoop} // Here you just passing reference, React will invoke it as independent function and this will be undefined

onClick={()=>this.onToggleLoop()} // Here you invoking your desired function as method of this, and this in that function will be set to object from that function is called ie: your component object

ReflectionException: Class ClassName does not exist - Laravel

If the issue is not resolved by composer dump-autoload or is not a newly created class.

Check for syntax errors in your class and its traits as well. In my case, there was a syntax error in a Trait, but ReflectionException was shown for the actual Class using that Trait instead.

javax.persistence.NoResultException: No entity found for query

String hql="from DrawUnusedBalance where unusedBalanceDate= :today";
DrawUnusedBalance drawUnusedBalance = em.unwrap(Session.class)
    .createQuery(hql, DrawUnusedBalance.class)
    .setParameter("today",new LocalDate())
    .uniqueResultOptional()
    .orElseThrow(NotFoundException::new);

How to delete from select in MySQL?

DELETE 
  p1
  FROM posts AS p1 
CROSS JOIN (
  SELECT ID FROM posts GROUP BY id HAVING COUNT(id) > 1
) AS p2
USING (id)

What is the difference between const and readonly in C#?

const: Can't be changed anywhere.

readonly: This value can only be changed in the constructor. Can't be changed in normal functions.

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

Let me know if this works. Way to detect an Apple device (Mac computers, iPhones, etc.) with help from StackOverflow.com:
What is the list of possible values for navigator.platform as of today?

var deviceDetect = navigator.platform;
var appleDevicesArr = ['MacIntel', 'MacPPC', 'Mac68K', 'Macintosh', 'iPhone', 
'iPod', 'iPad', 'iPhone Simulator', 'iPod Simulator', 'iPad Simulator', 'Pike 
v7.6 release 92', 'Pike v7.8 release 517'];

// If on Apple device
if(appleDevicesArr.includes(deviceDetect)) {
    // Execute code
}
// If NOT on Apple device
else {
    // Execute code
}

Calculate distance between two points in google maps V3

//p1 and p2 are google.maps.LatLng(x,y) objects

function calcDistance(p1, p2) {
          var d = (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
          console.log(d);              
}

Unable to capture screenshot. Prevented by security policy. Galaxy S6. Android 6.0

Go to Phone Settings --> Developer Options --> Simulate Secondary Displays and turn it to None. If you don't see Developer Options in the settings menu (it should be at the bottom, go Settings ==> About phone and tap on the Build number a lot of times)

How can I exclude multiple folders using Get-ChildItem -exclude?

I know this is quite old - but searching for an easy solution, I stumbled over this thread... If I got the question right, you were looking for a way to list more than one directory using Get-ChildItem. There seems to be a much easier way using powershell 5.0 - example

Get-ChildItem -Path D:\ -Directory -Name -Exclude tmp,music
   chaos
   docs
   downloads
   games
   pics
   videos

Without the -Exclude clause, tmp and music would still be in that list. If you don't use -Name the -Exclude clause won't work, because of the detailed output of Get-ChildItem. Hope this helps some people that are looking for an easy way to list all directory names without certain ones.

How to set socket timeout in C when making multiple connections?

Can't you implement your own timeout system?

Keep a sorted list, or better yet a priority heap as Heath suggests, of timeout events. In your select or poll calls use the timeout value from the top of the timeout list. When that timeout arrives, do that action attached to that timeout.

That action could be closing a socket that hasn't connected yet.

Stop all active ajax requests in jQuery

I found it too easy for multiple requests.

step1: define a variable at top of page:

  xhrPool = []; // no need to use **var**

step2: set beforeSend in all ajax requests:

  $.ajax({
   ...
   beforeSend: function (jqXHR, settings) {
        xhrPool.push(jqXHR);
    },
    ...

step3: use it whereever you required:

   $.each(xhrPool, function(idx, jqXHR) {
          jqXHR.abort();
    });

Get last n lines of a file, similar to tail

If reading the whole file is acceptable then use a deque.

from collections import deque
deque(f, maxlen=n)

Prior to 2.6, deques didn't have a maxlen option, but it's easy enough to implement.

import itertools
def maxque(items, size):
    items = iter(items)
    q = deque(itertools.islice(items, size))
    for item in items:
        del q[0]
        q.append(item)
    return q

If it's a requirement to read the file from the end, then use a gallop (a.k.a exponential) search.

def tail(f, n):
    assert n >= 0
    pos, lines = n+1, []
    while len(lines) <= n:
        try:
            f.seek(-pos, 2)
        except IOError:
            f.seek(0)
            break
        finally:
            lines = list(f)
        pos *= 2
    return lines[-n:]

python requests get cookies

If you need the path and thedomain for each cookie, which get_dict() is not exposes, you can parse the cookies manually, for instance:

[
    {'name': c.name, 'value': c.value, 'domain': c.domain, 'path': c.path}
    for c in session.cookies
]

HttpServletRequest get JSON POST data

Normaly you can GET and POST parameters in a servlet the same way:

request.getParameter("cmd");

But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.

If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:

BufferedReader reader = request.getReader();

Json post processing example (uses org.json package )

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jb.append(line);
  } catch (Exception e) { /*report an error*/ }

  try {
    JSONObject jsonObject =  HTTP.toJSONObject(jb.toString());
  } catch (JSONException e) {
    // crash and burn
    throw new IOException("Error parsing JSON request string");
  }

  // Work with the data using methods like...
  // int someInt = jsonObject.getInt("intParamName");
  // String someString = jsonObject.getString("stringParamName");
  // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
  // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
  // etc...
}

Openssl : error "self signed certificate in certificate chain"

You have a certificate which is self-signed, so it's non-trusted by default, that's why OpenSSL complains. This warning is actually a good thing, because this scenario might also rise due to a man-in-the-middle attack.

To solve this, you'll need to install it as a trusted server. If it's signed by a non-trusted CA, you'll have to install that CA's certificate as well.

Have a look at this link about installing self-signed certificates.

MySQL: ALTER TABLE if column not exists

Use the following in a stored procedure:

IF NOT EXISTS( SELECT NULL
            FROM INFORMATION_SCHEMA.COLUMNS
           WHERE table_name = 'tablename'
             AND table_schema = 'db_name'
             AND column_name = 'columnname')  THEN

  ALTER TABLE `TableName` ADD `ColumnName` int(1) NOT NULL default '0';

END IF;

how to convert integer to string?

NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];

How can I set the focus (and display the keyboard) on my EditText programmatically

I tried the top answer by David Merriman and it also didn't work in my case. But I found the suggestion to run this code delayed here and it works like a charm.

val editText = view.findViewById<View>(R.id.settings_input_text)

editText.postDelayed({
    editText.requestFocus()

    val imm = context.getSystemService(INPUT_METHOD_SERVICE) as? InputMethodManager
    imm?.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT)
}, 100)

How to set the value of a hidden field from a controller in mvc

You need to write following code on controller suppose test is model, and Name, Address are field of this model.

public ActionResult MyMethod()
{
    Test test=new Test();
    var test.Name="John";
    return View(test);   
}

now use like like this on your view to give set value of hidden variable.

@model YourApplicationName.Model.Test

@Html.HiddenFor(m=>m.Name,new{id="hdnFlag"})

This will automatically set hidden value=john.

What is the difference between readonly="true" & readonly="readonly"?

This is a property setting rather than a valued attribute

These property settings are values per see and don't need any assignments to them. When they are present, an element has this boolean property set to true, when they're absent they're false.

<input type="text" readonly />

It's actually browsers that are liberal toward value assignment to them. If you assign any value to them it will simply get ignored. Browsers will only see the presence of a particular property and ignore the value you're trying to assign to them.

This is of course good, because some frameworks don't have the ability to add such properties without providing their value along with them. Asp.net MVC Html helpers are one of them. jQuery used to be the same until version 1.6 where they added the concept of properties.

There are of course some implications that are related to XHTML as well, because attributes in XML need values in order to be well formed. But that's a different story. Hence browsers have to ignore value assignments.

Anyway. Never mind the value you're assigning to them as long as the name is correctly spelled so it will be detected by browsers. But for readability and maintainability it's better to assign meaningful values to them like:

readonly="true" <-- arguably best human readable
readonly="readonly"

as opposed to

readonly="johndoe"
readonly="01/01/2000"

that may confuse future developers maintaining your code and may interfere with future specification that may define more strict rules to such property settings.

How to upgrade Python version to 3.7?

On ubuntu you can add this PPA Repository and use it to install python 3.7: https://launchpad.net/~jonathonf/+archive/ubuntu/python-3.7

Or a different PPA that provides several Python versions is Deadsnakes: https://launchpad.net/~deadsnakes/+archive/ubuntu/ppa

See also here: https://askubuntu.com/questions/865554/how-do-i-install-python-3-6-using-apt-get (I know it says 3.6 in the url, but the deadsnakes ppa also contains 3.7 so you can use it for 3.7 just the same)

If you want "official" you'd have to install it from the sources from the site, get the code (which you already downloaded) and do this:

tar -xf Python-3.7.0.tar.xz
cd Python-3.7.0
./configure
make
sudo make install        <-- sudo is required.

This might take a while

How can I reference a dll in the GAC from Visual Studio?

The relevant files and references can be found here:

http://msdn.microsoft.com/en-us/library/cc283981.aspx

Note the links off it about implementation/etc.

Hiding a button in Javascript

<script>
    $('#btn_hide').click( function () {
      $('#btn_hide').hide();
    });
</script>
<input type="button" id="btn_hide"/>

this will be enough

How do I authenticate a WebClient request?

This helped me to call API that was using cookie authentication. I have passed authorization in header like this:

request.Headers.Set("Authorization", Utility.Helper.ReadCookie("AuthCookie"));

complete code:

// utility method to read the cookie value:
        public static string ReadCookie(string cookieName)
        {
            var cookies = HttpContext.Current.Request.Cookies;
            var cookie = cookies.Get(cookieName);
            if (cookie != null)
                return cookie.Value;
            return null;
        }

// using statements where you are creating your webclient
using System.Web.Script.Serialization;
using System.Net;
using System.IO;

// WebClient:

var requestUrl = "<API_url>";
var postRequest = new ClassRoom { name = "kushal seth" };

using (var webClient = new WebClient()) {
      JavaScriptSerializer serializer = new JavaScriptSerializer();
      byte[] requestData = Encoding.ASCII.GetBytes(serializer.Serialize(postRequest));
      HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
      request.Method = "POST";
      request.ContentType = "application/json";                        
      request.ContentLength = requestData.Length;
      request.ContentType = "application/json";
      request.Expect = "application/json";
      request.Headers.Set("Authorization", Utility.Helper.ReadCookie("AuthCookie"));
      request.GetRequestStream().Write(requestData, 0, requestData.Length);

      using (var response = (HttpWebResponse)request.GetResponse()) {
         var reader = new StreamReader(response.GetResponseStream());
         var objText = reader.ReadToEnd(); // objText will have the value
      }
}


Array.push() if does not exist?

Like this?

var item = "Hello World";
var array = [];
if (array.indexOf(item) === -1) array.push(item);

With object

var item = {name: "tom", text: "tasty"}
var array = [{}]
if (!array.find(o => o.name === 'tom' && o.text === 'tasty'))
    array.push(item)

Adb over wireless without usb cable at all for not rooted phones

There are actually apps on the Play store to enable wifi connections automatically. You'll need root though to do it without a cable. The top choices in https://play.google.com/store/search?q=adb%20wireless all have root and non-root options. Without root you'll need to connect your cable as before; with root you can just enable the app. That saves you having to mess with the Bluetooth option.

If you also add adb to your system path on windows it makes connecting via wifi very quick and easy. Enable the app and type one line in any terminal window and you're connected.

How to iterate through a list of dictionaries in Jinja template?

As a sidenote to @Navaneethan 's answer, Jinja2 is able to do "regular" item selections for the list and the dictionary, given we know the key of the dictionary, or the locations of items in the list.

Data:

parent_dict = [{'A':'val1','B':'val2', 'content': [["1.1", "2.2"]]},{'A':'val3','B':'val4', 'content': [["3.3", "4.4"]]}]

in Jinja2 iteration:

{% for dict_item in parent_dict %}
   This example has {{dict_item['A']}} and {{dict_item['B']}}:
       with the content --
       {% for item in dict_item['content'] %}{{item[0]}} and {{item[1]}}{% endfor %}.
{% endfor %}

The rendered output:

This example has val1 and val2:
    with the content --
    1.1 and 2.2.

This example has val3 and val4:
   with the content --
   3.3 and 4.4.

Is it possible to have a multi-line comments in R?

if(FALSE) {
...
}

precludes multiple lines from being executed. However, these lines still have to be syntactically correct, i.e., can't be comments in the proper sense. Still helpful for some cases though.

PowerShell and the -contains operator

The -Contains operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections.

From the documentation you linked to:

-Contains Description: Containment operator. Tells whether a collection of reference values includes a single test value.

In the example you provided you're working with a collection containing just one string item.

If you read the documentation you linked to you'll see an example that demonstrates this behaviour:

Examples:

PS C:\> "abc", "def" -Contains "def"
True

PS C:\> "Windows", "PowerShell" -Contains "Shell"
False  #Not an exact match

I think what you want is the -Match operator:

"12-18" -Match "-"

Which returns True.

Important: As pointed out in the comments and in the linked documentation, it should be noted that the -Match operator uses regular expressions to perform text matching.

Exec : display stdout "live"

Here is an async helper function written in typescript that seems to do the trick for me. I guess this will not work for long-lived processes but still might be handy for someone?

import * as child_process from "child_process";

private async spawn(command: string, args: string[]): Promise<{code: number | null, result: string}> {
    return new Promise((resolve, reject) => {
        const spawn = child_process.spawn(command, args)
        let result: string
        spawn.stdout.on('data', (data: any) => {
            if (result) {
                reject(Error('Helper function does not work for long lived proccess'))
            }
            result = data.toString()
        })
        spawn.stderr.on('data', (error: any) => {
            reject(Error(error.toString()))
        })
        spawn.on('exit', code => {
            resolve({code, result})
        })
    })
}

How can I copy columns from one sheet to another with VBA in Excel?

The following works fine for me in Excel 2007. It is simple, and performs a full copy (retains all formatting, etc.):

Sheets("Sheet1").Columns(1).Copy Destination:=Sheets("Sheet2").Columns(2)

"Columns" returns a Range object, and so this is utilizing the "Range.Copy" method. "Destination" is an option to this method - if not provided the default is to copy to the paste buffer. But when provided, it is an easy way to copy.

As when manually copying items in Excel, the size and geometry of the destination must support the range being copied.

In Rails, how do you render JSON using a view?

This is potentially a better option and faster than ERB: https://github.com/dewski/json_builder

How do I select a random value from an enumeration?

Use Enum.GetValues to retrieve an array of all values. Then select a random array item.

static Random _R = new Random ();
static T RandomEnumValue<T> ()
{
    var v = Enum.GetValues (typeof (T));
    return (T) v.GetValue (_R.Next(v.Length));
}

Test:

for (int i = 0; i < 10; i++) {
    var value = RandomEnumValue<System.DayOfWeek> ();
    Console.WriteLine (value.ToString ());
}

->

Tuesday
Saturday
Wednesday
Monday
Friday
Saturday
Saturday
Saturday
Friday
Wednesday

How to switch between frames in Selenium WebDriver using Java

First you have to locate the frame id and define it in a WebElement

For ex:- WebElement fr = driver.findElementById("id");

Then switch to the frame using this code:- driver.switchTo().frame("Frame_ID");

An example script:-

WebElement fr = driver.findElementById("theIframe");

driver.switchTo().frame(fr);

Then to move out of frame use:- driver.switchTo().defaultContent();

Is it possible to make Font Awesome icons larger than 'fa-5x'?

  1. Just add the font awesome class like this:

    class="fa fa-plus-circle fa-3x"
    

    (You can increase the size as per 5x, 7x, 9x..)

  2. You can also add custom CSS.

Version vs build in Xcode

Another way is to set the version number in appDelegate didFinishLaunchingWithOptions:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
     NSString * ver = [self myVersion];
     NSLog(@"version: %@",ver);

     NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
     [userDefaults setObject:ver forKey:@"version"];
     return YES;
}

- (NSString *) myVersion {
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    return [NSString stringWithFormat:@"%@ build %@", version, build];
}

setting JAVA_HOME & CLASSPATH in CentOS 6

Search here for centos jre install all users:

The easiest way to set an environment variable in CentOS is to use export as in

$> export JAVA_HOME=/usr/java/jdk.1.5.0_12

$> export PATH=$PATH:$JAVA_HOME

However, variables set in such a manner are transient i.e. they will disappear the moment you exit the shell. Obviously this is not helpful when setting environment variables that need to persist even when the system reboots. In such cases, you need to set the variables within the system wide profile. In CentOS (I’m using v5.2), the folder /etc/profile.d/ is the recommended place to add customizations to the system profile. For example, when installing the Sun JDK, you might need to set the JAVA_HOME and JRE_HOME environment variables. In this case: Create a new file called java.sh

vim /etc/profile.d/java.sh

Within this file, initialize the necessary environment variables

export JRE_HOME=/usr/java/jdk1.5.0_12/jre
export PATH=$PATH:$JRE_HOME/bin

export JAVA_HOME=/usr/java/jdk1.5.0_12
export JAVA_PATH=$JAVA_HOME

export PATH=$PATH:$JAVA_HOME/bin

Now when you restart your machine, the environment variables within java.sh will be automatically initialized (checkout /etc/profile if you are curious how the files in /etc/profile.d/ are loaded).

PS: If you want to load the environment variables within java.sh without having to restart the machine, you can use the source command as in:

$> source java.sh

How to get the current user in ASP.NET MVC

If you are inside your login page, in LoginUser_LoggedIn event for instance, Current.User.Identity.Name will return an empty value, so you have to use yourLoginControlName.UserName property.

MembershipUser u = Membership.GetUser(LoginUser.UserName);

Neatest way to remove linebreaks in Perl

Whenever I go through input and want to remove or replace characters I run it through little subroutines like this one.

sub clean {

    my $text = shift;

    $text =~ s/\n//g;
    $text =~ s/\r//g;

    return $text;
}

It may not be fancy but this method has been working flawless for me for years.

How to Import .bson file format on mongodb

It's very simple to import a .bson file:

mongorestore -d db_name -c collection_name /path/file.bson

Incase only for a single collection.Try this:

mongorestore --drop -d db_name -c collection_name /path/file.bson

For restoring the complete folder exported by mongodump:

mongorestore -d db_name /path/

NSOperation vs Grand Central Dispatch

GCD is a low-level C-based API that enables very simple use of a task-based concurrency model. NSOperation and NSOperationQueue are Objective-C classes that do a similar thing. NSOperation was introduced first, but as of 10.5 and iOS 2, NSOperationQueue and friends are internally implemented using GCD.

In general, you should use the highest level of abstraction that suits your needs. This means that you should usually use NSOperationQueue instead of GCD, unless you need to do something that NSOperationQueue doesn't support.

Note that NSOperationQueue isn't a "dumbed-down" version of GCD; in fact, there are many things that you can do very simply with NSOperationQueue that take a lot of work with pure GCD. (Examples: bandwidth-constrained queues that only run N operations at a time; establishing dependencies between operations. Both very simple with NSOperation, very difficult with GCD.) Apple's done the hard work of leveraging GCD to create a very nice object-friendly API with NSOperation. Take advantage of their work unless you have a reason not to.

Caveat: On the other hand, if you really just need to send off a block, and don't need any of the additional functionality that NSOperationQueue provides, there's nothing wrong with using GCD. Just be sure it's the right tool for the job.

How to set java.net.preferIPv4Stack=true at runtime?

I ran into this very problem trying to send mail with javax.mail from a web application in a web server running Java 7. Internal mail server destinations failed with "network unreachable", despite telnet and ping working from the same host, and while external mail servers worked. I tried

System.setProperty("java.net.preferIPv4Stack" , "true");

in the code, but that failed. So the parameter value was probably cached earlier by the system. Setting the VM argument

-Djava.net.preferIPv4Stack=true

in the web server startup script worked.

One further bit of evidence: in a very small targeted test program, setting the system property in the code did work. So the parameter is probably cached when the first Socket is used, probably not just as the JVM starts.

Bad operand type for unary +: 'str'

You say that if int(splitLine[0]) > int(lastUnix): is causing the trouble, but you don't actually show anything which suggests that. I think this line is the problem instead:

print 'Pulled', + stock

Do you see why this line could cause that error message? You want either

>>> stock = "AAAA"
>>> print 'Pulled', stock
Pulled AAAA

or

>>> print 'Pulled ' + stock
Pulled AAAA

not

>>> print 'Pulled', + stock
PulledTraceback (most recent call last):
  File "<ipython-input-5-7c26bb268609>", line 1, in <module>
    print 'Pulled', + stock
TypeError: bad operand type for unary +: 'str'

You're asking Python to apply the + symbol to a string like +23 makes a positive 23, and she's objecting.

Counting lines, words, and characters within a text file using Python

Try this:

fname = "feed.txt"

num_lines = 0
num_words = 0
num_chars = 0

with open(fname, 'r') as f:
    for line in f:
        words = line.split()

        num_lines += 1
        num_words += len(words)
        num_chars += len(line)

Back to your code:

fname = "feed.txt"
fname = open('feed.txt', 'r')

what's the point of this? fname is a string first and then a file object. You don't really use the string defined in the first line and you should use one variable for one thing only: either a string or a file object.

for line in feed:
    lines = line.split('\n')

line is one line from the file. It does not make sense to split('\n') it.

Concatenating two std::vectors

I've implemented this function which concatenates any number of containers, moving from rvalue-references and copying otherwise

namespace internal {

// Implementation detail of Concatenate, appends to a pre-reserved vector, copying or moving if
// appropriate
template<typename Target, typename Head, typename... Tail>
void AppendNoReserve(Target* target, Head&& head, Tail&&... tail) {
    // Currently, require each homogenous inputs. If there is demand, we could probably implement a
    // version that outputs a vector whose value_type is the common_type of all the containers
    // passed to it, and call it ConvertingConcatenate.
    static_assert(
            std::is_same_v<
                    typename std::decay_t<Target>::value_type,
                    typename std::decay_t<Head>::value_type>,
            "Concatenate requires each container passed to it to have the same value_type");
    if constexpr (std::is_lvalue_reference_v<Head>) {
        std::copy(head.begin(), head.end(), std::back_inserter(*target));
    } else {
        std::move(head.begin(), head.end(), std::back_inserter(*target));
    }
    if constexpr (sizeof...(Tail) > 0) {
        AppendNoReserve(target, std::forward<Tail>(tail)...);
    }
}

template<typename Head, typename... Tail>
size_t TotalSize(const Head& head, const Tail&... tail) {
    if constexpr (sizeof...(Tail) > 0) {
        return head.size() + TotalSize(tail...);
    } else {
        return head.size();
    }
}

}  // namespace internal

/// Concatenate the provided containers into a single vector. Moves from rvalue references, copies
/// otherwise.
template<typename Head, typename... Tail>
auto Concatenate(Head&& head, Tail&&... tail) {
    size_t totalSize = internal::TotalSize(head, tail...);
    std::vector<typename std::decay_t<Head>::value_type> result;
    result.reserve(totalSize);
    internal::AppendNoReserve(&result, std::forward<Head>(head), std::forward<Tail>(tail)...);
    return result;
}

Can I start the iPhone simulator without "Build and Run"?

First, add the iOS Simulator to Applications:

ln -s /Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app /Applications/iPhone\ Simulator.app

From there you can open it in Finder or drag it to the launch bar.

Source: http://www.bram.us/2010/05/05/xcode-iphone-simulator-location/

How to read json file into java with simple JSON library

You can use readAllBytes.

return String(Files.readAllBytes(Paths.get(filePath)),StandardCharsets.UTF_8);