Programs & Examples On #Benchmarking

Benchmarking is the process of comparing two or more systems or processes under controlled circumstances in order to have a quantitative measure with which to compare or rank them. The benchmarking tag should be used for questions about how to perform benchmarking tasks or theory questions, not for lists of benchmarking results or requests for benchmarking data; those questions are off-topic for Stack Overflow.

Why is 2 * (i * i) faster than 2 * i * i in Java?

I tried a JMH using the default archetype: I also added an optimized version based on Runemoro's explanation.

@State(Scope.Benchmark)
@Warmup(iterations = 2)
@Fork(1)
@Measurement(iterations = 10)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
//@BenchmarkMode({ Mode.All })
@BenchmarkMode(Mode.AverageTime)
public class MyBenchmark {
  @Param({ "100", "1000", "1000000000" })
  private int size;

  @Benchmark
  public int two_square_i() {
    int n = 0;
    for (int i = 0; i < size; i++) {
      n += 2 * (i * i);
    }
    return n;
  }

  @Benchmark
  public int square_i_two() {
    int n = 0;
    for (int i = 0; i < size; i++) {
      n += i * i;
    }
    return 2*n;
  }

  @Benchmark
  public int two_i_() {
    int n = 0;
    for (int i = 0; i < size; i++) {
      n += 2 * i * i;
    }
    return n;
  }
}

The result are here:

Benchmark                           (size)  Mode  Samples          Score   Score error  Units
o.s.MyBenchmark.square_i_two           100  avgt       10         58,062         1,410  ns/op
o.s.MyBenchmark.square_i_two          1000  avgt       10        547,393        12,851  ns/op
o.s.MyBenchmark.square_i_two    1000000000  avgt       10  540343681,267  16795210,324  ns/op
o.s.MyBenchmark.two_i_                 100  avgt       10         87,491         2,004  ns/op
o.s.MyBenchmark.two_i_                1000  avgt       10       1015,388        30,313  ns/op
o.s.MyBenchmark.two_i_          1000000000  avgt       10  967100076,600  24929570,556  ns/op
o.s.MyBenchmark.two_square_i           100  avgt       10         70,715         2,107  ns/op
o.s.MyBenchmark.two_square_i          1000  avgt       10        686,977        24,613  ns/op
o.s.MyBenchmark.two_square_i    1000000000  avgt       10  652736811,450  27015580,488  ns/op

On my PC (Core i7 860 - it is doing nothing much apart from reading on my smartphone):

  • n += i*i then n*2 is first
  • 2 * (i * i) is second.

The JVM is clearly not optimizing the same way than a human does (based on Runemoro's answer).

Now then, reading bytecode: javap -c -v ./target/classes/org/sample/MyBenchmark.class

I am not expert on bytecode, but we iload_2 before we imul: that's probably where you get the difference: I can suppose that the JVM optimize reading i twice (i is already here, and there is no need to load it again) whilst in the 2*i*i it can't.

Clang vs GCC - which produces faster binaries?

There is very little overall difference between GCC 4.8 and clang 3.3 in terms of speed of the resulting binary. In most cases code generated by both compilers performs similarly. Neither of these two compilers dominates the other one.

Benchmarks telling that there is a significant performance gap between GCC and clang are coincidental.

Program performance is affected by the choice of the compiler. If a developer or a group of developers is exclusively using GCC then the program can be expected to run slightly faster with GCC than with clang, and vice versa.

From developer viewpoint, a notable difference between GCC 4.8+ and clang 3.3 is that GCC has the -Og command line option. This option enables optimizations that do not interfere with debugging, so for example it is always possible to get accurate stack traces. The absence of this option in clang makes clang harder to use as an optimizing compiler for some developers.

Which is faster: multiple single INSERTs or one multiple-row INSERT?

multiple inserts are faster but it has thredshould. another thrik is disabling constrains checks temprorary make inserts much much faster. It dosn't matter your table has it or not. For example test disabling foreign keys and enjoy the speed:

SET FOREIGN_KEY_CHECKS=0;

offcourse you should turn it back on after inserts by:

SET FOREIGN_KEY_CHECKS=1;

this is common way to inserting huge data. the data integridity may break so you shoud care of that before disabling foreign key checks.

ab load testing

The apache benchmark tool is very basic, and while it will give you a solid idea of some performance, it is a bad idea to only depend on it if you plan to have your site exposed to serious stress in production.

Having said that, here's the most common and simplest parameters:

-c: ("Concurrency"). Indicates how many clients (people/users) will be hitting the site at the same time. While ab runs, there will be -c clients hitting the site. This is what actually decides the amount of stress your site will suffer during the benchmark.

-n: Indicates how many requests are going to be made. This just decides the length of the benchmark. A high -n value with a -c value that your server can support is a good idea to ensure that things don't break under sustained stress: it's not the same to support stress for 5 seconds than for 5 hours.

-k: This does the "KeepAlive" funcionality browsers do by nature. You don't need to pass a value for -k as it it "boolean" (meaning: it indicates that you desire for your test to use the Keep Alive header from HTTP and sustain the connection). Since browsers do this and you're likely to want to simulate the stress and flow that your site will have from browsers, it is recommended you do a benchmark with this.

The final argument is simply the host. By default it will hit http:// protocol if you don't specify it.

ab -k -c 350 -n 20000 example.com/

By issuing the command above, you will be hitting http://example.com/ with 350 simultaneous connections until 20 thousand requests are met. It will be done using the keep alive header.

After the process finishes the 20 thousand requests, you will receive feedback on stats. This will tell you how well the site performed under the stress you put it when using the parameters above.

For finding out how many people the site can handle at the same time, just see if the response times (means, min and max response times, failed requests, etc) are numbers your site can accept (different sites might desire different speeds). You can run the tool with different -c values until you hit the spot where you say "If I increase it, it starts to get failed requests and it breaks".

Depending on your website, you will expect an average number of requests per minute. This varies so much, you won't be able to simulate this with ab. However, think about it this way: If your average user will be hitting 5 requests per minute and the average response time that you find valid is 2 seconds, that means that 10 seconds out of a minute 1 user will be on requests, meaning only 1/6 of the time it will be hitting the site. This also means that if you have 6 users hitting the site with ab simultaneously, you are likely to have 36 users in simulation, even though your concurrency level (-c) is only 6.

This depends on the behavior you expect from your users using the site, but you can get it from "I expect my user to hit X requests per minute and I consider an average response time valid if it is 2 seconds". Then just modify your -c level until you are hitting 2 seconds of average response time (but make sure the max response time and stddev is still valid) and see how big you can make -c.

I hope I explained this clear :) Good luck

How to use clock() in C++

#include <iostream>
#include <ctime>
#include <cstdlib> //_sleep()  --- just a function that waits a certain amount of milliseconds

using namespace std;

int main()
{

    clock_t cl;     //initializing a clock type

    cl = clock();   //starting time of clock

    _sleep(5167);   //insert code here

    cl = clock() - cl;  //end point of clock

    _sleep(1000);   //testing to see if it actually stops at the end point

    cout << cl/(double)CLOCKS_PER_SEC << endl;  //prints the determined ticks per second (seconds passed)


    return 0;
}

//outputs "5.17"

How do I write a correct micro-benchmark in Java?

http://opt.sourceforge.net/ Java Micro Benchmark - control tasks required to determine the comparative performance characteristics of the computer system on different platforms. Can be used to guide optimization decisions and to compare different Java implementations.

How much faster is C++ than C#?

It's five oranges faster. Or rather: there can be no (correct) blanket answer. C++ is a statically compiled language (but then, there's profile guided optimization, too), C# runs aided by a JIT compiler. There are so many differences that questions like “how much faster” cannot be answered, not even by giving orders of magnitude.

How to Calculate Execution Time of a Code Snippet in C++

I have another working example that uses microseconds (UNIX, POSIX, etc).

    #include <sys/time.h>
    typedef unsigned long long timestamp_t;

    static timestamp_t
    get_timestamp ()
    {
      struct timeval now;
      gettimeofday (&now, NULL);
      return  now.tv_usec + (timestamp_t)now.tv_sec * 1000000;
    }

    ...
    timestamp_t t0 = get_timestamp();
    // Process
    timestamp_t t1 = get_timestamp();

    double secs = (t1 - t0) / 1000000.0L;

Here's the file where we coded this:

https://github.com/arhuaco/junkcode/blob/master/emqbit-bench/bench.c

Execution time of C program

You have to take into account that measuring the time that took a program to execute depends a lot on the load that the machine has in that specific moment.

Knowing that, the way of obtain the current time in C can be achieved in different ways, an easier one is:

#include <time.h>

#define CPU_TIME (getrusage(RUSAGE_SELF,&ruse), ruse.ru_utime.tv_sec + \
  ruse.ru_stime.tv_sec + 1e-6 * \
  (ruse.ru_utime.tv_usec + ruse.ru_stime.tv_usec))

int main(void) {
    time_t start, end;
    double first, second;

    // Save user and CPU start time
    time(&start);
    first = CPU_TIME;

    // Perform operations
    ...

    // Save end time
    time(&end);
    second = CPU_TIME;

    printf("cpu  : %.2f secs\n", second - first); 
    printf("user : %d secs\n", (int)(end - start));
}

Hope it helps.

Regards!

What do 'real', 'user' and 'sys' mean in the output of time(1)?

In very simple terms, I like to think about it like this:

  • real is the actual amount of time it took to run the command (as if you had timed it with a stopwatch)

  • user and sys are how much 'work' the CPU had to do to execute the command. This 'work' is expressed in units of time.

Generally speaking:

  • user is how much work the CPU did to run to run the command's code
  • sys is how much work the CPU had to do to handle 'system overhead' type tasks (such as allocating memory, file I/O, ect.) in order to support the running command

Since these last two times are counting 'work' done, they don't include time a thread might have spent waiting (such as waiting on another process or for disk I/O to finish).

real, however, is a measure of actual runtime and not 'work', so it does include any time spent waiting.

How to download an entire directory and subdirectories using wget?

You can use this in a shell:

wget -r -nH --cut-dirs=7 --reject="index.html*" \
      http://abc.tamu.edu/projects/tzivi/repository/revisions/2/raw/tzivi/

The Parameters are:

-r recursively download

-nH (--no-host-directories) cuts out hostname 

--cut-dirs=X (cuts out X directories)

Multiprocessing: How to use Pool.map on a function defined in a class?

I know this was asked over 6 years ago now, but just wanted to add my solution, as some of the suggestions above seem horribly complicated, but my solution was actually very simple.

All I had to do was wrap the pool.map() call to a helper function. Passing the class object along with args for the method as a tuple, which looked a bit like this.

def run_in_parallel(args):
    return args[0].method(args[1])

myclass = MyClass()
method_args = [1,2,3,4,5,6]
args_map = [ (myclass, arg) for arg in method_args ]
pool = Pool()
pool.map(run_in_parallel, args_map)

Base64 Java encode and decode a string

Java 8 now supports BASE64 Encoding and Decoding. You can use the following classes: java.util.Base64, java.util.Base64.Encoder and java.util.Base64.Decoder.

Example usage:

// encode with padding
String encoded = Base64.getEncoder().encodeToString(someByteArray);

// encode without padding
String encoded = Base64.getEncoder().withoutPadding().encodeToString(someByteArray);

// decode a String
byte [] barr = Base64.getDecoder().decode(encoded); 

Replace Div Content onclick

Try This:

I think that you want something like this.

HTML:

<div id="1">
    My Content 1
</div>

<div id="2" style="display:none;">
    My Dynamic Content
</div>
<button id="btnClick">Click me!</button>

jQuery:

$('#btnClick').on('click',function(){
if($('#1').css('display')!='none'){
$('#2').show().siblings('div').hide();
}else if($('#2').css('display')!='none'){
    $('#1').show().siblings('div').hide();
}
});


JsFiddle:
http://jsfiddle.net/ha6qp7w4/1113/ <--- see this I hope You want something like this.

React-router urls don't work when refreshing or writing manually

I am using WebPack, I had same problem Solution=> In your server.js file

const express = require('express');
const app = express();

app.use(express.static(path.resolve(__dirname, '../dist')));
  app.get('*', function (req, res) {
    res.sendFile(path.resolve(__dirname, '../dist/index.html'));
    // res.end();
  });

Why doesn't my application render after refreshing?

INNER JOIN vs INNER JOIN (SELECT . FROM)

You are correct. You did exactly the right thing, checking the query plan rather than trying to second-guess the optimiser. :-)

Adding a SVN repository in Eclipse

Try to connect to the repository using command line SVN to see if you get a similar error.

$ svn checkout http://svn.python.org/projects/peps/trunk

If you keep getting the error, it is probably an issue with your proxy server. I have found that I can't check out internet based SVN projects at work because the firewall blocks most HTTP commands. It only allows GET, POST and others necessary for browsing.

Error Code: 1406. Data too long for column - MySQL

Try to check the limits of your SQL database. Maybe you'r exceeding the field limit for this row.

Failed linking file resources

This might be useful for someone who is looking for a different answer. Go to the Gradle Panel and select your module -> Task -> Verification -> Check. This will check the project for errors and will print the log where the error occurs. Most of the time this Kind of error must be a typo present in your XML file of your project

Setting query string using Fetch GET request

Update March 2017:

URL.searchParams support has officially landed in Chrome 51, but other browsers still require a polyfill.


The official way to work with query parameters is just to add them onto the URL. From the spec, this is an example:

var url = new URL("https://geo.example.org/api"),
    params = {lat:35.696233, long:139.570431}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url).then(/* … */)

However, I'm not sure Chrome supports the searchParams property of a URL (at the time of writing) so you might want to either use a third party library or roll-your-own solution.

Update April 2018:

With the use of URLSearchParams constructor you could assign a 2D array or a object and just assign that to the url.search instead of looping over all keys and append them

var url = new URL('https://sl.se')

var params = {lat:35.696233, long:139.570431} // or:
var params = [['lat', '35.696233'], ['long', '139.570431']]

url.search = new URLSearchParams(params).toString();

fetch(url)

Sidenote: URLSearchParams is also available in NodeJS

const { URL, URLSearchParams } = require('url');

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

I found the original answer of updating the .edmx file work best in my situation. I just wasn't too happy about altering the model every time it was updated from the database. That's why I wrote an additional Text Template file, that is automaticaly invoked when after the model has changed - just like the entities are newly generated. I post it here in this comment. To make it work, make sure you name it like {model name}.something.tt, and store it in the same folder as your .edmx folder. I named it {model name}.NonPkTables.tt. It does not generate a file on its own due to the invalid file extension definition in the second line. Feel free to use.

<#@ template language="C#" debug="false" hostspecific="true"#>
<#@ output extension="/" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Data" #>
<#@ assembly name="System.Windows.Forms" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Xml.Linq"#>
<#@ assembly name="%VS120COMNTOOLS%..\IDE\EntityFramework.dll" #>
<#@ assembly name="%VS120COMNTOOLS%..\IDE\Microsoft.Data.Entity.Design.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Windows.Forms" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.Xml.Linq" #>
<#@ import namespace="System.Globalization" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="System.Data.Entity.Core.Metadata.Edm" #>
<#@ import namespace="System.Data.Entity.Core.Mapping" #>
<#@ import namespace="System.CodeDom" #>
<#@ import namespace="System.CodeDom.Compiler" #>
<#@ import namespace="Microsoft.CSharp"#>
<#@ import namespace="System.Text"#>
<#@ import namespace="System.Diagnostics" #>

<#
    string modelFileName= this.Host.TemplateFile.Split('.')[0] + ".edmx";
    string edmxPath = this.Host.ResolvePath( modelFileName );

    // MessageBox.Show( this.Host.TemplateFile + " applied." );
    var modelDoc = XDocument.Load(edmxPath);
    var root = modelDoc.Root;
    XNamespace nsEdmx = @"http://schemas.microsoft.com/ado/2009/11/edmx";
    XNamespace ns = @"http://schemas.microsoft.com/ado/2009/11/edm/ssdl";

    var runtime = root.Elements(nsEdmx + "Runtime").First();
    var storageModels = runtime.Elements(nsEdmx + "StorageModels").First();
    XNamespace nsStore = @"http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator";

    var schema = storageModels.Elements(ns + "Schema").First();
    XNamespace nsCustomAnnotation = @"http://schemas.microsoft.com/ado/2013/11/edm/customannotation";

    var entityTypes = schema.Nodes().OfType<XComment>().Where(c => c.Value.Contains("warning 6002: The table/view"));
    bool changed = false;

    foreach (var node in entityTypes)
    {
        var element = node.ElementsAfterSelf().First();
        string entityName = element.Attribute("Name").Value;

        // Find EntitySet in EntityContainer.
        var entityContainer = schema.Elements(ns + "EntityContainer").First();
        var entitySet = entityContainer.Elements(ns + "EntitySet").First(s => s.Attribute("Name").Value == entityName);

        // Change "store:Schema" attribute to "Schema" attribute.
        var attribute = entitySet.Attribute(nsStore + "Schema");

        if (attribute != null)
        {
            string schemaName = entitySet.Attribute(nsStore + "Schema").Value;
            entitySet.Attribute(nsStore + "Schema").Remove();
            entitySet.Add(new XAttribute("Schema", schemaName));
            changed |= true;
        }

        // Remove the DefiningQuery element.
        var definingQuery = entitySet.Element(ns + "DefiningQuery");

        if (definingQuery != null)
        {
            definingQuery.Remove();
            changed |= true;        
            Debug.WriteLine(string.Format("Removed defining query of EntitySet {0}.", entityName));
        }
    }

    if (changed)
        modelDoc.Save(edmxPath);
#>

How to assert greater than using JUnit Assert?

You should add Hamcrest-library to your Build Path. It contains the needed Matchers.class which has the lessThan() method.

Dependency as below.

<dependency>
  <groupId>org.hamcrest</groupId>
  <artifactId>hamcrest-library</artifactId>
  <version>1.3</version>
  <scope>test</scope>
</dependency>

Your branch is ahead of 'origin/master' by 3 commits

Use these 4 simple commands

Step 1 : git checkout <branch_name>

This is obvious to go into that branch.

Step 2 : git pull -s recursive -X theirs

Take remote branch changes and replace with their changes if conflict arise. Here if you do git status you will get something like this your branch is ahead of 'origin/master' by 3 commits.

Step 3 : git reset --hard origin/<branch_name>

Step 4 : git fetch

Hard reset your branch.

Enjoy.

How do I find out my root MySQL password?

MySQL 5.5 on Ubuntu 14.04 required slightly different commands as recommended here. In a nutshell:

sudo /etc/init.d/mysql stop
sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &
mysql -u root

And then from the MySQL prompt

FLUSH PRIVILEGES;
SET PASSWORD FOR root@'localhost' = PASSWORD('password');
UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';
FLUSH PRIVILEGES;

And the cited source offers an alternate method as well.

Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

I actually prefer to use the display name for the placeholder text majority of the time. Here is an example of using the DisplayName:

  @Html.TextBoxFor(x => x.FirstName, true, null, new { @class = "form-control", placeholder = Html.DisplayNameFor(x => x.FirstName) })

convert array into DataFrame in Python

In general you can use pandas rename function here. Given your dataframe you could change to a new name like this. If you had more columns you could also rename those in the dictionary. The 0 is the current name of your column

import pandas as pd    
import numpy as np   
e = np.random.normal(size=100)  
e_dataframe = pd.DataFrame(e)      

e_dataframe.rename(index=str, columns={0:'new_column_name'})

python for increment inner loop

You might just be better of using while loops rather than for loops for this. I translated your code directly from the java code.

str1 = "ababa"
str2 = "aba"
i = 0

while i < len(str1):
  j = 0
  while j < len(str2):
    if not str1[i+j] == str1[j]:
      break
    if j == (len(str2) -1):
      i += len(str2)
    j+=1  
  i+=1

SQL SERVER, SELECT statement with auto generate row id

If you are making use of GUIDs this should be nice and easy, if you are looking for an integer ID, you will have to wait for another answer.

SELECT newId() AS ColId, Col1, Col2, Col3 FROM table1

The newId() will generate a new GUID for you that you can use as your automatically generated id column.

jQuery UI Dialog with ASP.NET button postback

ken's answer above did the trick for me. The problem with the accepted answer is that it only works if you have a single modal on the page. If you have multiple modals, you'll need to do it inline in the "open" param while initializing the dialog, not after the fact.

open: function(type,data) { $(this).parent().appendTo("form"); }

If you do what the first accepted answer tells you with multiple modals, you'll only get the last modal on the page working firing postbacks properly, not all of them.

CSS @media print issues with background-color;

Try this, it worked for me on Google Chrome:

<style media="print" type="text/css">
    .page {
        background-color: white !important;
    }
</style>

Caused by: java.security.UnrecoverableKeyException: Cannot recover key

In order to not have the Cannot recover key exception, I had to apply the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files to the installation of Java that was running my application. Version 8 of those files can be found here or the latest version should be listed on this page. The download includes a file that explains how to apply the policy files.


Since JDK 8u151 it isn't necessary to add policy files. Instead the JCE jurisdiction policy files are controlled by a Security property called crypto.policy. Setting that to unlimited with allow unlimited cryptography to be used by the JDK. As the release notes linked to above state, it can be set by Security.setProperty() or via the java.security file. The java.security file could also be appended to by adding -Djava.security.properties=my_security.properties to the command to start the program as detailed here.


Since JDK 8u161 unlimited cryptography is enabled by default.

Count all duplicates of each value

SELECT   col,
         COUNT(dupe_col) AS dupe_cnt
FROM     TABLE
GROUP BY col
HAVING   COUNT(dupe_col) > 1
ORDER BY COUNT(dupe_col) DESC

C# equivalent of the IsNull() function in SQL Server

It's called the null coalescing (??) operator:

myNewValue = myValue ?? new MyValue();

How can I tell if a DOM element is visible in the current viewport?

This checks if an element is at least partially in view (vertical dimension):

function inView(element) {
    var box = element.getBoundingClientRect();
    return inViewBox(box);
}

function inViewBox(box) {
    return ((box.bottom < 0) || (box.top > getWindowSize().h)) ? false : true;
}


function getWindowSize() {
    return { w: document.body.offsetWidth || document.documentElement.offsetWidth || window.innerWidth, h: document.body.offsetHeight || document.documentElement.offsetHeight || window.innerHeight}
}

How do I replace multiple spaces with a single space in C#?

I just wrote a new Join that I like, so I thought I'd re-answer, with it:

public static string Join<T>(this IEnumerable<T> source, string separator)
{
    return string.Join(separator, source.Select(e => e.ToString()).ToArray());
}

One of the cool things about this is that it work with collections that aren't strings, by calling ToString() on the elements. Usage is still the same:

//...

string s = "     1  2    4 5".Split (
    " ".ToCharArray(), 
    StringSplitOptions.RemoveEmptyEntries
    ).Join (" ");

Spring: @Component versus @Bean

Both approaches aim to register target type in Spring container.

The difference is that @Bean is applicable to methods, whereas @Component is applicable to types.

Therefore when you use @Bean annotation you control instance creation logic in method's body (see example above). With @Component annotation you cannot.

How to push changes to github after jenkins build completes?

Found an answer myself, this blog helped: http://thingsyoudidntknowaboutjenkins.tumblr.com/post/23596855946/git-plugin-part-3

Basically need to execute:

git checkout master

before modifying any files

then

git commit -am "Updated version number"

after modified files

and then use post build action of Git Publisher with an option of Merge Results which will push changes to github on successful build.

jQuery Datepicker onchange event issue

Try :

$('#idPicker').on('changeDate', function() {
    var date = $('#idPicker').datepicker('getFormattedDate');
});

How to upload image in CodeIgniter?

Simple Image upload in codeigniter

Find below code for easy image upload

public function doupload()
     {
        $upload_path="https://localhost/project/profile"  
        $uid='10'; //creare seperate folder for each user 
        $upPath=upload_path."/".$uid;
        if(!file_exists($upPath)) 
        {
                   mkdir($upPath, 0777, true);
        }
        $config = array(
        'upload_path' => $upPath,
        'allowed_types' => "gif|jpg|png|jpeg",
        'overwrite' => TRUE,
        'max_size' => "2048000", 
        'max_height' => "768",
        'max_width' => "1024"
        );
        $this->load->library('upload', $config);
        if(!$this->upload->do_upload('userpic'))
        { 
            $data['imageError'] =  $this->upload->display_errors();

        }
        else
        {
            $imageDetailArray = $this->upload->data();
            $image =  $imageDetailArray['file_name'];
        }

     }

Hope this helps you to upload image

How to "Open" and "Save" using java

Maybe you could take a look at JFileChooser, which allow you to use native dialogs in one line of code.

Cocoa Touch: How To Change UIView's Border Color And Thickness?

item's border color in swift 4.2:

let cell = tableView.dequeueReusableCell(withIdentifier: "Cell_lastOrderId") as! Cell_lastOrder
cell.layer.borderWidth = 1
cell.layer.borderColor = UIColor.white.cgColor
cell.layer.cornerRadius = 10

Error Code 1292 - Truncated incorrect DOUBLE value - Mysql

Had this issue with ES6 and TypeORM while trying to pass .where("order.id IN (:orders)", { orders }), where orders was a comma separated string of numbers. When I converted to a template literal, the problem was resolved.

.where(`order.id IN (${orders})`);

Flutter plugin not installed error;. When running flutter doctor

The best way to install it on Windows 

Doctor summary (to see all details, run flutter doctor -v):
[v] Flutter (Channel stable, 1.20.1, on Microsoft Windows [Version 10.0.18363.959], locale en-US)
[v] Android toolchain - develop for Android devices (Android SDK version 30.0.0)
[v] Android Studio (version 4.0)
[v] VS Code (version 1.47.3)
[!] Connected device
    ! No devices available

1- Open Android Studio File->Settings->Plugins and Make Sure You have Flutter and Dart Installed enter image description here

2- Go to VSCode to Extensions and install Flutter and Dart Extension

enter image description here

Hope It Solved the problem

Sorting object property by values

let toSort = {a:2323, b: 14, c: 799} 
let sorted = Object.entries(toSort ).sort((a,b)=> a[1]-b[1]) 

Output:

[ [ "b", 14 ], [ "c", 799 ], [ "a", 2323 ] ]

Disabling of EditText in Android

use EditText.setFocusable(false) to disable editing
EditText.setFocusableInTouchMode(true) to enable editing;

best OCR (Optical character recognition) example in android

Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.

Let me explain using step-by-step guidance.

First, download the source code from https://github.com/rmtheis/tess-two.

Import all three projects. After importing you will get an error. To solve the error you have to create a res folder in the tess-two project

enter image description here

First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"

After doing this in all three project the error should be gone.

Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.

Now you just need to import it into your workspace, but first you have to download android-ndk from this site:

http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file

Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable

Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture

enter image description here

done it

Now open cmd and go to on D:\Android Workspace\tess-two like below

enter image description here

If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:

Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest

enter image description here

Import test-two in this and run OCRTest and run it; you will get the best example of OCR.

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

I tested as below. Hope it helps.

Integer[] integers1 = new Integer[10];
        System.out.println(integers1.length); //it has length 10 but it is empty. It is not null array
        for (Integer integer : integers1) {
            System.out.println(integer); //prints all 0s
        }

//But if I manually add 0 to any index, now even though array has all 0s elements
//still it is not empty
//        integers1[2] = 0;
        for (Integer integer : integers1) {
            System.out.println(integer); //Still it prints all 0s but it is not empty
            //but that manually added 0 is different
        }

//Even we manually add 0, still we need to treat it as null. This is semantic logic.

        Integer[] integers2 = new Integer[20];
        integers2 = null; //array is nullified
//        integers2[3] = null; //If I had int[] -- because it is priitive -- then I can't write this line. 
        if (integers2 == null) {
            System.out.println("null Array");
        }   

How to get an isoformat datetime string including the default timezone?

Something like the following example. Note I'm in Eastern Australia (UTC + 10 hours at the moment).

>>> import datetime
>>> dtnow = datetime.datetime.now();dtutcnow = datetime.datetime.utcnow()
>>> dtnow
datetime.datetime(2010, 8, 4, 9, 33, 9, 890000)
>>> dtutcnow
datetime.datetime(2010, 8, 3, 23, 33, 9, 890000)
>>> delta = dtnow - dtutcnow
>>> delta
datetime.timedelta(0, 36000)
>>> hh,mm = divmod((delta.days * 24*60*60 + delta.seconds + 30) // 60, 60)
>>> hh,mm
(10, 0)
>>> "%s%+02d:%02d" % (dtnow.isoformat(), hh, mm)
'2010-08-04T09:33:09.890000+10:00'
>>>

What are the proper permissions for an upload folder with PHP/Apache?

I would go with Ryan's answer if you really want to do this.

In general on a *nix environment, you always want to err on giving away as little permissions as possible.

9 times out of 10, 755 is the ideal permission for this - as the only user with the ability to modify the files will be the webserver. Change this to 775 with your ftp user in a group if you REALLY need to change this.

Since you're new to php by your own admission, here's a helpful link for improving the security of your upload service: move_uploaded_file

Maintain image aspect ratio when changing height

I just had the same issue. Use the flex align to center your elements. You need to use align-items: center instead of align-content: center. This will maintain the aspect ratio, while align-content will not keep the aspect ratio.

How to convert a String to a Date using SimpleDateFormat?

You have used some type errors. If you want to set 08/16/2011 to following pattern. It is wrong because,

mm stands for minutes, use MM as it is for Months

DD is wrong, it should be dd which represents Days

Try this to achieve the output you want to get ( Tue Aug 16 "Whatever Time" IST 2011 ),

    String date = "08/16/2011"; //input date as String

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy"); // date pattern

    Date myDate = simpleDateFormat.parse(date); // returns date object 

    System.out.println(myDate); //outputs: Tue Aug 16 00:00:00 IST 2011

Can we overload the main method in Java?

Yes, main method can be overloaded. Overloaded main method has to be called from inside the "public static void main(String args[])" as this is the entry point when the class is launched by the JVM. Also overloaded main method can have any qualifier as a normal method have.

Java Pass Method as Parameter

While this is not yet valid for Java 7 and below, I believe that we should look to the future and at least recognize the changes to come in new versions such as Java 8.

Namely, this new version brings lambdas and method references to Java (along with new APIs, which are another valid solution to this problem. While they still require an interface no new objects are created, and extra classfiles need not pollute output directories due to different handling by the JVM.

Both flavors(lambda and method reference) require an interface available with a single method whose signature is used:

public interface NewVersionTest{
    String returnAString(Object oIn, String str);
}

Names of methods will not matter from here on. Where a lambda is accepted, a method reference is as well. For example, to use our signature here:

public static void printOutput(NewVersionTest t, Object o, String s){
    System.out.println(t.returnAString(o, s));
}

This is just a simple interface invocation, up until the lambda1 gets passed:

public static void main(String[] args){
    printOutput( (Object oIn, String sIn) -> {
        System.out.println("Lambda reached!");
        return "lambda return";
    }
    );
}

This will output:

Lambda reached!
lambda return

Method references are similar. Given:

public class HelperClass{
    public static String testOtherSig(Object o, String s){
        return "real static method";
    }
}

and main:

public static void main(String[] args){
    printOutput(HelperClass::testOtherSig);
}

the output would be real static method. Method references can be static, instance, non-static with arbitrary instances, and even constructors. For the constructor something akin to ClassName::new would be used.

1 This is not considered a lambda by some, as it has side effects. It does illustrate, however, the use of one in a more straightforward-to-visualize fashion.

How to solve munmap_chunk(): invalid pointer error in C++

This happens when the pointer passed to free() is not valid or has been modified somehow. I don't really know the details here. The bottom line is that the pointer passed to free() must be the same as returned by malloc(), realloc() and their friends. It's not always easy to spot what the problem is for a novice in their own code or even deeper in a library. In my case, it was a simple case of an undefined (uninitialized) pointer related to branching.

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. GNU 2012-05-10 MALLOC(3)

char *words; // setting this to NULL would have prevented the issue

if (condition) {
    words = malloc( 512 );

    /* calling free sometime later works here */

    free(words)
} else {

    /* do not allocate words in this branch */
}

/* free(words);  -- error here --
*** glibc detected *** ./bin: munmap_chunk(): invalid pointer: 0xb________ ***/

There are many similar questions here about the related free() and rellocate() functions. Some notable answers providing more details:

*** glibc detected *** free(): invalid next size (normal): 0x0a03c978 ***
*** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
glibc detected, realloc(): invalid pointer


IMHO running everything in a debugger (Valgrind) is not the best option because errors like this are often caused by inept or novice programmers. It's more productive to figure out the issue manually and learn how to avoid it in the future.

Selenium IDE - Command to wait for 5 seconds

Your best bet is probably waitForCondition and writing a javascript function that returns true when the map is loaded.

nodejs npm global config missing on windows

It looks like the files npm uses to edit its config files are not created on a clean install, as npm has a default option for each one. This is why you can still get options with npm config get <option>: having those files only overrides the defaults, it doesn't create the options from scratch.

I had never touched my npm config stuff before today, even though I had had it for months now. None of the files were there yet, such as ~/.npmrc (on a Windows 8.1 machine with Git Bash), yet I could run npm config get <something> and, if it was a correct npm option, it returned a value. When I ran npm config set <option> <value>, the file ~/.npmrc seemed to be created automatically, with the option & its value as the only non-commented-out line.

As for deleting options, it looks like this just sets the value back to the default value, or does nothing if that option was never set or was unset & never reset. Additionally, if that option is the only explicitly set option, it looks like ~/.npmrc is deleted, too, and recreated if you set anything else later.

In your case (assuming it is still the same over a year later), it looks like you never set the proxy option in npm. Therefore, as npm's config help page says, it is set to whatever your http_proxy (case-insensitive) environment variable is. This means there is nothing to delete, unless you want to "delete" your HTTP proxy, although you could set the option or environment variable to something else and hope neither breaks your set-up somehow.

How to select the last column of dataframe

Somewhat similar to your original attempt, but more Pythonic, is to use Python's standard negative-indexing convention to count backwards from the end:

df[df.columns[-1]]

A 'for' loop to iterate over an enum in Java

Streams

Prior to Java 8

for (Direction dir : Direction.values()) {
            System.out.println(dir);
}

Java 8

We can also make use of lambda and streams (Tutorial):

Stream.of(Direction.values()).forEachOrdered(System.out::println);

Why forEachOrdered and not forEach with streams ?

The behaviour of forEach is explicitly nondeterministic where as the forEachOrdered performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach does not guarantee that the order would be kept.

Also when working with streams (especially parallel ones) keep in mind the nature of streams. As per the doc:

Stream pipeline results may be nondeterministic or incorrect if the behavioral parameters to the stream operations are stateful. A stateful lambda is one whose result depends on any state which might change during the execution of the stream pipeline.

Set<Integer> seen = Collections.synchronizedSet(new HashSet<>());
stream.parallel().map(e -> { if (seen.add(e)) return 0; else return e; })...

Here, if the mapping operation is performed in parallel, the results for the same input could vary from run to run, due to thread scheduling differences, whereas, with a stateless lambda expression the results would always be the same.

Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards.

Streams may or may not have a defined encounter order. Whether or not a stream has an encounter order depends on the source and the intermediate operations.

Override body style for content in an iframe

This code uses vanilla JavaScript. It creates a new <style> element. It sets the text content of that element to be a string containing the new CSS. And it appends that element directly to the iframe document's head.

Keep in mind, however, that accessing elements of a document loaded from another origin is not permitted (for security reasons) -- contentDocument of the iframe element will evaluate to null when attempted from the browsing context of the page embedding the frame.

var iframe = document.getElementById('the-iframe');
var style = document.createElement('style');
style.textContent =
  'body {' +
  '  background-color: some-color;' +
  '  background-image: some-image;' +
  '}' 
;
iframe.contentDocument.head.appendChild(style);

Angular2: child component access parent class variable/function

What about a little trickery like NgModel does with NgForm? You have to register your parent as a provider, then load your parent in the constructor of the child.

That way, you don't have to put [sharedList] on all your children.

// Parent.ts
export var parentProvider = {
    provide: Parent,
    useExisting: forwardRef(function () { return Parent; })
};

@Component({
    moduleId: module.id,
    selector: 'parent',
    template: '<div><ng-content></ng-content></div>',
    providers: [parentProvider]
})
export class Parent {
    @Input()
    public sharedList = [];
}

// Child.ts
@Component({
    moduleId: module.id,
    selector: 'child',
    template: '<div>child</div>'
})
export class Child {
    constructor(private parent: Parent) {
        parent.sharedList.push('Me.');
    }
}

Then your HTML

<parent [sharedList]="myArray">
    <child></child>
    <child></child>
</parent>

You can find more information on the subject in the Angular documentation: https://angular.io/guide/dependency-injection-in-action#find-a-parent-component-by-injection

Ant is using wrong java version

Set your JAVA_HOME environment variable with the required java version (in your case java 1.5), then in build.xml use executable="${JAVA_HOME}/bin/javac" inside <javac></javac> tag .

example:

<target name="java compiler" description="Compiles the java code">
    <javac executable="${JAVA_HOME}/bin/javac" srcdir="./src" 
        destdir="${build.dir}/classes"> 
    </javac> 
</target>

Difference between <input type='button' /> and <input type='submit' />

W3C make it clear, on the specification about Button element

Button may be seen as a generic class for all kind of Buttons with no default behavior.

W3C

What is the difference between <section> and <div>?

<div>—the generic flow container we all know and love. It’s a block-level element with no additional semantic meaning (W3C:Markup, WhatWG)

<section>—a generic document or application section. A normally has a heading (title) and maybe a footer too. It’s a chunk of related content, like a subsection of a long article, a major part of the page (eg the news section on the homepage), or a page in a webapp’s tabbed interface. (W3C:Markup, WhatWG)

My suggestion: div: used lower version( i think 4.01 to still) html element(lot of designers handled that). section: recently comming (html5) html element.

Java Minimum and Maximum values in Array

You are doing two mistakes here.
1. calling getMaxValue(),getMinValue() methods before array initialization completes.
2.Not storing return value returned by the getMaxValue(),getMinValue() methods.
So try this code

   for (int i = 0 ; i < array.length; i++ ) 
  {
       int next = input.nextInt();
       // sentineil that will stop loop when 999 is entered
       if (next == 999)
       break;
       array[i] = next;
  }
  // get biggest number
  int maxValue = getMaxValue(array);
  System.out.println(maxValue );

  // get smallest number
  int minValue = getMinValue(array);
  System.out.println(minValue);

Read SQL Table into C# DataTable

Vendor independent version, solely relies on ADO.NET interfaces; 2 ways:

public DataTable Read1<T>(string query) where T : IDbConnection, new()
{
    using (var conn = new T())
    {
        using (var cmd = conn.CreateCommand())
        {
            cmd.CommandText = query;
            cmd.Connection.ConnectionString = _connectionString;
            cmd.Connection.Open();
            var table = new DataTable();
            table.Load(cmd.ExecuteReader());
            return table;
        }
    }
}

public DataTable Read2<S, T>(string query) where S : IDbConnection, new() 
                                           where T : IDbDataAdapter, IDisposable, new()
{
    using (var conn = new S())
    {
        using (var da = new T())
        {
            using (da.SelectCommand = conn.CreateCommand())
            {
                da.SelectCommand.CommandText = query;
                da.SelectCommand.Connection.ConnectionString = _connectionString;
                DataSet ds = new DataSet(); //conn is opened by dataadapter
                da.Fill(ds);
                return ds.Tables[0];
            }
        }
    }
}

I did some performance testing, and the second approach always outperformed the first.

Stopwatch sw = Stopwatch.StartNew();
DataTable dt = null;
for (int i = 0; i < 100; i++)
{
    dt = Read1<MySqlConnection>(query); // ~9800ms
    dt = Read2<MySqlConnection, MySqlDataAdapter>(query); // ~2300ms

    dt = Read1<SQLiteConnection>(query); // ~4000ms
    dt = Read2<SQLiteConnection, SQLiteDataAdapter>(query); // ~2000ms

    dt = Read1<SqlCeConnection>(query); // ~5700ms
    dt = Read2<SqlCeConnection, SqlCeDataAdapter>(query); // ~5700ms

    dt = Read1<SqlConnection>(query); // ~850ms
    dt = Read2<SqlConnection, SqlDataAdapter>(query); // ~600ms

    dt = Read1<VistaDBConnection>(query); // ~3900ms
    dt = Read2<VistaDBConnection, VistaDBDataAdapter>(query); // ~3700ms
}
sw.Stop();
MessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());

Read1 looks better on eyes, but data adapter performs better (not to confuse that one db outperformed the other, the queries were all different). The difference between the two depended on query though. The reason could be that Load requires various constraints to be checked row by row from the documentation when adding rows (its a method on DataTable) while Fill is on DataAdapters which were designed just for that - fast creation of DataTables.

How to capitalize the first character of each word in a string

The following method converts all the letters into upper/lower case, depending on their position near a space or other special chars.

public static String capitalizeString(String string) {
  char[] chars = string.toLowerCase().toCharArray();
  boolean found = false;
  for (int i = 0; i < chars.length; i++) {
    if (!found && Character.isLetter(chars[i])) {
      chars[i] = Character.toUpperCase(chars[i]);
      found = true;
    } else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { // You can add other chars here
      found = false;
    }
  }
  return String.valueOf(chars);
}

How do I install chkconfig on Ubuntu?

But how do I run this? I tried typing: sudo chkconfig.install which doesn't work.

I'm not sure where you got this package or what it contains; A url of download would be helpful. Without being able to look at the contents of chkconfig.install; I'm surprised to find a unix tool like chkconfig to be bundled in a zip archive, maybe it is still yet to be uncompressed, a tar.gz? but maybe it is a shell script?

I should suggest editing it and seeing what you are executing.

sh chkconfig.install or ./chkconfig.install ; which might work....but my suggestion would be to learn to use update-rc.d as the other answers have suggested but do not speak directly to the question...which is pretty hard to answer without being able to look at the data yourself.

Search a string in a file and delete it from this file by Shell Script

sed -i '/pattern/d' file

Use 'd' to delete a line. This works at least with GNU-Sed.

If your Sed doesn't have the option, to change a file in place, maybe you can use an intermediate file, to store the modification:

sed '/pattern/d' file > tmpfile && mv tmpfile file

Writing directly to the source usually doesn't work: sed '/pattern/d' file > file so make a copy before trying out, if you doubt it.

Parse JSON from JQuery.ajax success data

input type Button

<input type="button" Id="update" value="Update">

I've successfully posted a form with AJAX in perl. After posting the form, controller returns a JSON response as below

$(function() {

    $('#Search').click(function() {
        var query = $('#query').val();
        var update = $('#update').val();

        $.ajax({
            type: 'POST',
            url: '/Products/Search/',
            data: {
                'insert': update,
                'query': address,
            },
            success: function(res) {
                $('#ProductList').empty('');
                console.log(res);
                json = JSON.parse(res);
                for (var i in json) {
                    var row = $('<tr>');
                    row.append($('<td id=' + json[i].Id + '>').html(json[i].Id));
                    row.append($('<td id=' + json[i].Name + '>').html(json[i].Name));
                    $('</tr>');
                    $('#ProductList').append(row);
                }
            },
            error: function() {
                alert("did not work");
                location.reload(true);
            }
        });
    });
});

Print Html template in Angular 2 (ng-print in Angular 2)

Shortest solution to be assign the window to a typescript variable then call the print method on that, like below

in template file

<button ... (click)="window.print()" ...>Submit</button>

and, in typescript file

window: any;
constructor() {
  this.window = window;
}

How to enable file sharing for my app?

According to apple doc:

File-Sharing Support
File-sharing support lets apps make user data files available in iTunes 9.1 and later. An app that declares its support for file sharing makes the contents of its /Documents directory available to the user. The user can then move files in and out of this directory as needed from iTunes. This feature does not allow your app to share files with other apps on the same device; that behavior requires the pasteboard or a document interaction controller object.

To enable file sharing for your app, do the following:

  1. Add the UIFileSharingEnabled key to your app’s Info.plist file, and set the value of the key to YES. (The actual key name is "Application supports iTunes file sharing")

  2. Put whatever files you want to share in your app’s Documents directory.

  3. When the device is plugged into the user’s computer, iTunes displays a File Sharing section in the Apps tab of the selected device.

  4. The user can add files to this directory or move files to the desktop.

Apps that support file sharing should be able to recognize when files have been added to the Documents directory and respond appropriately. For example, your app might make the contents of any new files available from its interface. You should never present the user with the list of files in this directory and ask them to decide what to do with those files.

For additional information about the UIFileSharingEnabled key, see Information Property List Key Reference.

mongod command not recognized when trying to connect to a mongodb server

Apart from having a Path variable, the directory C:\data\db is mandatory.

Create this and the error shall be solved.

How can I simulate a print statement in MySQL?

to take output in MySQL you can use if statement SYNTAX:

if(condition,if_true,if_false)

the if_true and if_false can be used to verify and to show output as there is no print statement in the MySQL

Upload Image using POST form data in Python-requests

In case if you were to pass the image as part of JSON along with other attributes, you can use the below snippet.
client.py

import base64
import json                    

import requests

api = 'http://localhost:8080/test'
image_file = 'sample_image.png'

with open(image_file, "rb") as f:
    im_bytes = f.read()        
im_b64 = base64.b64encode(im_bytes).decode("utf8")

headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
  
payload = json.dumps({"image": im_b64, "other_key": "value"})
response = requests.post(api, data=payload, headers=headers)
try:
    data = response.json()     
    print(data)                
except requests.exceptions.RequestException:
    print(response.text)

server.py

import io
import json                    
import base64                  
import logging             
import numpy as np
from PIL import Image

from flask import Flask, request, jsonify, abort

app = Flask(__name__)          
app.logger.setLevel(logging.DEBUG)
  
  
@app.route("/test", methods=['POST'])
def test_method():         
    # print(request.json)      
    if not request.json or 'image' not in request.json: 
        abort(400)
             
    # get the base64 encoded string
    im_b64 = request.json['image']

    # convert it into bytes  
    img_bytes = base64.b64decode(im_b64.encode('utf-8'))

    # convert bytes data to PIL Image object
    img = Image.open(io.BytesIO(img_bytes))

    # PIL image object to numpy array
    img_arr = np.asarray(img)      
    print('img shape', img_arr.shape)

    # process your img_arr here    
    
    # access other keys of json
    # print(request.json['other_key'])

    result_dict = {'output': 'output_key'}
    return result_dict
  
  
def run_server_api():
    app.run(host='0.0.0.0', port=8080)
  
  
if __name__ == "__main__":     
    run_server_api()

What is the difference between `throw new Error` and `throw someObject`?

throw "I'm Evil"

throw will terminate the further execution & expose message string on catch the error.

_x000D_
_x000D_
try {
  throw "I'm Evil"
  console.log("You'll never reach to me", 123465)
} catch (e) {
  console.log(e); // I'm Evil
}
_x000D_
_x000D_
_x000D_

Console after throw will never be reached cause of termination.


throw new Error("I'm Evil")

throw new Error exposes an error event with two params name & message. It also terminate further execution

_x000D_
_x000D_
try {
  throw new Error("I'm Evil")
  console.log("You'll never reach to me", 123465)
} catch (e) {
  console.log(e.name, e.message); // Error I'm Evil
}
_x000D_
_x000D_
_x000D_

throw Error("I'm Evil")

And just for completeness, this works also, though is not technically the correct way to do it -

_x000D_
_x000D_
try {
  throw Error("I'm Evil")
  console.log("You'll never reach to me", 123465)
} catch (e) {
  console.log(e.name, e.message); // Error I'm Evil
}

console.log(typeof(new Error("hello"))) // object
console.log(typeof(Error)) // function
_x000D_
_x000D_
_x000D_

NLS_NUMERIC_CHARACTERS setting for decimal

Best way is,

SELECT to_number(replace(:Str,',','')/100) --into num2 
FROM dual;

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

How can I remove the last character of a string in python?

The simplest way is to use slice. If x is your string variable then x[:-1] will return the string variable without the last character. (BTW, x[-1] is the last character in the string variable) You are looking for

my_file_path = '/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg/' my_file_path = my_file_path[:-1]

Making Python loggers output all messages to stdout in addition to log file

For more detailed explanations - great documentation at that link. For example: It's easy, you only need to set up two loggers.

import sys
import logging

logger = logging.getLogger('')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('my_log_info.log')
sh = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('[%(asctime)s] %(levelname)s [%(filename)s.%(funcName)s:%(lineno)d] %(message)s', datefmt='%a, %d %b %Y %H:%M:%S')
fh.setFormatter(formatter)
sh.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(sh)

def hello_logger():
    logger.info("Hello info")
    logger.critical("Hello critical")
    logger.warning("Hello warning")
    logger.debug("Hello debug")

if __name__ == "__main__":
    print(hello_logger())

Output - terminal:

[Mon, 10 Aug 2020 12:44:25] INFO [TestLoger.py.hello_logger:15] Hello info
[Mon, 10 Aug 2020 12:44:25] CRITICAL [TestLoger.py.hello_logger:16] Hello critical
[Mon, 10 Aug 2020 12:44:25] WARNING [TestLoger.py.hello_logger:17] Hello warning
[Mon, 10 Aug 2020 12:44:25] DEBUG [TestLoger.py.hello_logger:18] Hello debug
None

Output - in file:

log in file


UPDATE: color terminal

Package:

pip install colorlog

Code:

import sys
import logging
import colorlog

logger = logging.getLogger('')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('my_log_info.log')
sh = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('[%(asctime)s] %(levelname)s [%(filename)s.%(funcName)s:%(lineno)d] %(message)s', datefmt='%a, %d %b %Y %H:%M:%S')
fh.setFormatter(formatter)
sh.setFormatter(colorlog.ColoredFormatter('%(log_color)s [%(asctime)s] %(levelname)s [%(filename)s.%(funcName)s:%(lineno)d] %(message)s', datefmt='%a, %d %b %Y %H:%M:%S'))
logger.addHandler(fh)
logger.addHandler(sh)

def hello_logger():
    logger.info("Hello info")
    logger.critical("Hello critical")
    logger.warning("Hello warning")
    logger.debug("Hello debug")
    logger.error("Error message")

if __name__ == "__main__":
    hello_logger()

output: enter image description here

Recommendation:

Complete logger configuration from INI file, which also includes setup for stdout and debug.log:

  • handler_file
    • level=WARNING
  • handler_screen
    • level=DEBUG

facet label font size

This should get you started:

R> qplot(hwy, cty, data = mpg) + 
       facet_grid(. ~ manufacturer) + 
       theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))

See also this question: How can I manipulate the strip text of facet plots in ggplot2?

How to store standard error in a variable

For error proofing your commands:

execute [INVOKING-FUNCTION] [COMMAND]

execute () {
    function="${1}"
    command="${2}"
    error=$(eval "${command}" 2>&1 >"/dev/null")

    if [ ${?} -ne 0 ]; then
        echo "${function}: ${error}"
        exit 1
    fi
}

Inspired in Lean manufacturing:

Hashing a dictionary?

Using sorted(d.items()) isn't enough to get us a stable repr. Some of the values in d could be dictionaries too, and their keys will still come out in an arbitrary order. As long as all the keys are strings, I prefer to use:

json.dumps(d, sort_keys=True)

That said, if the hashes need to be stable across different machines or Python versions, I'm not certain that this is bulletproof. You might want to add the separators and ensure_ascii arguments to protect yourself from any changes to the defaults there. I'd appreciate comments.

Put Excel-VBA code in module or sheet?

In my experience it's best to put as much code as you can into well-named modules, and only put as much code as you need to into the actual worksheet objects.

Example: Any code that uses worksheet events like Worksheet_SelectionChange or Worksheet_Calculate.

How to return a custom object from a Spring Data JPA GROUP BY query

I just solved this problem :

  • Class-based Projections doesn't work with query native(@Query(value = "SELECT ...", nativeQuery = true)) so I recommend to define custom DTO using interface .
  • Before using DTO should verify the query syntatically correct or not

Hide div after a few seconds

This will hide the div after 1 second (1000 milliseconds).

_x000D_
_x000D_
setTimeout(function() {_x000D_
    $('#mydiv').fadeOut('fast');_x000D_
}, 1000); // <-- time in milliseconds
_x000D_
#mydiv{_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
    background: #000;_x000D_
    color: #fff;_x000D_
    text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="mydiv">myDiv</div>
_x000D_
_x000D_
_x000D_

If you just want to hide without fading, use hide().

How can I check if a single character appears in a string?

You won't be able to check if char appears at all in some string without atleast going over the string once using loop / recursion ( the built-in methods like indexOf also use a loop )

If the no. of times you look up if a char is in string x is more way more than the length of the string than I would recommend using a Set data structure as that would be more efficient than simply using indexOf

String s = "abc";

// Build a set so we can check if character exists in constant time O(1)
Set<Character> set = new HashSet<>();
int len = s.length();
for(int i = 0; i < len; i++) set.add(s.charAt(i));

// Now we can check without the need of a loop
// contains method of set doesn't use a loop unlike string's contains method
set.contains('a') // true
set.contains('z') // false

Using set you will be able to check if character exists in a string in constant time O(1) but you will also use additional memory ( Space complexity will be O(n) ).

How to change the spinner background in Android?

It is already said in other answers . I did it like placing Spinner inside a CardView and changed the cardBackgroundColor . You could use some other views also and set its background either drawable or color . Thus it doesn't affect Spinner drop down arrow. As the spinner dropdown arrow disappears if we set background to Spinner.

 <androidx.cardview.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:cardCornerRadius="6dp"
        app:cardBackgroundColor="@color/white">
        
        <Spinner
            android:id="@+id/spinner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"/>

    </androidx.cardview.widget.CardView>

Using Eloquent ORM in Laravel to perform search of database using LIKE

If you need to frequently use LIKE, you can simplify the problem a bit. A custom method like () can be created in the model that inherits the Eloquent ORM:

public  function scopeLike($query, $field, $value){
        return $query->where($field, 'LIKE', "%$value%");
}

So then you can use this method in such way:

User::like('name', 'Tomas')->get();

How to create JSON post to api using C#

Have you tried using the WebClient class?

you should be able to use

string result = "";
using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/json"; 
    result = client.UploadString(url, "POST", json);
}
Console.WriteLine(result);

Documentation at

http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.110%29.aspx

http://msdn.microsoft.com/en-us/library/d0d3595k%28v=vs.110%29.aspx

TOMCAT - HTTP Status 404

  1. Click on Window > Show view > Server or right click on the server in "Servers" view, select "Properties".
  2. In the "General" panel, click on the "Switch Location" button.
  3. The "Location: [workspace metadata]" should replace by something else.
  4. Open the Overview screen for the server by double clicking it.
  5. In the Server locations tab , select "Use Tomcat location".
  6. Save the configurations and restart the Server.

You may want to follow the steps above before starting the server. Because server location section goes grayed-unreachable.

server Locations in eclipse view

Insert current date in datetime format mySQL

"datetime" expects the date to be formated like this: YYYY-MM-DD HH:MM:SS

so format your date like that when you are inserting.

Notepad++ cached files location

I have discovered that NotePad++ now also creates a subfolder at the file location, called nppBackup. So if your file lived in a folder called c:/thisfolder have a look to see if there's a folder called c:/thisfolder/nppBackup.

Occasionally I couldn't find the backup in AppData\Roaming\Notepad++\backup, but I found it in nppBackup.

Unsupported major.minor version 52.0

It happens when you compile your projects on higher version of java(say jdk 1.8) and then run it on a lower version (say jdk 1.7).

If you have JRE-1.7 library in your project path then ,

1.Right click on project

2.Go to Properties

3.Select Project Facets

4.Find Java in rows and then choose version (say 1.7) if using JRE-1.7

5.Click Apply and run your project.

What is the correct XPath for choosing attributes that contain "foo"?

try this:

//a[contains(@prop,'foo')]

that should work for any "a" tags in the document

How to get the anchor from the URL using jQuery?

Use

window.location.hash

to retrieve everything beyond and including the #

Sorting a list using Lambda/Linq to objects

Answer for 1.:

You should be able to manually build an expression tree that can be passed into OrderBy using the name as a string. Or you could use reflection as suggested in another answer, which might be less work.

Edit: Here is a working example of building an expression tree manually. (Sorting on X.Value, when only knowing the name "Value" of the property). You could (should) build a generic method for doing it.

using System;
using System.Linq;
using System.Linq.Expressions;

class Program
{
    private static readonly Random rand = new Random();
    static void Main(string[] args)
    {
        var randX = from n in Enumerable.Range(0, 100)
                    select new X { Value = rand.Next(1000) };

        ParameterExpression pe = Expression.Parameter(typeof(X), "value");
        var expression = Expression.Property(pe, "Value");
        var exp = Expression.Lambda<Func<X, int>>(expression, pe).Compile();

        foreach (var n in randX.OrderBy(exp))
            Console.WriteLine(n.Value);
    }

    public class X
    {
        public int Value { get; set; }
    }
}

Building an expression tree requires you to know the particpating types, however. That might or might not be a problem in your usage scenario. If you don't know what type you should be sorting on, it will propably be easier using reflection.

Answer for 2.:

Yes, since Comparer<T>.Default will be used for the comparison, if you do not explicitly define the comparer.

Get multiple elements by Id

You can get the multiple element by id by identifying what element it is. For example

<div id='id'></div>
<div id='id'></div>
<div id='id'></div>

I assume if you are using jQuery you can select all them all by

$("div#id")

. This will get you array of elements you loop them based on your logic.

Rails: How can I rename a database column in a Ruby on Rails migration?

rename_column :table, :old_column, :new_column

You'll probably want to create a separate migration to do this. (Rename FixColumnName as you will.):

script/generate migration FixColumnName
# creates  db/migrate/xxxxxxxxxx_fix_column_name.rb

Then edit the migration to do your will:

# db/migrate/xxxxxxxxxx_fix_column_name.rb
class FixColumnName < ActiveRecord::Migration
  def self.up
    rename_column :table_name, :old_column, :new_column
  end

  def self.down
    # rename back if you need or do something else or do nothing
  end
end

For Rails 3.1 use:

While, the up and down methods still apply, Rails 3.1 receives a change method that "knows how to migrate your database and reverse it when the migration is rolled back without the need to write a separate down method".

See "Active Record Migrations" for more information.

rails g migration FixColumnName

class FixColumnName < ActiveRecord::Migration
  def change
    rename_column :table_name, :old_column, :new_column
  end
end

If you happen to have a whole bunch of columns to rename, or something that would have required repeating the table name over and over again:

rename_column :table_name, :old_column1, :new_column1
rename_column :table_name, :old_column2, :new_column2
...

You could use change_table to keep things a little neater:

class FixColumnNames < ActiveRecord::Migration
  def change
    change_table :table_name do |t|
      t.rename :old_column1, :new_column1
      t.rename :old_column2, :new_column2
      ...
    end
  end
end

Then just db:migrate as usual or however you go about your business.


For Rails 4:

While creating a Migration for renaming a column, Rails 4 generates a change method instead of up and down as mentioned in the above section. The generated change method is:

$ > rails g migration ChangeColumnName

which will create a migration file similar to:

class ChangeColumnName < ActiveRecord::Migration
  def change
    rename_column :table_name, :old_column, :new_column
  end
end

How to read a file in Groovy into a string?

A slight variation...

new File('/path/to/file').eachLine { line ->
  println line
}

How to click a href link using Selenium

Use

driver.findElement(By.linkText("App Configuration")).click()

Other Approaches will be

JavascriptLibrary jsLib = new JavascriptLibrary(); 
jsLib.callEmbeddedSelenium(selenium, "triggerMouseEventAt", elementToClick,"click", "0,0");

or

((JavascriptExecutor) driver).executeScript("arguments[0].click();", elementToClick);

For detailed answer, View this post

How to remove the Flutter debug banner?

There is also another way for removing the "debug" banner from the flutter app. Now after new release there is no "debugShowCheckedModeBanner: false," code line in main .dart file. So I think these methods are effective:

  1. If you are using VS Code, then install "Dart DevTools" from extensions. After installation, you can easily find "Dart DevTools" text icon at the bottom of the VS Code. When you click on that text icon, a link will be open in google chrome. From that link page, you can easily remove the banner by just tapping on the banner icon as shown in this screenshot.

NOTE:-- Dart DevTools is a dart language debugger extension in VS Code

  1. If Dart DevTools is already installed in your VS Code, then you can directly open the google chrome and open this URL = "127.0.0.1: ZZZZZ/?hide=debugger&port=XXXXX"

NOTE:-- In this link replace "XXXXX" by 5 digit port-id (on which your flutter app is running) which will vary whenever you use "flutter run" command and replace "ZZZZZ" by your global(unchangeable) 5 digit debugger-id

NOTE:-- these dart dev tools are only for "Google Chrome Browser"

How to set a hidden value in Razor

There is a Hidden helper alongside HiddenFor which lets you set the value.

@Html.Hidden("RequiredProperty", "default")

EDIT Based on the edit you've made to the question, you could do this, but I believe you're moving into territory where it will be cheaper and more effective, in the long run, to fight for making the code change. As has been said, even by yourself, the controller or view model should be setting the default.

This code:

<ul>
@{
        var stacks = new System.Diagnostics.StackTrace().GetFrames();
        foreach (var frame in stacks)
        {
            <li>@frame.GetMethod().Name - @frame.GetMethod().DeclaringType</li>
        }
}
</ul>

Will give output like this:

Execute - ASP._Page_Views_ViewDirectoryX__SubView_cshtml
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
ExecutePageHierarchy - System.Web.Mvc.WebViewPage
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
RenderView - System.Web.Mvc.RazorView
Render - System.Web.Mvc.BuildManagerCompiledView
RenderPartialInternal - System.Web.Mvc.HtmlHelper
RenderPartial - System.Web.Mvc.Html.RenderPartialExtensions
Execute - ASP._Page_Views_ViewDirectoryY__MainView_cshtml

So assuming the MVC framework will always go through the same stack, you can grab var frame = stacks[8]; and use the declaring type to determine who your parent view is, and then use that determination to set (or not) the default value. You could also walk the stack instead of directly grabbing [8] which would be safer but even less efficient.

How to make links in a TextView clickable?

This is how I solved clickable and Visible links in a TextView (by code)

private void setAsLink(TextView view, String url){
        Pattern pattern = Pattern.compile(url);
        Linkify.addLinks(view, pattern, "http://");
        view.setText(Html.fromHtml("<a href='http://"+url+"'>http://"+url+"</a>"));
    }

How to lowercase a pandas dataframe string column if it has missing values?

Apply lambda function

df['original_category'] = df['original_category'].apply(lambda x:x.lower())

Creating a folder if it does not exists - "Item already exists"

I was not even concentrating, here is how to do it

$DOCDIR = [Environment]::GetFolderPath("MyDocuments")
$TARGETDIR = '$DOCDIR\MatchedLog'
if(!(Test-Path -Path $TARGETDIR )){
    New-Item -ItemType directory -Path $TARGETDIR
}

showDialog deprecated. What's the alternative?

From http://developer.android.com/reference/android/app/Activity.html

public final void showDialog (int id) Added in API level 1

This method was deprecated in API level 13. Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.

Simple version of showDialog(int, Bundle) that does not take any arguments. Simply calls showDialog(int, Bundle) with null arguments.

Why

  • A fragment that displays a dialog window, floating on top of its activity's window. This fragment contains a Dialog object, which it displays as appropriate based on the fragment's state. Control of the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on the dialog.
  • Here is a nice discussion Android DialogFragment vs Dialog
  • Another nice discussion DialogFragment advantages over AlertDialog

How to solve?

More

How to increase heap size for jBoss server

On wildfly 8 and later, go to /bin/standalone.conf and put your JAVA_OPTS there, with all you need.

awk - concatenate two string variable and assign to a third

Just use var = var1 var2 and it will automatically concatenate the vars var1 and var2:

awk '{new_var=$1$2; print new_var}' file

You can put an space in between with:

awk '{new_var=$1" "$2; print new_var}' file

Which in fact is the same as using FS, because it defaults to the space:

awk '{new_var=$1 FS $2; print new_var}' file

Test

$ cat file
hello how are you
i am fine
$ awk '{new_var=$1$2; print new_var}' file
hellohow
iam
$ awk '{new_var=$1 FS $2; print new_var}' file
hello how
i am

You can play around with it in ideone: http://ideone.com/4u2Aip

Check if AJAX response data is empty/blank/null/undefined/0

This worked form me.. PHP Code on page.php

 $query_de="sql statements here";
 $sql_de = sqlsrv_query($conn,$query_de);
      if ($sql_de)
      {
        echo "SQLSuccess";
       }
         exit();

and then AJAX Code has bellow

jQuery.ajax({
                    url  : "page.php",
                    type : "POST",
                    data : {
                            buttonsave   : 1,
                            var1         : val1,
                            var2         : val2,
                              },
                  success:function(data)
                           {
                     if(jQuery.trim(data) === "SQLSuccess")
                                   {
                           alert("Se agrego correctamente");
                          // alert(data);
                                      } else { alert(data);}
                              },
                   error: function(error)
                           {
                    alert("Error AJAX not working: "+ error );
                              } 
               }); 

NOTE: the word 'SQLSuccess' must be received from PHP

How to export query result to csv in Oracle SQL Developer?

CSV Export does not escape your data. Watch out for strings which end in \ because the resulting \" will look like an escaped " and not a \. Then you have the wrong number of " and your entire row is broken.

pull/push from multiple remote locations

Here is my example with bash script inside .gitconfig alias section

[alias]
        pushall = "!f(){ for i in `git remote`; do git push $i; done; };f"

Fetch the row which has the Max value for a column

I don't have Oracle to test it, but the most efficient solution is to use analytic queries. It should look something like this:

SELECT DISTINCT
    UserId
  , MaxValue
FROM (
    SELECT UserId
      , FIRST (Value) Over (
          PARTITION BY UserId
          ORDER BY Date DESC
        ) MaxValue
    FROM SomeTable
  )

I suspect that you can get rid of the outer query and put distinct on the inner, but I'm not sure. In the meantime I know this one works.

If you want to learn about analytic queries, I'd suggest reading http://www.orafaq.com/node/55 and http://www.akadia.com/services/ora_analytic_functions.html. Here is the short summary.

Under the hood analytic queries sort the whole dataset, then process it sequentially. As you process it you partition the dataset according to certain criteria, and then for each row looks at some window (defaults to the first value in the partition to the current row - that default is also the most efficient) and can compute values using a number of analytic functions (the list of which is very similar to the aggregate functions).

In this case here is what the inner query does. The whole dataset is sorted by UserId then Date DESC. Then it processes it in one pass. For each row you return the UserId and the first Date seen for that UserId (since dates are sorted DESC, that's the max date). This gives you your answer with duplicated rows. Then the outer DISTINCT squashes duplicates.

This is not a particularly spectacular example of analytic queries. For a much bigger win consider taking a table of financial receipts and calculating for each user and receipt, a running total of what they paid. Analytic queries solve that efficiently. Other solutions are less efficient. Which is why they are part of the 2003 SQL standard. (Unfortunately Postgres doesn't have them yet. Grrr...)

How to set a fixed width column with CSS flexbox

You should use the flex or flex-basis property rather than width. Read more on MDN.

.flexbox .red {
  flex: 0 0 25em;
}

The flex CSS property is a shorthand property specifying the ability of a flex item to alter its dimensions to fill available space. It contains:

flex-grow: 0;     /* do not grow   - initial value: 0 */
flex-shrink: 0;   /* do not shrink - initial value: 1 */
flex-basis: 25em; /* width/height  - initial value: auto */

A simple demo shows how to set the first column to 50px fixed width.

_x000D_
_x000D_
.flexbox {_x000D_
  display: flex;_x000D_
}_x000D_
.red {_x000D_
  background: red;_x000D_
  flex: 0 0 50px;_x000D_
}_x000D_
.green {_x000D_
  background: green;_x000D_
  flex: 1;_x000D_
}_x000D_
.blue {_x000D_
  background: blue;_x000D_
  flex: 1;_x000D_
}
_x000D_
<div class="flexbox">_x000D_
  <div class="red">1</div>_x000D_
  <div class="green">2</div>_x000D_
  <div class="blue">3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


See the updated codepen based on your code.

How do I encode URI parameter values?

Mmhh I know you've already discarded URLEncoder, but despite of what the docs say, I decided to give it a try.

You said:

For example, given an input:

http://google.com/resource?key=value

I expect the output:

http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue

So:

C:\oreyes\samples\java\URL>type URLEncodeSample.java
import java.net.*;

public class URLEncodeSample {
    public static void main( String [] args ) throws Throwable {
        System.out.println( URLEncoder.encode( args[0], "UTF-8" ));
    }
}

C:\oreyes\samples\java\URL>javac URLEncodeSample.java

C:\oreyes\samples\java\URL>java URLEncodeSample "http://google.com/resource?key=value"
http%3A%2F%2Fgoogle.com%2Fresource%3Fkey%3Dvalue

As expected.

What would be the problem with this?

Input and output numpy arrays to h5py

A cleaner way to handle file open/close and avoid memory leaks:

Prep:

import numpy as np
import h5py

data_to_write = np.random.random(size=(100,20)) # or some such

Write:

with h5py.File('name-of-file.h5', 'w') as hf:
    hf.create_dataset("name-of-dataset",  data=data_to_write)

Read:

with h5py.File('name-of-file.h5', 'r') as hf:
    data = hf['name-of-dataset'][:]

Bundling data files with PyInstaller (--onefile)

The most common complaint/question I've seen wrt PyInstaller is "my code can't find a data file which I definitely included in the bundle, where is it?", and it isn't easy to see what/where your code is searching because the extracted code is in a temp location and is removed when it exits. Add this bit of code to see what's included in your onefile and where it is, using @Jonathon Reinhart's resource_path()

for root, dirs, files in os.walk(resource_path("")):
    print(root)
    for file in files:
        print( "  ",file)

Returning first x items from array

You can use array_slice function, but do you will use another values? or only the first 5? because if you will use only the first 5 you can use the LIMIT on SQL.

Working with a List of Lists in Java

Also this is an example of how to print List of List using advanced for loop:

public static void main(String[] args){
        int[] a={1,3, 7, 8, 3, 9, 2, 4, 10};
        List<List<Integer>> triplets;
        triplets=sumOfThreeNaive(a, 13);
        for (List<Integer> list : triplets){
            for (int triplet: list){
                System.out.print(triplet+" ");
            }
            System.out.println();
        }
    }

Facebook Android Generate Key Hash

Great blog post on the subject

Extracting the Key Hash from .p12 key

  1. Open Terminal or Command line and navigate to where your .p12 key is.
  2. Type in: “keytool -v -list -keystore mycert.p12 -storetype pkcs12" where mycert.p12 is the filename of your .p12 key.
  3. Enter keystore password (the one you used when exported .p12 key). 4 . Copy sha1 fingerprint signature bytes text.
  4. The bytes at sha1 fingerprint signature are needed to write the “sha1.bin” file. You can use a hexadecimal editor to paste the bytes you copied. Afterwards, save the file as “sha1.bin”.
  5. Open terminal again and type in: “openssl base64 -in sha1.bin -out base64.txt”.
  6. The resulting “base64.txt” will contain the Key Hash that is needed for Facebook.

Great and simple hexadecimal editor for mac: HexFiend

OpenSSL should be preinstalled on mac, and here is the link for Windows version.

Link

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

I had the same problem using regex with bash scripting. I used a 2-step solution using pipes with grep -o applying

 '\[(.*?)\]'  

first, then

'\b.*\b'

Obviously not as efficient at the other answers, but an alternative.

change pgsql port

There should be a line in your postgresql.conf file that says:

port = 1486

Change that.

The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/

On Windows it is C:\Program Files\PostgreSQL\9.3\data

Don't forget to sudo service postgresql restart for changes to take effect.

How do I use InputFilter to limit characters in an EditText in Android?

I have done something like this to keep it simple:

edit_text.filters = arrayOf(object : InputFilter {
    override fun filter(
        source: CharSequence?,
        start: Int,
        end: Int,
        dest: Spanned?,
        dstart: Int,
        dend: Int
    ): CharSequence? {
        return source?.subSequence(start, end)
            ?.replace(Regex("[^A-Za-z0-9 ]"), "")
    }
})

This way we are replacing all the unwanted characters in the new part of the source string with an empty string.

The edit_text variable is the EditText object we are referring to.

The code is written in kotlin.

Inline elements shifting when made bold on hover

What about this? A javascript - CSS3 free solution.

http://jsfiddle.net/u1aks77x/1/

ul{}
li{float:left; list-style-type:none; }
a{position:relative; padding-right: 10px; text-decoration:none;}
a > .l1{}
a:hover > .l1{visibility:hidden;}
a:hover > .l2{display:inline;}
a > .l2{position: absolute; left:0; font-weight:bold; display:none;}

<ul>
  <li><a href="/" title="Home"><span class="l1">Home</span><span class="l2">Home</span></a></li>
  <li><a href="/" title="Contact"><span class="l1">Contact</span><span class="l2">Contact</span></a></li>
  <li><a href="/" title="Sitemap"><span class="l1">Sitemap</span><span class="l2">Sitemap</span></a></li>
</ul>

How do I rename a Git repository?

  • On the server side, just rename the repository with the mv command as usual:

    mv oldName.git newName.git
    
  • Then on the client side, change the value of the [remote "origin"] URL into the new one:

    url=example.com/newName.git
    

It worked for me.

Close iOS Keyboard by touching anywhere using Swift

Swift 3

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

Default value in Doctrine

Here is how I solved it for myself. Below is an Entity example with default value for MySQL. However, this also requires the setup of a constructor in your entity, and for you to set the default value there.

Entity\Example:
  type: entity
  table: example
  fields:
    id:
      type: integer
      id: true
      generator:
        strategy: AUTO
    label:
      type: string
      columnDefinition: varchar(255) NOT NULL DEFAULT 'default_value' COMMENT 'This is column comment'

How to import a CSS file in a React Component

The solutions above are completely changed and deprecated. If you want to use CSS modules (assuming you imported css-loaders) and I have been trying to find an answer for this for such a long time and finally did. The default webpack loader is quite different in the new version.

In your webpack, you need to find a part starting with cssRegex and replace it with this;

{
  test: cssRegex,
  exclude: cssModuleRegex,
  use: getStyleLoaders({
      importLoaders: 1,
      modules: true,
      localIdentName: '[name]__[local]__[hash:base64:5]'
  }),
}

String comparison using '==' vs. 'strcmp()'

The reason to use it is because strcmp

returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

=== only returns true or false, it doesn't tell you which is the "greater" string.

Android - Activity vs FragmentActivity?

ianhanniballake is right. You can get all the functionality of Activity from FragmentActivity. In fact, FragmentActivity has more functionality.

Using FragmentActivity you can easily build tab and swap format. For each tab you can use different Fragment (Fragments are reusable). So for any FragmentActivity you can reuse the same Fragment.

Still you can use Activity for single pages like list down something and edit element of the list in next page.

Also remember to use Activity if you are using android.app.Fragment; use FragmentActivity if you are using android.support.v4.app.Fragment. Never attach a android.support.v4.app.Fragment to an android.app.Activity, as this will cause an exception to be thrown.

How to get a web page's source code from Java

I am sure that you have found a solution somewhere over the past 2 years but the following is a solution that works for your requested site

package javasandbox;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
*
* @author Ryan.Oglesby
*/
public class JavaSandbox {

private static String sURL;

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws MalformedURLException, IOException {
    sURL = "http://www.cumhuriyet.com.tr/?hn=298710";
    System.out.println(sURL);
    URL url = new URL(sURL);
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    //set http request headers
            httpCon.addRequestProperty("Host", "www.cumhuriyet.com.tr");
            httpCon.addRequestProperty("Connection", "keep-alive");
            httpCon.addRequestProperty("Cache-Control", "max-age=0");
            httpCon.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            httpCon.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
            httpCon.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
            httpCon.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
            //httpCon.addRequestProperty("Cookie", "JSESSIONID=EC0F373FCC023CD3B8B9C1E2E2F7606C; lang=tr; __utma=169322547.1217782332.1386173665.1386173665.1386173665.1; __utmb=169322547.1.10.1386173665; __utmc=169322547; __utmz=169322547.1386173665.1.1.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/questions/8616781/how-to-get-a-web-pages-source-code-from-java; __gads=ID=3ab4e50d8713e391:T=1386173664:S=ALNI_Mb8N_wW0xS_wRa68vhR0gTRl8MwFA; scrElm=body");
            HttpURLConnection.setFollowRedirects(false);
            httpCon.setInstanceFollowRedirects(false);
            httpCon.setDoOutput(true);
            httpCon.setUseCaches(true);

            httpCon.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream(), "UTF-8"));
            String inputLine;
            StringBuilder a = new StringBuilder();
            while ((inputLine = in.readLine()) != null)
                a.append(inputLine);
            in.close();

            System.out.println(a.toString());

            httpCon.disconnect();
}
}

Checking for a null int value from a Java ResultSet

Another nice way of checking, if you have control the SQL, is to add a default value in the query itself for your int column. Then just check for that value.

e.g for an Oracle database, use NVL

SELECT NVL(ID_PARENT, -999) FROM TABLE_NAME;

then check

if (rs.getInt('ID_PARENT') != -999)
{
}

Of course this also is under the assumption that there is a value that wouldn't normally be found in the column.

How to group by week in MySQL?

You can use both YEAR(timestamp) and WEEK(timestamp), and use both of the these expressions in the SELECT and the GROUP BY clause.

Not overly elegant, but functional...

And of course you can combine these two date parts in a single expression as well, i.e. something like

SELECT CONCAT(YEAR(timestamp), '/', WEEK(timestamp)), etc...
FROM ...
WHERE ..
GROUP BY CONCAT(YEAR(timestamp), '/', WEEK(timestamp))

Edit: As Martin points out you can also use the YEARWEEK(mysqldatefield) function, although its output is not as eye friendly as the longer formula above.


Edit 2 [3 1/2 years later!]:
YEARWEEK(mysqldatefield) with the optional second argument (mode) set to either 0 or 2 is probably the best way to aggregate by complete weeks (i.e. including for weeks which straddle over January 1st), if that is what is desired. The YEAR() / WEEK() approach initially proposed in this answer has the effect of splitting the aggregated data for such "straddling" weeks in two: one with the former year, one with the new year.
A clean-cut every year, at the cost of having up to two partial weeks, one at either end, is often desired in accounting etc. and for that the YEAR() / WEEK() approach is better.

How can I overwrite file contents with new content in PHP?

Use file_put_contents()

file_put_contents('file.txt', 'bar');
echo file_get_contents('file.txt'); // bar
file_put_contents('file.txt', 'foo');
echo file_get_contents('file.txt'); // foo

Alternatively, if you're stuck with fopen() you can use the w or w+ modes:

'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

How to install and use "make" in Windows?

The accepted answer is a bad idea in general because the manually created make.exe will stick around and can potentially cause unexpected problems. It actually breaks RubyInstaller: https://github.com/oneclick/rubyinstaller2/issues/105

An alternative is installing make via Chocolatey (as pointed out by @Vasantha Ganesh K)

Another alternative is installing MSYS2 from Chocolatey and using make from C:\tools\msys64\usr\bin. If make isn't installed automatically with MSYS2 you need to install it manually via pacman -S make (as pointed out by @Thad Guidry and @Luke).

How to move a git repository into another directory and make that directory a git repository?

It's very simple. Git doesn't care about what's the name of its directory. It only cares what's inside. So you can simply do:

# copy the directory into newrepo dir that exists already (else create it)
$ cp -r gitrepo1 newrepo

# remove .git from old repo to delete all history and anything git from it
$ rm -rf gitrepo1/.git

Note that the copy is quite expensive if the repository is large and with a long history. You can avoid it easily too:

# move the directory instead
$ mv gitrepo1 newrepo

# make a copy of the latest version
# Either:
$ mkdir gitrepo1; cp -r newrepo/* gitrepo1/  # doesn't copy .gitignore (and other hidden files)

# Or:
$ git clone --depth 1 newrepo gitrepo1; rm -rf gitrepo1/.git

# Or (look further here: http://stackoverflow.com/q/1209999/912144)
$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -

Once you create newrepo, the destination to put gitrepo1 could be anywhere, even inside newrepo if you want it. It doesn't change the procedure, just the path you are writing gitrepo1 back.

Html.DropDownList - Disabled/Readonly

I just do this and call it a day

Model.Id > -1 ? Html.EnumDropDownListFor(m => m.Property, new { disabled = "disabled" }) : Html.EnumDropDownListFor(m => m.Property)

Vim clear last search highlighting

There are two 'must have' plugins for this:

  1. sensible - Ctrl-l for nohlsearch and redraw screen.
  2. unimpared - [oh, ]oh and coh to control hlsearch.

ImportError: No module named six

I did the following to solve the mentioned problem. I got the mentioned problem when I was trying to run the built exe, even I successfully built the exe using pyinstaller. I did this on Windows 10.

  1. go to https://pypi.org/project/six/#files
  2. download "six-1.14.0.tar.gz (33.9 kB)"
  3. unzip it, copy and paste "six.py" into your source directory.
  4. import "six" module into your source code (import six)
  5. run source script.

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

Use DateTime.Now.ToString("yyyy-MM-dd h:mm tt");. See this.

How to make CSS3 rounded corners hide overflow in Chrome/Opera

Supported in latest chrome, opera and safari, you can do this:

-webkit-clip-path: inset(0 0 0 0 round 100px);
clip-path: inset(0 0 0 0 round 100px);

You should definitely check out the tool http://bennettfeely.com/clippy/!

Printing variables in Python 3.4

one can print values using the format method in python. This small example will help take input of two numbers a and b. Print a+b in first line and a-b in second line

print('{:d}\n{:d}'.format(a+b,a-b))

Similarly in the answer we can do

print ("{0}. {1} appears {2} times.".format(22, 'c', 9999))

The python method format() for string is used to specify a string format. So {0},{1},{2} are like array indexes called as positional parameters. Therefore {0} is assigned first value written in format (a+b), {1} is assigned the second value (a-b) and so on. We can also use keyword instead of positional parameter like for example

print("Hi! my name is {name}".format(name="rashi"))

Therefore name here is the keyword and its value is Rashi Hope it helps :)

Remove empty lines in a text file via grep

Try the following:

grep -v -e '^$'

C# Reflection: How to get class reference from string?

You can use Type.GetType(string), but you'll need to know the full class name including namespace, and if it's not in the current assembly or mscorlib you'll need the assembly name instead. (Ideally, use Assembly.GetType(typeName) instead - I find that easier in terms of getting the assembly reference right!)

For instance:

// "I know String is in the same assembly as Int32..."
Type stringType = typeof(int).Assembly.GetType("System.String");

// "It's in the current assembly"
Type myType = Type.GetType("MyNamespace.MyType");

// "It's in System.Windows.Forms.dll..."
Type formType = Type.GetType ("System.Windows.Forms.Form, " + 
    "System.Windows.Forms, Version=2.0.0.0, Culture=neutral, " + 
    "PublicKeyToken=b77a5c561934e089");

Using TortoiseSVN how do I merge changes from the trunk to a branch and vice versa?

Shift-Right Click on the folder and select TortoiseSVN -> Merge All

Breaking/exit nested for in vb.net

Unfortunately, there's no exit two levels of for statement, but there are a few workarounds to do what you want:

  • Goto. In general, using goto is considered to be bad practice (and rightfully so), but using goto solely for a forward jump out of structured control statements is usually considered to be OK, especially if the alternative is to have more complicated code.

    For Each item In itemList
        For Each item1 In itemList1
            If item1.Text = "bla bla bla" Then
                Goto end_of_for
            End If
        Next
    Next
    
    end_of_for:
    
  • Dummy outer block

    Do
        For Each item In itemList
            For Each item1 In itemList1
                If item1.Text = "bla bla bla" Then
                    Exit Do
                End If
            Next
        Next
    Loop While False
    

    or

    Try
        For Each item In itemlist
            For Each item1 In itemlist1
                If item1 = "bla bla bla" Then
                    Exit Try
                End If
            Next
        Next
    Finally
    End Try
    
  • Separate function: Put the loops inside a separate function, which can be exited with return. This might require you to pass a lot of parameters, though, depending on how many local variables you use inside the loop. An alternative would be to put the block into a multi-line lambda, since this will create a closure over the local variables.

  • Boolean variable: This might make your code a bit less readable, depending on how many layers of nested loops you have:

    Dim done = False
    
    For Each item In itemList
        For Each item1 In itemList1
            If item1.Text = "bla bla bla" Then
                done = True
                Exit For
            End If
        Next
        If done Then Exit For
    Next
    

Form Submission without page refresh

Just catch the submit event and prevent that, then do ajax

$(document).ready(function () {
    $('#myform').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url : $(this).attr('action') || window.location.pathname,
            type: "GET",
            data: $(this).serialize(),
            success: function (data) {
                $("#form_output").html(data);
            },
            error: function (jXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    });
});

'cannot open git-upload-pack' error in Eclipse when cloning or pushing git repository

I just got this same error, "cannot open git-upload-pack", in Eclipse with a BitBucket repo trying to do a pull or a push. I resolved it by switching local branches (Team/Switch To) to the master branch and doing a pull, and then switching back to the branch I was working on and pulling again.

ie8 var w= window.open() - "Message: Invalid argument."

It seems when even using a "valid" custom window name (not _blank, etc.) using window.open to launch a new window, there is still issues. It works fine the first time you click the link, but if you click it again (with the first launched window still up) you receive an "Error: No such interface supported" script debug.

Eloquent - where not equal to

For where field not empty this worked for me:

->where('table_name.field_name', '<>', '')

Get a DataTable Columns DataType

if (dr[dc.ColumnName].GetType().ToString() == "System.DateTime")

How to run the Python program forever?

I know this is too old thread but why no one mentioned this

#!/usr/bin/python3
import asyncio 

loop = asyncio.get_event_loop()
try:
    loop.run_forever()
finally:
    loop.close()

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

I just want to add that if you want to somehow store the encrypted byte array as String and then retrieve it and decrypt it (often for obfuscation of database values) you can use this approach:

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class StrongAES 
{
    public void run() 
    {
        try 
        {
            String text = "Hello World";
            String key = "Bar12345Bar12345"; // 128 bit key
            // Create key and cipher
            Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            // encrypt the text
            cipher.init(Cipher.ENCRYPT_MODE, aesKey);
            byte[] encrypted = cipher.doFinal(text.getBytes());

            StringBuilder sb = new StringBuilder();
            for (byte b: encrypted) {
                sb.append((char)b);
            }

            // the encrypted String
            String enc = sb.toString();
            System.out.println("encrypted:" + enc);

            // now convert the string to byte array
            // for decryption
            byte[] bb = new byte[enc.length()];
            for (int i=0; i<enc.length(); i++) {
                bb[i] = (byte) enc.charAt(i);
            }

            // decrypt the text
            cipher.init(Cipher.DECRYPT_MODE, aesKey);
            String decrypted = new String(cipher.doFinal(bb));
            System.err.println("decrypted:" + decrypted);

        }
        catch(Exception e) 
        {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) 
    {
        StrongAES app = new StrongAES();
        app.run();
    }
}

Swift add icon/image in UITextField

This did it for me. in a custom/reusable class. helps alot with the space in b/w the actual text and left view icon/image enter image description here

func currencyLeftVeiw(image litery: UIImage) {
        self.leftView = UIView(frame: CGRect(x: 10, y: 0, width: 40, height: 40))
        self.leftViewMode = .always
        let leftViewItSelf = UIImageView(frame: CGRect(x: 10, y: 10, width: 20, height: 20))
        leftViewItSelf.image = litery
        leftView?.addSubview(leftViewItSelf)
    }

How to use jQuery to get the current value of a file input field

You need to use val rather than value.

$("#fileinput").val();

How to cache Google map tiles for offline usage?

update:

I found the terms of use from Google Map:

Section 10.5

No caching or storage. You will not pre-fetch, cache, index, or store any Content to be used outside the Service, except that you may store limited amounts of Content solely for the purpose of improving the performance of your Maps API Implementation due to network latency (and not for the purpose of preventing Google from accurately tracking usage), and only if such storage: is temporary (and in no event more than 30 calendar days); is secure; does not manipulate or aggregate any part of the Content or Service; and does not modify attribution in any way.

It means we can cache for limited time actually

How to convert strings into integers in Python?

If it's only a tuple of tuples, something like rows=[map(int, row) for row in rows] will do the trick. (There's a list comprehension and a call to map(f, lst), which is equal to [f(a) for a in lst], in there.)

Eval is not what you want to do, in case there's something like __import__("os").unlink("importantsystemfile") in your database for some reason. Always validate your input (if with nothing else, the exception int() will raise if you have bad input).

What is difference between INNER join and OUTER join

INNER JOIN: Returns all rows when there is at least one match in BOTH tables

LEFT JOIN: Return all rows from the left table, and the matched rows from the right table

RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table

FULL JOIN: Return all rows when there is a match in ONE of the tables

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

If you transferred these files through disk or other means, it is likely they were not saved properly.

How to detect Adblock on my website?

This approach I use on my site, maybe you will find it helpful. In my opinion, it's the simpliest solution.

AdBlocker blocks specific classes and html elements, by inspecting these selectors of any blocked ads in developer console (they are all listed) you can see which elements will be always blocked.

E.g. just inspect this question page on stackoverflow and you will see bunch of blocked ads.

For example, any element with bottom-ad class is automatically blocked.

  1. I created a non-empty div element with bottom-ad class: <div class="bottom-ad" style="width: 1px; height: 1px;">HI</div>
  2. After page loads just check if this element is hidden. I used jQuery, but feel free to use javascript: $('.bottom-ad').css('display') == "none" or even better by using $('.bottom-ad').is(':visible')

If value is true, then AdBlocker is active.

Cannot authenticate into mongo, "auth fails"

It appears the problem is that a user created via the method described in the mongo docs does not have permission to connect to the default database (test), even if that user was created with the "userAdminAnyDatabase" and "dbAdminAnyDatabase" roles.

How to: Add/Remove Class on mouseOver/mouseOut - JQuery .hover?

Your selector is missing a . and though you say you want to change the border-color - you're adding and removing a class that sets the background-color

How to put a UserControl into Visual Studio toolBox

Basic qustion if you are using generics in your base control. If yes:

lets say we have control:

public class MyComboDropDown : ComboDropDownComon<MyType>
{
    public MyComboDropDown() { }
}

MyComboDropDown will not allow to open designer on it and will be not shown in Toolbox. Why? Because base control is not already compiled - when MyComboDropDown is complied. You can modify to this:

public class MyComboDropDown : MyComboDropDownBase
{
    public MyComboDropDown() { }
}

public class MyComboDropDownBase : ComboDropDownComon<MyType>
{

}

Than after rebuild, and reset toolbox it should be able to see MyComboDropDown in designer and also in Toolbox

Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

This error is definite mismatch between the data that is advertised in the HTTP Headers and the data transferred over the wire.

It could come from the following:

  1. Server: If a server has a bug with certain modules that changes the content but don't update the content-length in the header or just doesn't work properly. It was the case for the Node HTTP Proxy at some point (see here)

  2. Proxy: Any proxy between you and your server could be modifying the request and not update the content-length header.

As far as I know, I haven't see those problem in IIS but mostly with custom written code.

Let me know if that helps.

Powershell script to check if service is started, if not then start it

Given $arrService = Get-Service -Name $ServiceName, $arrService.Status is a static property, corresponding to the value at the time of the call. Use $arrService.Refresh() when needed to renew the properties to current values.

MSDN ~ ServiceController.Refresh()

Refreshes property values by resetting the properties to their current values.

using scp in terminal

Simple :::

scp remoteusername@remoteIP:/path/of/file /Local/path/to/copy

scp -r remoteusername@remoteIP:/path/of/folder /Local/path/to/copy

jQuery .each() index?

surprise to see that no have given this syntax.

.each syntax with data or collection

jQuery.each(collection, callback(indexInArray, valueOfElement));

OR

jQuery.each( jQuery('#list option'), function(indexInArray, valueOfElement){
//your code here
}); 

Getting time difference between two times in PHP

<?php
$start = strtotime("12:00");
$end = // Run query to get datetime value from db
$elapsed = $end - $start;
echo date("H:i", $elapsed);
?>

How to send a stacktrace to log4j?

The answer from skaffman is definitely the correct answer. All logger methods such as error(), warn(), info(), debug() take Throwable as a second parameter:

try {
...
 } catch (Exception e) {
logger.error("error: ", e);
}

However, you can extract stacktrace as a String as well. Sometimes it could be useful if you wish to take advantage of formatting feature using "{}" placeholder - see method void info(String var1, Object... var2); In this case say you have a stacktrace as String, then you can actually do something like this:

try {
...
 } catch (Exception e) {
String stacktrace = TextUtils.getStacktrace(e);
logger.error("error occurred for usename {} and group {}, details: {}",username, group, stacktrace);
}

This will print parametrized message and the stacktrace at the end the same way it does for method: logger.error("error: ", e);

I actually wrote an open source library that has a Utility for extraction of a stacktrace as a String with an option to smartly filter out some noise out of stacktrace. I.e. if you specify the package prefix that you are interested in your extracted stacktrace would be filtered out of some irrelevant parts and leave you with very consized info. Here is the link to the article that explains what utilities the library has and where to get it (both as maven artifacts and git sources) and how to use it as well. Open Source Java library with stack trace filtering, Silent String parsing Unicode converter and Version comparison See the paragraph "Stacktrace noise filter"

Get visible items in RecyclerView

for those who have a logic to be implemented inside the RecyclerView adapter you can still use @ernesto approach combined with an on scrollListener to get what you want as the RecyclerView is consulted. Inside the adapter you will have something like this:

@Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if(manager instanceof LinearLayoutManager && getItemCount() > 0) {
            LinearLayoutManager llm = (LinearLayoutManager) manager;
            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                }

                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                        int visiblePosition = llm.findFirstCompletelyVisibleItemPosition();
                        if(visiblePosition > -1) {
                            View v = llm.findViewByPosition(visiblePosition);
                            //do something
                            v.setBackgroundColor(Color.parseColor("#777777"));
                        }
                }
            });
        }
    }

Add default value of datetime field in SQL Server to a timestamp

This can also be done through the SSMS GUI.

  1. Put your table in design view (Right click on table in object explorer->Design)
  2. Add a column to the table (or click on the column you want to update if it already exists)
  3. In Column Properties, enter (getdate()) in Default Value or Binding field as pictured below

Image of table in design view

Returning data from Axios API

You can use Async - Await:

async function axiosTest() {
  const response = await axios.get(url);
  const data = await response.json();  
}

Windows command prompt log to a file

You can redirect the output of a cmd prompt to a file using > or >> to append to a file.

i.e.

echo Hello World >C:\output.txt
echo Hello again! >>C:\output.txt

or

mybatchfile.bat >C:\output.txt

Note that using > will automatically overwrite the file if it already exists.

You also have the option of redirecting stdin, stdout and stderr.

See here for a complete list of options.

ReactJS: "Uncaught SyntaxError: Unexpected token <"

In addition to Dee Jee solution, After trying out his solution, My error never went.

I noticed(after two days of head scratch) that the browser has cached the files improperly.

  • My browser wasn't able to load the preview of the cached files and status code from express was 301.
  • In the networks tab of the browser dev tools, I get that those files are server from disk cache.

Solution

Remove the cached files. By clearing the browser history in a span of 1 hour, so that all the cached files get deleted.

Is there an Eclipse plugin to run system shell in the Console?

I really like StartExplorer but it is a contextual launcher rather than in - IDE shell so not sure if that is what you want

How to check if array is not empty?

if self.table:
    print 'It is not empty'

Is fine too

Best way to do nested case statement logic in SQL Server

You can combine multiple conditions to avoid the situation:

CASE WHEN condition1 = true AND condition2 = true THEN calculation1 
     WHEN condition1 = true AND condition2 = false 
     ELSE 'what so ever' END,

Can I give a default value to parameters or optional parameters in C# functions?

Yes. See Named and Optional Arguments. Note that the default value needs to be a constant, so this is OK:

public string Foo(string myParam = "default value") // constant, OK
{
}

but this is not:

public void Bar(string myParam = Foo()) // not a constant, not OK
{
}

Format y axis as percent

pandas dataframe plot will return the ax for you, And then you can start to manipulate the axes whatever you want.

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(100,5))

# you get ax from here
ax = df.plot()
type(ax)  # matplotlib.axes._subplots.AxesSubplot

# manipulate
vals = ax.get_yticks()
ax.set_yticklabels(['{:,.2%}'.format(x) for x in vals])

enter image description here

How do I automatically set the $DISPLAY variable for my current session?

You'll need to tell your vnc client to export the correct $DISPLAY once you have logged in. How you do that will probably depend on your vnc client.

How can I install a .ipa file to my iPhone simulator

In Xcode 6+ and iOS8+ you can do the simple steps below

  1. Paste .app file on desktop.
  2. Open terminal and paste the commands below:

    cd desktop

    xcrun simctl install booted xyz.app

  3. Open iPhone simulator and click on app and use

For versions below iOS 8, do the following simple steps.

Note: You'll want to make sure that your app is built for all architectures, the Simulator is x386 in the Build Settings and Build Active Architecture Only set to No.

  1. Path: Library->Application Support->iPhone Simulator->7.1 (or another version if you need it)->Applications
  2. Create a new folder with the name of the app
  3. Go inside the folder and place the .app file here.

How to check if a string contains a specific text

Use the strpos function: http://php.net/manual/en/function.strpos.php

$haystack = "foo bar baz";
$needle   = "bar";

if( strpos( $haystack, $needle ) !== false) {
    echo "\"bar\" exists in the haystack variable";
}

In your case:

if( strpos( $a, 'some text' ) !== false ) echo 'text';

Note that my use of the !== operator (instead of != false or == true or even just if( strpos( ... ) ) {) is because of the "truthy"/"falsy" nature of PHP's handling of the return value of strpos.

As of PHP 8.0.0 you can now use str_contains

<?php
    if (str_contains('abc', '')) {
        echo "Checking the existence of the empty string will always 
        return true";
    }

Adding a module (Specifically pymorph) to Spyder (Python IDE)

Using ! on the IPython console within spyder allows you to use pip. So, in the example, you could do:

[1] !pip install pymorph

Note, this is also available (though perhaps unreliably) on the Python console for Spyder versions before ~2.3.3. Thanks to @CarlosCordoba for this clarification.

What do the terms "CPU bound" and "I/O bound" mean?

When your program is waiting for I/O (ie. a disk read/write or network read/write etc), the CPU is free to do other tasks even if your program is stopped. The speed of your program will mostly depend on how fast that IO can happen, and if you want to speed it up you will need to speed up the I/O.

If your program is running lots of program instructions and not waiting for I/O, then it is said to be CPU bound. Speeding up the CPU will make the program run faster.

In either case, the key to speeding up the program might not be to speed up the hardware, but to optimize the program to reduce the amount of IO or CPU it needs, or to have it do I/O while it also does CPU intensive stuff.

Possible to access MVC ViewBag object from Javascript file?

Create a view and return it as a partial view:

public class AssetsController : Controller
{
    protected void SetMIME(string mimeType)
    {
        this.Response.AddHeader("Content-Type", mimeType);
        this.Response.ContentType = mimeType;
    }

    // this will render a view as a Javascript file
    public ActionResult GlobalJS()
    {
        this.SetMIME("text/javascript");
        return PartialView();
    }
}

Then in the GlobalJS view add the javascript code like (adding the // will make visual studio intellisense read it as java-script)

//<script>

    $(document).ready(function () {
       alert('@ViewBag.PropertyName');
    }); 

//</script>

Then in your final view you can add a reference to the javascript just like this.

<script src="@Url.Action("GlobalJS", "Assets")"></script> 

Then in your final view controller you can create/pass your ViewBags and it will be rendered in your javascript.

public class MyFinalViewController : Controller
{
    public ActionResult Index()
    {
        ViewBag.PropertyName = "My ViewBag value!";
        return View();
    }
}

Hope it helps.

Avoid dropdown menu close on click inside

You could simply execute event.stopPropagation on click event of the links themselves. Something like this.

    $(".dropdown-menu a").click((event) => {
         event.stopPropagation()
         let url = event.target.href
         //Do something with the url or any other logic you wish
    })

Edit: If someone saw this answer and is using react, it will not work. React handle the javascript events differently and by the time your react event handler is being called, the event has already been fired and propagated. To overcome that you should attach the event manually like that

handleMenuClick(event) {
   event.stopPropagation()
   let menu_item = event.target
   //implement your logic here.
}
componentDidMount() {
    document.getElementsByClassName("dropdown-menu")[0].addEventListener(
        "click", this.handleMenuClick.bind(this), false)
   }
}

How to search a specific value in all tables (PostgreSQL)?

And if someone think it could help. Here is @Daniel Vérité's function, with another param that accept names of columns that can be used in search. This way it decrease the time of processing. At least in my test it reduced a lot.

CREATE OR REPLACE FUNCTION search_columns(
    needle text,
    haystack_columns name[] default '{}',
    haystack_tables name[] default '{}',
    haystack_schema name[] default '{public}'
)
RETURNS table(schemaname text, tablename text, columnname text, rowctid text)
AS $$
begin
  FOR schemaname,tablename,columnname IN
      SELECT c.table_schema,c.table_name,c.column_name
      FROM information_schema.columns c
      JOIN information_schema.tables t ON
        (t.table_name=c.table_name AND t.table_schema=c.table_schema)
      WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
        AND c.table_schema=ANY(haystack_schema)
        AND (c.column_name=ANY(haystack_columns) OR haystack_columns='{}')
        AND t.table_type='BASE TABLE'
  LOOP
    EXECUTE format('SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L',
       schemaname,
       tablename,
       columnname,
       needle
    ) INTO rowctid;
    IF rowctid is not null THEN
      RETURN NEXT;
    END IF;
 END LOOP;
END;
$$ language plpgsql;

Bellow is an example of usage of the search_function created above.

SELECT * FROM search_columns('86192700'
    , array(SELECT DISTINCT a.column_name::name FROM information_schema.columns AS a
            INNER JOIN information_schema.tables as b ON (b.table_catalog = a.table_catalog AND b.table_schema = a.table_schema AND b.table_name = a.table_name)
        WHERE 
            a.column_name iLIKE '%cep%' 
            AND b.table_type = 'BASE TABLE'
            AND b.table_schema = 'public'
    )

    , array(SELECT b.table_name::name FROM information_schema.columns AS a
            INNER JOIN information_schema.tables as b ON (b.table_catalog = a.table_catalog AND b.table_schema = a.table_schema AND b.table_name = a.table_name)
        WHERE 
            a.column_name iLIKE '%cep%' 
            AND b.table_type = 'BASE TABLE'
            AND b.table_schema = 'public')
);

Remove all items from a FormArray in Angular

I had same problem. There are two ways to solve this issue.

Preserve subscription

You can manually clear each FormArray element by calling the removeAt(i) function in a loop.

clearFormArray = (formArray: FormArray) => {
  while (formArray.length !== 0) {
    formArray.removeAt(0)
  }
}

The advantage to this approach is that any subscriptions on your formArray, such as that registered with formArray.valueChanges, will not be lost.

See the FormArray documentation for more information.


Cleaner method (but breaks subscription references)

You can replace whole FormArray with a new one.

clearFormArray = (formArray: FormArray) => {
  formArray = this.formBuilder.array([]);
}

This approach causes an issue if you're subscribed to the formArray.valueChanges observable! If you replace the FromArray with a new array, you will lose the reference to the observable that you're subscribed to.

Which port we can use to run IIS other than 80?

you can configure IIS in IIS Mgr to use EVERY port between 1 and 65535 as long it is not used by any other application

Delete worksheet in Excel using VBA

Worksheets("Sheet1").Delete
Worksheets("Sheet2").Delete

ES6 export all values from object

Exporting each variable from your variables file. Then importing them with * as in your other file and exporting the as a constant from that file will give you a dynamic object with the named exports from the first file being attributes on the object exported from the second.

Variables.js

export const var1 = 'first';
export const var2 = 'second':
...
export const varN = 'nth';

Other.js

import * as vars from './Variables';

export const Variables = vars;

Third.js

import { Variables } from './Other';

Variables.var2 === 'second'

how to draw directed graphs using networkx in python?

I only put this in for completeness. I've learned plenty from marius and mdml. Here are the edge weights. Sorry about the arrows. Looks like I'm not the only one saying it can't be helped. I couldn't render this with ipython notebook I had to go straight from python which was the problem with getting my edge weights in sooner.

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import pylab

G = nx.DiGraph()

G.add_edges_from([('A', 'B'),('C','D'),('G','D')], weight=1)
G.add_edges_from([('D','A'),('D','E'),('B','D'),('D','E')], weight=2)
G.add_edges_from([('B','C'),('E','F')], weight=3)
G.add_edges_from([('C','F')], weight=4)


val_map = {'A': 1.0,
                   'D': 0.5714285714285714,
                              'H': 0.0}

values = [val_map.get(node, 0.45) for node in G.nodes()]
edge_labels=dict([((u,v,),d['weight'])
                 for u,v,d in G.edges(data=True)])
red_edges = [('C','D'),('D','A')]
edge_colors = ['black' if not edge in red_edges else 'red' for edge in G.edges()]

pos=nx.spring_layout(G)
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
nx.draw(G,pos, node_color = values, node_size=1500,edge_color=edge_colors,edge_cmap=plt.cm.Reds)
pylab.show()

enter image description here

I need to convert an int variable to double

I think you should casting variable or use Integer class by call out method doubleValue().

What is middleware exactly?

Middleware is a general term for software that serves to "glue together" separate, often complex and already existing, programs. Some software components that are frequently connected with middleware include enterprise applications and Web services.

How to clear memory to prevent "out of memory error" in excel vba?

The best way to help memory to be freed is to nullify large objects:

Sub Whatever()
    Dim someLargeObject as SomeObject

    'expensive computation

    Set someLargeObject = Nothing
End Sub

Also note that global variables remain allocated from one call to another, so if you don't need persistence you should either not use global variables or nullify them when you don't need them any longer.

However this won't help if:

  • you need the object after the procedure (obviously)
  • your object does not fit in memory

Another possibility is to switch to a 64 bit version of Excel which should be able to use more RAM before crashing (32 bits versions are typically limited at around 1.3GB).

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

This solution worked for me

1) Click the "Export" tab for the database

2) Click the "Custom" radio button

3) Go the section titled "Format-specific options" and change the dropdown for "Database system or older MySQL server to maximize output compatibility with:" from NONE to MYSQL40.

4) Scroll to the bottom and click "GO".

If it's related to wordpress, more info on why it is happening.

Best way to resolve file path too long exception

On Windows 8.1, using. NET 3.5, I had a similar problem.
Although the name of my file was only 239 characters length when I went to instantiate a FileInfo object with just the file name (without path) occurred an exception of type System. IO.PathTooLongException

2014-01-22 11:10:35 DEBUG LogicalDOCOutlookAddIn.LogicalDOCAddIn - fileName.Length: 239 
2014-01-22 11:10:35 ERROR LogicalDOCOutlookAddIn.LogicalDOCAddIn - Exception in ImportEmail System.IO.PathTooLongException: Percorso e/o nome di file specificato troppo lungo. Il nome di file completo deve contenere meno di 260 caratteri, mentre il nome di directory deve contenere meno di 248 caratteri.
   in System.IO.Path.NormalizePathFast(String path, Boolean fullCheck)
   in System.IO.FileInfo..ctor(String fileName)
   in LogicalDOCOutlookAddIn.LogicalDOCAddIn.GetTempFilePath(String fileName) in C:\Users\alle\Documents\Visual Studio 2010\Projects\MyAddin1Outlook20072010\MyAddin1Outlook20072010\LogicalDOCAddIn.cs:riga 692
   in LogicalDOCOutlookAddIn.LogicalDOCAddIn.ImportEmail(_MailItem mailItem, OutlookConfigXML configXML, Int64 targetFolderID, String SID) in C:\Users\alle\Documents\Visual Studio 2010\Projects\MyAddin1Outlook20072010\MyAddin1Outlook20072010\LogicalDOCAddIn.cs:riga 857
   in LogicalDOCOutlookAddIn.LogicalDOCAddIn.ImportEmails(Explorers explorers, OutlookConfigXML configXML, Int64 targetFolderID, Boolean suppressResultMB) in C:\Users\alle\Documents\Visual Studio 2010\Projects\MyAddin1Outlook20072010\MyAddin1Outlook20072010\LogicalDOCAddIn.cs:riga 99

I resolved the problem trimming the file name to 204 characters (extension included).

Counting the number of option tags in a select tag in jQuery

The best form is this

$('#example option').length

deleting folder from java

I wrote a method for this sometime back. It deletes the specified directory and returns true if the directory deletion was successful.

/**
 * Delets a dir recursively deleting anything inside it.
 * @param dir The dir to delete
 * @return true if the dir was successfully deleted
 */
public static boolean deleteDirectory(File dir) {
    if(! dir.exists() || !dir.isDirectory())    {
        return false;
    }

    String[] files = dir.list();
    for(int i = 0, len = files.length; i < len; i++)    {
        File f = new File(dir, files[i]);
        if(f.isDirectory()) {
            deleteDirectory(f);
        }else   {
            f.delete();
        }
    }
    return dir.delete();
}

Define global variable with webpack

I solved this issue by setting the global variables as a static properties on the classes to which they are most relevant. In ES5 it looks like this:

var Foo = function(){...};
Foo.globalVar = {};

Switch case in C# - a constant value is expected

There is this trick which was shared with me (don't ask for details - won't be able to provide them, but it works for me):

switch (variable_1)
{
    case var value when value == variable_2: // that's the trick
        DoSomething();
        break;
    default:
        DoSomethingElse();
        break;
}

Copying formula to the next row when inserting a new row

Make the area with your data and formulas a Table:

enter image description here

Then adding new information in the next line will copy all formulas in that table for the new line. Data validation will also be applied for the new row as it was for the whole column. This is indeed Excel being smarter with your data.

NO VBA required...

Which comes first in a 2D array, rows or columns?

In Java, there are no multi-dimension arrays. There are arrays of arrays. So:

int[][] array = new int[2][3];

It actually consists of two arrays, each has three elements.

Put byte array to JSON and vice versa

If your byte array may contain runs of ASCII characters that you'd like to be able to see, you might prefer BAIS (Byte Array In String) format instead of Base64. The nice thing about BAIS is that if all the bytes happen to be ASCII, they are converted 1-to-1 to a string (e.g. byte array {65,66,67} becomes simply "ABC") Also, BAIS often gives you a smaller file size than Base64 (this isn't guaranteed).

After converting the byte array to a BAIS string, write it to JSON like you would any other string.

Here is a Java class (ported from the original C#) that converts byte arrays to string and back.

import java.io.*;
import java.lang.*;
import java.util.*;

public class ByteArrayInString
{
  // Encodes a byte array to a string with BAIS encoding, which 
  // preserves runs of ASCII characters unchanged.
  //
  // For simplicity, this method's base-64 encoding always encodes groups of 
  // three bytes if possible (as four characters). This decision may 
  // unfortunately cut off the beginning of some ASCII runs.
  public static String convert(byte[] bytes) { return convert(bytes, true); }
  public static String convert(byte[] bytes, boolean allowControlChars)
  {
    StringBuilder sb = new StringBuilder();
    int i = 0;
    int b;
    while (i < bytes.length)
    {
      b = get(bytes,i++);
      if (isAscii(b, allowControlChars))
        sb.append((char)b);
      else {
        sb.append('\b');
        // Do binary encoding in groups of 3 bytes
        for (;; b = get(bytes,i++)) {
          int accum = b;
          System.out.println("i="+i);
          if (i < bytes.length) {
            b = get(bytes,i++);
            accum = (accum << 8) | b;
            if (i < bytes.length) {
              b = get(bytes,i++);
              accum = (accum << 8) | b;
              sb.append(encodeBase64Digit(accum >> 18));
              sb.append(encodeBase64Digit(accum >> 12));
              sb.append(encodeBase64Digit(accum >> 6));
              sb.append(encodeBase64Digit(accum));
              if (i >= bytes.length)
                break;
            } else {
              sb.append(encodeBase64Digit(accum >> 10));
              sb.append(encodeBase64Digit(accum >> 4));
              sb.append(encodeBase64Digit(accum << 2));
              break;
            }
          } else {
            sb.append(encodeBase64Digit(accum >> 2));
            sb.append(encodeBase64Digit(accum << 4));
            break;
          }
          if (isAscii(get(bytes,i), allowControlChars) &&
            (i+1 >= bytes.length || isAscii(get(bytes,i), allowControlChars)) &&
            (i+2 >= bytes.length || isAscii(get(bytes,i), allowControlChars))) {
            sb.append('!'); // return to ASCII mode
            break;
          }
        }
      }
    }
    return sb.toString();
  }

  // Decodes a BAIS string back to a byte array.
  public static byte[] convert(String s)
  {
    byte[] b;
    try {
      b = s.getBytes("UTF8");
    } catch(UnsupportedEncodingException e) { 
      throw new RuntimeException(e.getMessage());
    }
    for (int i = 0; i < b.length - 1; ++i) {
      if (b[i] == '\b') {
        int iOut = i++;

        for (;;) {
          int cur;
          if (i >= b.length || ((cur = get(b, i)) < 63 || cur > 126))
            throw new RuntimeException("String cannot be interpreted as a BAIS array");
          int digit = (cur - 64) & 63;
          int zeros = 16 - 6; // number of 0 bits on right side of accum
          int accum = digit << zeros;

          while (++i < b.length)
          {
            if ((cur = get(b, i)) < 63 || cur > 126)
              break;
            digit = (cur - 64) & 63;
            zeros -= 6;
            accum |= digit << zeros;
            if (zeros <= 8)
            {
              b[iOut++] = (byte)(accum >> 8);
              accum <<= 8;
              zeros += 8;
            }
          }

          if ((accum & 0xFF00) != 0 || (i < b.length && b[i] != '!'))
            throw new RuntimeException("String cannot be interpreted as BAIS array");
          i++;

          // Start taking bytes verbatim
          while (i < b.length && b[i] != '\b')
            b[iOut++] = b[i++];
          if (i >= b.length)
            return Arrays.copyOfRange(b, 0, iOut);
          i++;
        }
      }
    }
    return b;
  }

  static int get(byte[] bytes, int i) { return ((int)bytes[i]) & 0xFF; }

  public static int decodeBase64Digit(char digit)
    { return digit >= 63 && digit <= 126 ? (digit - 64) & 63 : -1; }
  public static char encodeBase64Digit(int digit)
    { return (char)((digit + 1 & 63) + 63); }
  static boolean isAscii(int b, boolean allowControlChars)
    { return b < 127 && (b >= 32 || (allowControlChars && b != '\b')); }
}

See also: C# unit tests.

Can't specify the 'async' modifier on the 'Main' method of a console app

On MSDN, the documentation for Task.Run Method (Action) provides this example which shows how to run a method asynchronously from main:

using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
    public static void Main()
    {
        ShowThreadInfo("Application");

        var t = Task.Run(() => ShowThreadInfo("Task") );
        t.Wait();
    }

    static void ShowThreadInfo(String s)
    {
        Console.WriteLine("{0} Thread ID: {1}",
                          s, Thread.CurrentThread.ManagedThreadId);
    }
}
// The example displays the following output:
//       Application thread ID: 1
//       Task thread ID: 3

Note this statement that follows the example:

The examples show that the asynchronous task executes on a different thread than the main application thread.

So, if instead you want the task to run on the main application thread, see the answer by @StephenCleary.

And regarding the thread on which the task runs, also note Stephen's comment on his answer:

You can use a simple Wait or Result, and there's nothing wrong with that. But be aware that there are two important differences: 1) all async continuations run on the thread pool rather than the main thread, and 2) any exceptions are wrapped in an AggregateException.

(See Exception Handling (Task Parallel Library) for how to incorporate exception handling to deal with an AggregateException.)


Finally, on MSDN from the documentation for Task.Delay Method (TimeSpan), this example shows how to run an asynchronous task that returns a value:

using System;
using System.Threading.Tasks;

public class Example
{
    public static void Main()
    {
        var t = Task.Run(async delegate
                {
                    await Task.Delay(TimeSpan.FromSeconds(1.5));
                    return 42;
                });
        t.Wait();
        Console.WriteLine("Task t Status: {0}, Result: {1}",
                          t.Status, t.Result);
    }
}
// The example displays the following output:
//        Task t Status: RanToCompletion, Result: 42

Note that instead of passing a delegate to Task.Run, you can instead pass a lambda function like this:

var t = Task.Run(async () =>
        {
            await Task.Delay(TimeSpan.FromSeconds(1.5));
            return 42;
        });