Programs & Examples On #On clause

SQL JOIN - WHERE clause vs. ON clause

  • Does not matter for inner joins

  • Matters for outer joins

    a. WHERE clause: After joining. Records will be filtered after join has taken place.

    b. ON clause - Before joining. Records (from right table) will be filtered before joining. This may end up as null in the result (since OUTER join).



Example: Consider the below tables:

    1. documents:
     | id    | name        |
     --------|-------------|
     | 1     | Document1   |
     | 2     | Document2   |
     | 3     | Document3   |
     | 4     | Document4   |
     | 5     | Document5   |


    2. downloads:
     | id   | document_id   | username |
     |------|---------------|----------|
     | 1    | 1             | sandeep  |
     | 2    | 1             | simi     |
     | 3    | 2             | sandeep  |
     | 4    | 2             | reya     |
     | 5    | 3             | simi     |

a) Inside WHERE clause:

  SELECT documents.name, downloads.id
    FROM documents
    LEFT OUTER JOIN downloads
      ON documents.id = downloads.document_id
    WHERE username = 'sandeep'

 For above query the intermediate join table will look like this.

    | id(from documents) | name         | id (from downloads) | document_id | username |
    |--------------------|--------------|---------------------|-------------|----------|
    | 1                  | Document1    | 1                   | 1           | sandeep  |
    | 1                  | Document1    | 2                   | 1           | simi     |
    | 2                  | Document2    | 3                   | 2           | sandeep  |
    | 2                  | Document2    | 4                   | 2           | reya     |
    | 3                  | Document3    | 5                   | 3           | simi     |
    | 4                  | Document4    | NULL                | NULL        | NULL     |
    | 5                  | Document5    | NULL                | NULL        | NULL     |

  After applying the `WHERE` clause and selecting the listed attributes, the result will be: 

   | name         | id |
   |--------------|----|
   | Document1    | 1  |
   | Document2    | 3  | 

b) Inside JOIN clause

  SELECT documents.name, downloads.id
  FROM documents
    LEFT OUTER JOIN downloads
      ON documents.id = downloads.document_id
        AND username = 'sandeep'

For above query the intermediate join table will look like this.

    | id(from documents) | name         | id (from downloads) | document_id | username |
    |--------------------|--------------|---------------------|-------------|----------|
    | 1                  | Document1    | 1                   | 1           | sandeep  |
    | 2                  | Document2    | 3                   | 2           | sandeep  |
    | 3                  | Document3    | NULL                | NULL        | NULL     |
    | 4                  | Document4    | NULL                | NULL        | NULL     |
    | 5                  | Document5    | NULL                | NULL        | NULL     |

Notice how the rows in `documents` that did not match both the conditions are populated with `NULL` values.

After Selecting the listed attributes, the result will be: 

   | name       | id   |
   |------------|------|
   |  Document1 | 1    |
   |  Document2 | 3    | 
   |  Document3 | NULL |
   |  Document4 | NULL | 
   |  Document5 | NULL | 

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15

For me it worked, by removing the jars in question from the war. With Maven, I just had to exclude for example

    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxb-provider</artifactId>
        <version>${resteasy.version}</version>
        <exclusions>
            <exclusion>
                <groupId>com.sun.istack</groupId>
                <artifactId>istack-commons-runtime</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.jvnet.staxex</groupId>
                <artifactId>stax-ex</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.glassfish.jaxb</groupId>
                <artifactId>txw2</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.sun.xml.fastinfoset</groupId>
                <artifactId>FastInfoset</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

Using CookieContainer with WebClient class

I think there's cleaner way where you don't have to create a new webclient (and it'll work with 3rd party libraries as well)

internal static class MyWebRequestCreator
{
    private static IWebRequestCreate myCreator;

    public static IWebRequestCreate MyHttp
    {
        get
        {
            if (myCreator == null)
            {
                myCreator = new MyHttpRequestCreator();
            }
            return myCreator;
        }
    }

    private class MyHttpRequestCreator : IWebRequestCreate
    {
        public WebRequest Create(Uri uri)
        {
            var req = System.Net.WebRequest.CreateHttp(uri);
            req.CookieContainer = new CookieContainer();
            return req;
        }
    }
}

Now all you have to do is opt in for which domains you want to use this:

    WebRequest.RegisterPrefix("http://example.com/", MyWebRequestCreator.MyHttp);

That means ANY webrequest that goes to example.com will now use your custom webrequest creator, including the standard webclient. This approach means you don't have to touch all you code. You just call the register prefix once and be done with it. You can also register for "http" prefix to opt in for everything everywhere.

MySQL Data Source not appearing in Visual Studio

Stuzor and hexcodes solution worked for me as well. However, if you do want the latest connector you have to download another product. From the oracle website:

Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).

Can someone post a well formed crossdomain.xml sample?

A version of crossdomain.xml used to be packaged with the HTML5 Boilerplate which is the product of many years of iterative development and combined community knowledge. However, it has since been deleted from the repository. I've copied it verbatim here, and included a link to the commit where it was deleted below.

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
  <!-- Read this: https://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html -->

  <!-- Most restrictive policy: -->
  <site-control permitted-cross-domain-policies="none"/>

  <!-- Least restrictive policy: -->
  <!--
  <site-control permitted-cross-domain-policies="all"/>
  <allow-access-from domain="*" to-ports="*" secure="false"/>
  <allow-http-request-headers-from domain="*" headers="*" secure="false"/>
  -->
</cross-domain-policy>

Deleted in #1881
https://github.com/h5bp/html5-boilerplate/commit/58a2ba81d250301e7b5e3da28ae4c1b42d91b2c2

How to end a session in ExpressJS

The question didn't clarify what type of session store was being used. Both answers seem to be correct.

For cookie based sessions:

From http://expressjs.com/api.html#cookieSession

req.session = null // Deletes the cookie.

For Redis, etc based sessions:

req.session.destroy // Deletes the session in the database.

Stopping a windows service when the stop option is grayed out

I solved the problem with the following steps:

  1. Open "services.msc" from command / Windows RUN.

  2. Find the service (which is greyed out).

  3. Double click on that service and go to the "Recovery" tab.

  4. Ensure that

    • First Failure action is selected as "Take No action".
    • Second Failure action is selected as "Take No action".
    • Subsequent Failures action is selected as "Take No action".

    and Press OK.

Now, the service will not try to restart and you can able to delete the greyed out service from services list (i.e. greyed out will be gone).

Maven: add a dependency to a jar by relative path

One small addition to the solution posted by Pascal

When I followed this route, I got an error in maven while installing ojdbc jar.

[INFO] --- maven-install-plugin:2.5.1:install-file (default-cli) @ validator ---
[INFO] pom.xml not found in ojdbc14.jar

After adding -DpomFile, the problem was resolved.

$ mvn install:install-file -Dfile=./lib/ojdbc14.jar -DgroupId=ojdbc \
   -DartifactId=ojdbc -Dversion=14 -Dpackaging=jar -DlocalRepositoryPath=./repo \
   -DpomFile=~/.m2/repository/ojdbc/ojdbc/14/ojdbc-14.pom

sudo in php exec()

I think you can bring specific access to user and command with visudo something like this:

nobody ALL = NOPASSWD: /path/to/osascript myscript.scpt

and with php:

@exec("sudo /path/to/osascript myscript.scpt ");

supposing nobody user is running apache.

Can a relative sitemap url be used in a robots.txt?

Google crawlers are not smart enough, they can't crawl relative URLs, that's why it's always recommended to use absolute URL's for better crawlability and indexability.

Therefore, you can not use this variation

> sitemap: /sitemap.xml

Recommended syntax is

Sitemap: https://www.yourdomain.com/sitemap.xml

Note:

  • Don't forgot to capitalise the first letter in "sitemap"
  • Don't forgot to put space after "Sitemap:"

browser sessionStorage. share between tabs?

Actually looking at other areas, if you open with _blank it keeps the sessionStorage as long as you're opening the tab when the parent is open:

In this link, there's a good jsfiddle to test it. sessionStorage on new window isn't empty, when following a link with target="_blank"

What does <![CDATA[]]> in XML mean?

From Wikipedia:

[In] an XML document or external parsed entity, a CDATA section is a section of element content that is marked for the parser to interpret as only character data, not markup.

http://en.wikipedia.org/wiki/CDATA

Thus: text inside CDATA is seen by the parser but only as characters not as XML nodes.

Append text with .bat

Any line starting with a "REM" is treated as a comment, nothing is executed including the redirection.

Also, the %date% variable may contain "/" characters which are treated as path separator characters, leading to the system being unable to create the desired log file.

How do I get the first n characters of a string without checking the size or going out of bounds?

Kotlin: (If anyone needs)

var mText = text.substring(0, text.length.coerceAtMost(20))

Data was not saved: object references an unsaved transient instance - save the transient instance before flushing

I had the same problem. In my case it arises, because the lookup-table "country" has an existing record with countryId==0 and a primitive primary key and I try to save a User with a countryID==0. Change the primary key of country to Integer. Now Hibernate can identify new records.

For the recommendation of using wrapper classes as primary key see this stackoverflow question

How to use format() on a moment.js duration?

You can use numeral.js to format your duration:

numeral(your_duration.asSeconds()).format('00:00:00') // result: hh:mm:ss

JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

- First to me Iterating and Looping are 2 different things.

Eg: Increment a variable till 5 is Looping.

    int count = 0;

    for (int i=0 ; i<5 ; i++){

        count = count + 1;

   }

Eg: Iterate over the Array to print out its values, is about Iteration

    int[] arr = {5,10,15,20,25};

    for (int i=0 ; i<arr.length ; i++){

        System.out.println(arr[i]);

   }

Now about all the Loops:

- Its always better to use For-Loop when you know the exact nos of time you gonna Loop, and if you are not sure of it go for While-Loop. Yes out there many geniuses can say that it can be done gracefully with both of them and i don't deny with them...but these are few things which makes me execute my program flawlessly...

For Loop :

int sum = 0; 

for (int i = 1; i <= 100; i++) {

  sum += i; 

}

 System.out.println("The sum is " + sum);

The Difference between While and Do-While is as Follows :

- While is a Entry Control Loop, Condition is checked in the Beginning before entering the loop.

- Do-While is a Exit Control Loop, Atleast once the block is always executed then the Condition is checked.

While Loop :

int sum = 0; 
int i = 0;       // i is 0 Here

    while (i<100) {

      sum += i; 
      i++;

    }

  System.out.println("The sum is " + sum);

do-While :

int sum = 0; 
int i = 0;      // i is 0 Here

    do{ 

      sum += i; 
       i++
    }while(i < 100; );

     System.out.println("The sum is " + sum);

From Java 5 we also have For-Each Loop to iterate over the Collections, even its handy with Arrays.

ArrayList<String> arr = new ArrayList<String>();

arr.add("Vivek");
arr.add("Is");
arr.add("Good");
arr.add("Boy");

for (String str : arr){         // str represents the value in each index of arr

    System.out.println(str);     

 }

"android.view.WindowManager$BadTokenException: Unable to add window" on buider.show()

Try this :

    public class <class> extends Activity{

    private AlertDialog.Builder builder;

    public void onCreate(Bundle savedInstanceState) {
                    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
                    super.onCreate(savedInstanceState);

                setContentView(R.layout.<view>); 

                builder = new AlertDialog.Builder(<class>.this);
                builder.setCancelable(true);
                builder.setMessage(<message>);
                builder.setInverseBackgroundForced(true);

        //call the <className> class to execute
}

    private class <className> extends AsyncTask<String, Void, String>{

    protected String doInBackground(String... params) {

    }
    protected void onPostExecute(String result){
        if(page.contains("error")) //when not subscribed
        {   
           if(builder!=null){
                builder.setNeutralButton("Ok",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton){
                    dialog.dismiss();
                        if(!<condition>)
                        {
                        try
                        {
                        String pl = ""; 

                        mHelper.<flow>(<class>.this, SKU, RC_REQUEST, 
                        <listener>, pl);
                        }

                        catch(Exception e)
                        {
                        e.printStackTrace();
                        }
                    }  
                }
            });

            builder.show();
        }
    }

}
}

Parse JSON String to JSON Object in C#.NET

I see that this question is very old, but this is the solution I used for the same problem, and it seems to require a bit less code than the others.

As @Maloric mentioned in his answer to this question:

var jo = JObject.Parse(myJsonString);

To use JObject, you need the following in your class file

using Newtonsoft.Json.Linq;

Encrypt and Decrypt in Java

public class GenerateEncryptedPassword {

    public static void main(String[] args){

        Scanner sc= new Scanner(System.in);    
        System.out.println("Please enter the password that needs to be encrypted :");
        String input = sc.next();

        try {
            String encryptedPassword= AESencrp.encrypt(input);
            System.out.println("Encrypted password generated is :"+encryptedPassword);
        } catch (Exception ex) {
            Logger.getLogger(GenerateEncryptedPassword.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Setting a max height on a table

You can do this by using the following css.

.scroll-thead{
    width: 100%;
    display: inline-table;
}

.scroll-tbody-y
{
    display: block;
    overflow-y: scroll;
}

.table-body{
    height: /*fix height here*/;
}

Following is the HTML.

<table>
 <thead class="scroll-thead">
          <tr> 
           <th>Key</th>
           <th>Value</th>
          </tr> 
         </thead>
         <tbody class="scroll-tbody-y table-body">
          <tr> 
          <td>Blah</td> 
          <td>Blah</td> 
          </tr> 
</tbody>
</table>

JSFiddle

How to write new line character to a file in Java

In EDIT 2:

while((line = bufferedReader.readLine()) != null)
{
  sb.append(line); //append the lines to the string
  sb.append('\n'); //append new line
} //end while

you are reading the text file, and appending a newline to it. Don't append newline, which will not show a newline in some simple-minded Windows editors like Notepad. Instead append the OS-specific line separator string using:

sb.append(System.lineSeparator()); (for Java 1.7 and 1.8) or sb.append(System.getProperty("line.separator")); (Java 1.6 and below)

Alternatively, later you can use String.replaceAll() to replace "\n" in the string built in the StringBuffer with the OS-specific newline character:

String updatedText = text.replaceAll("\n", System.lineSeparator())

but it would be more efficient to append it while you are building the string, than append '\n' and replace it later.

Finally, as a developer, if you are using notepad for viewing or editing files, you should drop it, as there are far more capable tools like Notepad++, or your favorite Java IDE.

Searching word in vim?

like this:

/\<word\>

\< means beginning of a word, and \> means the end of a word,

Adding @Roe's comment:
VIM provides a shortcut for this. If you already have word on screen and you want to find other instances of it, you can put the cursor on the word and press '*' to search forward in the file or '#' to search backwards.

Autocomplete syntax for HTML or PHP in Notepad++. Not auto-close, autocompelete

If you want extended auto-completion for PHP (not only for the code in the current window or standard classes), try out the "ACCPC" plugin: https://github.com/StanDog/npp-phpautocompletion

jQuery .live() vs .on() method for adding a click event after loading dynamic html

I know it's a little late for an answer, but I've created a polyfill for the .live() method. I've tested it in jQuery 1.11, and it seems to work pretty well. I know that we're supposed to implement the .on() method wherever possible, but in big projects, where it's not possible to convert all .live() calls to the equivalent .on() calls for whatever reason, the following might work:

if(jQuery && !jQuery.fn.live) {
    jQuery.fn.live = function(evt, func) {
        $('body').on(evt, this.selector, func);
    }
}

Just include it after you load jQuery and before you call live().

How to input a regex in string.replace?

str.replace() does fixed replacements. Use re.sub() instead.

Unit Testing: DateTime.Now

Regarding to @crabcrusherclamcollector answer there is issue when using that approach in EF queries (System.NotSupportedException: The LINQ expression node type 'Invoke' is not supported in LINQ to Entities). I modified implementation to that:

public static class SystemTime
    {
        private static Func<DateTime> UtcNowFunc = () => DateTime.UtcNow;

        public static void SetDateTime(DateTime dateTimeNow)
        {
            UtcNowFunc = () => dateTimeNow;
        }

        public static void ResetDateTime()
        {
            UtcNowFunc = () => DateTime.UtcNow;
        }

        public static DateTime UtcNow
        {
            get
            {
                DateTime now = UtcNowFunc.Invoke();
                return now;
            }
        }
    }

What does "zend_mm_heap corrupted" mean

If you are using traits and the trait is loaded after the class (ie. the case of autoloading) you need to load the trait beforehand.

https://bugs.php.net/bug.php?id=62339

Note: this bug is very very random; due to it's nature.

Align two inline-blocks left and right on same line

For both elements use

display: inline-block;

the for the 'nav' element use

float: right;

Find all zero-byte files in directory and subdirectories

To print the names of all files in and below $dir of size 0:

find "$dir" -size 0

Note that not all implementations of find will produce output by default, so you may need to do:

find "$dir" -size 0 -print

Two comments on the final loop in the question:

Rather than iterating over every other word in a string and seeing if the alternate values are zero, you can partially eliminate the issue you're having with whitespace by iterating over lines. eg:

printf '1 f1\n0 f 2\n10 f3\n' | while read size path; do
    test "$size" -eq 0 && echo "$path"; done

Note that this will fail in your case if any of the paths output by ls contain newlines, and this reinforces 2 points: don't parse ls, and have a sane naming policy that doesn't allow whitespace in paths.

Secondly, to output the data from the loop, there is no need to store the output in a variable just to echo it. If you simply let the loop write its output to stdout, you accomplish the same thing but avoid storing it.

System.Net.Http: missing from namespace? (using .net 4.5)

HttpClient lives in the System.Net.Http namespace.

You'll need to add:

using System.Net.Http;

And make sure you are referencing System.Net.Http.dll in .NET 4.5.


The code posted doesn't appear to do anything with webClient. Is there something wrong with the code that is actually compiling using HttpWebRequest?


Update

To open the Add Reference dialog right-click on your project in Solution Explorer and select Add Reference.... It should look something like:

enter image description here

Explain the "setUp" and "tearDown" Python methods used in test cases

In general you add all prerequisite steps to setUp and all clean-up steps to tearDown.

You can read more with examples here.

When a setUp() method is defined, the test runner will run that method prior to each test. Likewise, if a tearDown() method is defined, the test runner will invoke that method after each test.

For example you have a test that requires items to exist, or certain state - so you put these actions(creating object instances, initializing db, preparing rules and so on) into the setUp.

Also as you know each test should stop in the place where it was started - this means that we have to restore app state to it's initial state - e.g close files, connections, removing newly created items, calling transactions callback and so on - all these steps are to be included into the tearDown.

So the idea is that test itself should contain only actions that to be performed on the test object to get the result, while setUp and tearDown are the methods to help you to leave your test code clean and flexible.

You can create a setUp and tearDown for a bunch of tests and define them in a parent class - so it would be easy for you to support such tests and update common preparations and clean ups.

If you are looking for an easy example please use the following link with example

Volatile boolean vs AtomicBoolean

If you have only one thread modifying your boolean, you can use a volatile boolean (usually you do this to define a stop variable checked in the thread's main loop).

However, if you have multiple threads modifying the boolean, you should use an AtomicBoolean. Else, the following code is not safe:

boolean r = !myVolatileBoolean;

This operation is done in two steps:

  1. The boolean value is read.
  2. The boolean value is written.

If an other thread modify the value between #1 and 2#, you might got a wrong result. AtomicBoolean methods avoid this problem by doing steps #1 and #2 atomically.

How to get rid of blank pages in PDF exported from SSRS

I've successfully used pdftk to remove pages I didn't want/need in pdfs. You can download the program here

You might try something like the following. Taken from here under examples

Remove 'page 13' from in1.pdf to create out1.pdf pdftk in.pdf cat 1-12 14-end output out1.pdf

or:

pdftk A=in1.pdf cat A1-12 A14-end output out1.pdf

Find row in datatable with specific id

You can use LINQ to DataSet/DataTable

var rows = dt.AsEnumerable()
               .Where(r=> r.Field<int>("ID") == 5);

Since each row has a unique ID, you should use Single/SingleOrDefault which would throw exception if you get multiple records back.

DataRow dr = dt.AsEnumerable()
               .SingleOrDefault(r=> r.Field<int>("ID") == 5);

(Substitute int for the type of your ID field)

How to pass a list from Python, by Jinja2 to JavaScript

You can do this with Jinja's tojson filter, which

Dumps a structure to JSON so that it’s safe to use in <script> tags [and] in any place in HTML with the notable exception of double quoted attributes.

For example, in your Python, write:

some_template.render(list_of_items=list_of_items)

... or, in the context of a Flask endpoint:

return render_template('your_template.html', list_of_items=list_of_items)

Then in your template, write this:

{% for item in list_of_items %}
<span onclick='somefunction({{item | tojson}})'>{{item}}</span><br>
{% endfor %}

(Note that the onclick attribute is single-quoted. This is necessary since |tojson escapes ' characters but not " characters in its output, meaning that it can be safely used in single-quoted HTML attributes but not double-quoted ones.)

Or, to use list_of_items in an inline script instead of an HTML attribute, write this:

<script>
const jsArrayOfItems = {{list_of_items | tojson}};
// ... do something with jsArrayOfItems in JavaScript ...
</script>

DON'T use json.dumps to JSON-encode variables in your Python code and pass the resulting JSON text to your template. This will produce incorrect output for some string values, and will expose you to XSS if you're trying to encode user-provided values. This is because Python's built-in json.dumps doesn't escape characters like < and > (which need escaping to safely template values into inline <script>s, as noted at https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements) or single quotes (which need escaping to safely template values into single-quoted HTML attributes).

If you're using Flask, note that Flask injects a custom tojson filter instead of using Jinja's version. However, everything written above still applies. The two versions behave almost identically; Flask's just allows for some app-specific configuration that isn't available in Jinja's version.

Get the element triggering an onclick event in jquery?

If you don't want to pass the clicked on element to the function through a parameter, then you need to access the event object that is happening, and get the target from that object. This is most easily done if you bind the click event like this:

$('#sendButton').click(function(e){
    var SendButton = $(e.target);
    var TheForm = SendButton.parents('form');
    TheForm.submit();

    return false;
});

Simplest way to detect a mobile device in PHP

<?php 

//-- Very simple way
$useragent = $_SERVER['HTTP_USER_AGENT']; 
$iPod = stripos($useragent, "iPod"); 
$iPad = stripos($useragent, "iPad"); 
$iPhone = stripos($useragent, "iPhone");
$Android = stripos($useragent, "Android"); 
$iOS = stripos($useragent, "iOS");
//-- You can add billion devices 

$DEVICE = ($iPod||$iPad||$iPhone||$Android||$iOS);

if (!$DEVICE) { ?>

<!-- What you want for all non-mobile devices. Anything with all HTML, PHP, CSS, even full page codes-->

<?php }else{ ?> 

<!-- What you want for all mobile devices. Anything with all HTML, PHP, CSS, even full page codes --> 

<?php } ?>

PHP Echo text Color

this works for me every time try this.

echo "<font color='blue'>".$myvariable."</font>";

since font is not supported in html5 you can do this

echo "<p class="variablecolor">".$myvariable."</p>";

then in css do

.variablecolor{
color: blue;}

How to unpublish an app in Google Play Developer Console

FYI, they've updated the Google Play developer page again. Now, at the far right, click the vertical ellipsis (like a colon with an extra dot in it). That now has the 'Unpublish App' option.

Rename all files in a folder with a prefix in a single command

Try the rename command in the folder with the files:

rename 's/^/Unix_/' *

The argument of rename (sed s command) indicates to replace the regex ^ with Unix_. The caret (^) is a special character that means start of the line.

How to capitalize the first letter of a String in Java?

The code i have posted will remove underscore(_) symbol and extra spaces from String and also it will capitalize first letter of every new word in String

private String capitalize(String txt){ 
  List<String> finalTxt=new ArrayList<>();

  if(txt.contains("_")){
       txt=txt.replace("_"," ");
  }

  if(txt.contains(" ") && txt.length()>1){
       String[] tSS=txt.split(" ");
       for(String tSSV:tSS){ finalTxt.add(capitalize(tSSV)); }  
  }

  if(finalTxt.size()>0){
       txt="";
       for(String s:finalTxt){ txt+=s+" "; }
  }

  if(txt.endsWith(" ") && txt.length()>1){
       txt=txt.substring(0, (txt.length()-1));
       return txt;
  }

  txt = txt.substring(0,1).toUpperCase() + txt.substring(1).toLowerCase();
  return txt;
}

Service Temporarily Unavailable Magento?

If you run into this problem (like I did) and NO maintenance.flag file exists anywhere, it's the Redis cache that's causing the problem; clear it.

I had to clear the Redis cache by contacting my hosting company and let them do it because I don't have access to that cache.

I figured this out using this answer: https://magento.stackexchange.com/a/55814/77803

How to do a for loop in windows command line?

You might also consider adding ".

For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus" is very good idea.

How to detect if a browser is Chrome using jQuery?

As a quick addition, and I'm surprised nobody has thought of this, you could use the in operator:

"chrome" in window

Obviously this isn't using JQuery, but I figured I'd put it since it's handy for times when you aren't using any external libraries.

How do I break a string in YAML over multiple lines?

To concatenate long lines without whitespace, use double quotes and escape the newlines with backslashes:

key: "Loremipsumdolorsitamet,consecteturadipiscingelit,seddoeiusmodtemp\
  orincididuntutlaboreetdoloremagnaaliqua."

(Thanks @Tobia)

Selenium WebDriver and DropDown Boxes

public static void mulptiTransfer(WebDriver driver, By dropdownID, String text, By to)
{   
    String valuetext = null;
    WebElement element = locateElement(driver, dropdownID, 10);
    Select select = new Select(element);
    List<WebElement> options = element.findElements(By.tagName("option"));
    for (WebElement value: options) 
    {
        valuetext = value.getText();
        if (valuetext.equalsIgnoreCase(text))
        {
            try
            {
                select.selectByVisibleText(valuetext);
                locateElement(driver, to, 5).click();                           
                break;
            }
            catch (Exception e)
            {
                System.out.println(valuetext + "Value not found in Dropdown to Select");
            }       
        }
    }
}

Why does the JFrame setSize() method not set the size correctly?

There are lots of good reasons for setting the size of a frame. One is to remember the last size the user set, and restore those settings. I have this code which seems to work for me:

package javatools.swing;
import java.util.prefs.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.JFrame;

public class FramePositionMemory {
    public static final String WIDTH_PREF = "-width";

    public static final String HEIGHT_PREF = "-height";

    public static final String XPOS_PREF = "-xpos";

    public static final String YPOS_PREF = "-ypos";
    String prefix;
    Window frame;
    Class<?> cls;

    public FramePositionMemory(String prefix, Window frame, Class<?> cls) {
        this.prefix = prefix;
        this.frame = frame;
        this.cls = cls;
    }

    public void loadPosition() {
        Preferences prefs = (Preferences)Preferences.userNodeForPackage(cls);
    //  Restore the most recent mainframe size and location
        int width = prefs.getInt(prefix + WIDTH_PREF, frame.getWidth());
        int height = prefs.getInt(prefix + HEIGHT_PREF, frame.getHeight());
        System.out.println("WID: " + width + " HEI: " + height);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int xpos = (screenSize.width - width) / 2;
        int ypos = (screenSize.height - height) / 2;
        xpos = prefs.getInt(prefix + XPOS_PREF, xpos);
        ypos = prefs.getInt(prefix + YPOS_PREF, ypos);
        frame.setPreferredSize(new Dimension(width, height));
        frame.setLocation(xpos, ypos);
        frame.pack();
    }

    public void storePosition() {
        Preferences prefs = (Preferences)Preferences.userNodeForPackage(cls);
        prefs.putInt(prefix + WIDTH_PREF, frame.getWidth());
        prefs.putInt(prefix + HEIGHT_PREF, frame.getHeight());
        Point loc = frame.getLocation();
        prefs.putInt(prefix + XPOS_PREF, (int)loc.getX());
        prefs.putInt(prefix + YPOS_PREF, (int)loc.getY());
        System.out.println("STORE: " + frame.getWidth() + " " + frame.getHeight() + " " + loc.getX() + " " + loc.getY());
    }
}
public class Main {
void main(String[] args) {
        JFrame frame = new Frame();
        // SET UP YOUR FRAME HERE.
        final FramePositionMemory fm = new FramePositionMemory("scannacs2", frame, Main.class);
        frame.setSize(400, 400); // default size in the absence of previous setting
        fm.loadPosition();

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                fm.storePosition();
            }
        });
        frame.setVisible(true);
    }
}

}

Received fatal alert: handshake_failure through SSLHandshakeException

Installing Java Cryptography Extension (JCE) Unlimited Strength (for JDK7 | for JDK8) might fix this bug. Unzip the file and follow the readme to install it.

Python: How to get stdout after running os.system?

import subprocess
string="echo Hello world"
result=subprocess.getoutput(string)
print("result::: ",result)

How to print to console using swift playground?

Just Press Alt + Command + Enter to open the Assistant editor. Assistant Editor will open up the Timeline view. Timeline by default shows your console output.

Additionally You can add any line to Timeline view by pressing the small circle next to the eye icon in the results area. This will enable history for this expression. So you can see the output of the variable over last 30 secs (you can change this as well) of execution.

Sort a list of numerical strings in ascending order

in python sorted works like you want with integers:

>>> sorted([10,3,2])
[2, 3, 10]

it looks like you have a problem because you are using strings:

>>> sorted(['10','3','2'])
['10', '2', '3']

(because string ordering starts with the first character, and "1" comes before "2", no matter what characters follow) which can be fixed with key=int

>>> sorted(['10','3','2'], key=int)
['2', '3', '10']

which converts the values to integers during the sort (it is called as a function - int('10') returns the integer 10)

and as suggested in the comments, you can also sort the list itself, rather than generating a new one:

>>> l = ['10','3','2']
>>> l.sort(key=int)
>>> l
['2', '3', '10']

but i would look into why you have strings at all. you should be able to save and retrieve integers. it looks like you are saving a string when you should be saving an int? (sqlite is unusual amongst databases, in that it kind-of stores data in the same type as it is given, even if the table column type is different).

and once you start saving integers, you can also get the list back sorted from sqlite by adding order by ... to the sql command:

select temperature from temperatures order by temperature;

Change font color and background in html on mouseover

It would be great if you use :hover pseudo class over the onmouseover event

td:hover
{
   background-color:white
}

and for the default styling just use

td
{
  background-color:black
}

As you want to use these styling not over all the td elements then you need to specify the class to those elements and add styling to that class like this

.customTD
{
   background-color:black
}
.customTD:hover
{
  background-color:white;
}

You can also use :nth-child selector to select the td elements

How can you speed up Eclipse?

There could be several things that could delay the start and exit of eclipse. One of them is like familiar to what we have a lookalike in Windows. Disabling the windows animations and disabling startup activities speeds up windows to certain extent

Similar to what in eclipse we can have the same thing Windows-> General -> Preferences -> Appearance -> Turning OFF some decorative options. This would give a little boost but may not have much impact.

In my opinion, the projects in the work space you might have created should be limited to certain extent or rather creating a new work space if projects are more. For instance, when you try to run a single project on server it takes less time as compared to running several projects on the same server

Python Checking a string's first and last character

When you say [:-1] you are stripping the last element. Instead of slicing the string, you can apply startswith and endswith on the string object itself like this

if str1.startswith('"') and str1.endswith('"'):

So the whole program becomes like this

>>> str1 = '"xxx"'
>>> if str1.startswith('"') and str1.endswith('"'):
...     print "hi"
>>> else:
...     print "condition fails"
...
hi

Even simpler, with a conditional expression, like this

>>> print("hi" if str1.startswith('"') and str1.endswith('"') else "fails")
hi

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

Wait until boolean value changes it state

public Boolean test() throws InterruptedException {
    BlockingQueue<Boolean> booleanHolder = new LinkedBlockingQueue<>();
    new Thread(() -> {
        try {
            TimeUnit.SECONDS.sleep(2);
            booleanHolder.put(true);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }).start();
    return booleanHolder.poll(4, TimeUnit.SECONDS);
}

Compare two folders which has many files inside contents

Diff command in Unix is used to find the differences between files(all types). Since directory is also a type of file, the differences between two directories can easily be figure out by using diff commands. For more option use man diff on your unix box.

 -b              Ignores trailing blanks  (spaces  and  tabs)
                 and   treats  other  strings  of  blanks  as
                 equivalent.

 -i              Ignores the case of  letters.  For  example,
                 `A' will compare equal to `a'.
 -t              Expands <TAB> characters  in  output  lines.
                 Normal or -c output adds character(s) to the
                 front of each line that may adversely affect
                 the indentation of the original source lines
                 and  make  the  output  lines  difficult  to
                 interpret.  This  option  will  preserve the
                 original source's indentation.

 -w              Ignores all blanks (<SPACE> and <TAB>  char-
                 acters)  and  treats  all  other  strings of
                 blanks   as   equivalent.    For    example,
                 `if ( a == b )'   will   compare   equal  to
                 `if(a==b)'.

and there are many more.

Best Practice: Initialize JUnit class fields in setUp() or at declaration?

In addition to Alex B's answer.

It is even required to use the setUp method to instantiate resources in a certain state. Doing this in the constructor is not only a matter of timings, but because of the way JUnit runs the tests, each test state would be erased after running one.

JUnit first creates instances of the testClass for each test method and starts running the tests after each instance is created. Before running the test method, its setup method is ran, in which some state can be prepared.

If the database state would be created in the constructor, all instances would instantiate the db state right after each other, before running each tests. As of the second test, tests would run with a dirty state.

JUnits lifecycle:

  1. Create a different testclass instance for each test method
  2. Repeat for each testclass instance: call setup + call the testmethod

With some loggings in a test with two test methods you get: (number is the hashcode)

  • Creating new instance: 5718203
  • Creating new instance: 5947506
  • Setup: 5718203
  • TestOne: 5718203
  • Setup: 5947506
  • TestTwo: 5947506

Corrupted Access .accdb file: "Unrecognized Database Format"

Sometimes it might depend on whether you are using code to access the database or not. If you are using "DriverJet" in your code instead of "DriverACE" (or an older version of the DAO library) such a problem is highly probable to happen. You just need to replace "DriverJet" with "DriverACE" and test.

How to initialize a static array?

If you are creating an array then there is no difference, however, the following is neater:

String[] suit = {
  "spades", 
  "hearts", 
  "diamonds", 
  "clubs"  
};

But, if you want to pass an array into a method you have to call it like this:

myMethod(new String[] {"spades", "hearts"});

myMethod({"spades", "hearts"}); //won't compile!

How to force reloading php.ini file?

You also can use graceful restart the apache server with service apache2 reload or apachectl -k graceful. As the apache doc says:

The USR1 or graceful signal causes the parent process to advise the children to exit after their current request (or to exit immediately if they're not serving anything). The parent re-reads its configuration files and re-opens its log files. As each child dies off the parent replaces it with a child from the new generation of the configuration, which begins serving new requests immediately.

Get SSID when WIFI is connected

For me it only worked when I set the permission on the phone itself (settings -> app permissions -> location always on).

Using NOT operator in IF conditions

It really depends on what you're trying to accomplish. If you have no else clause then if(!doSomething()) seems fine. However, if you have

if(!doSomething()) {
    ...
}
else {
    // do something else
}

I'd probably reverse that logic to remove the ! operator and make the if clause slightly more clear.

Change CSS class properties with jQuery

In case you cannot use different stylesheet by dynamically loading it, you can use this function to modify CSS class. Hope it helps you...

function changeCss(className, classValue) {
    // we need invisible container to store additional css definitions
    var cssMainContainer = $('#css-modifier-container');
    if (cssMainContainer.length == 0) {
        var cssMainContainer = $('<div id="css-modifier-container"></div>');
        cssMainContainer.hide();
        cssMainContainer.appendTo($('body'));
    }

    // and we need one div for each class
    classContainer = cssMainContainer.find('div[data-class="' + className + '"]');
    if (classContainer.length == 0) {
        classContainer = $('<div data-class="' + className + '"></div>');
        classContainer.appendTo(cssMainContainer);
    }

    // append additional style
    classContainer.html('<style>' + className + ' {' + classValue + '}</style>');
}

This function will take any class name and replace any previously set values with the new value. Note, you can add multiple values by passing the following into classValue: "background: blue; color:yellow".

How to insert a row in an HTML table body in JavaScript

If you want to add a row into the tbody, get a reference to it and call its insertRow method.

_x000D_
_x000D_
var tbodyRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

// Insert a row at the end of table
var newRow = tbodyRef.insertRow();

// Insert a cell at the end of the row
var newCell = newRow.insertCell();

// Append a text node to the cell
var newText = document.createTextNode('new row');
newCell.appendChild(newText);
_x000D_
<table id="myTable">
  <thead>
    <tr>
      <th>My Header</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>initial row</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>My Footer</td>
    </tr>
  </tfoot>
</table>
_x000D_
_x000D_
_x000D_

(old demo on JSFiddle)

Easy way to dismiss keyboard?

Here's what I use in my code. It works like a charm!

In yourviewcontroller.h add:

@property (nonatomic) UITapGestureRecognizer *tapRecognizer;

Now in the .m file, add this to your ViewDidLoad function:

- (void)viewDidLoad {
    //Keyboard stuff
    tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapAnywhere:)];
    tapRecognizer.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapRecognizer];
}

Also, add this function in the .m file:

- (void)handleSingleTap:(UITapGestureRecognizer *) sender
{
    [self.view endEditing:YES];
}

user authentication libraries for node.js?

Quick simple example using mongo, for an API that provides user auth for ie Angular client

in app.js

var express = require('express');
var MongoStore = require('connect-mongo')(express);

// ...

app.use(express.cookieParser());
// obviously change db settings to suit
app.use(express.session({
    secret: 'blah1234',
    store: new MongoStore({
        db: 'dbname',
        host: 'localhost',
        port: 27017
    })
}));

app.use(app.router);

for your route something like this:

// (mongo connection stuff)

exports.login = function(req, res) {

    var email = req.body.email;
    // use bcrypt in production for password hashing
    var password = req.body.password;

    db.collection('users', function(err, collection) {
        collection.findOne({'email': email, 'password': password}, function(err, user) {
            if (err) {
                res.send(500);
            } else {
                if(user !== null) {
                    req.session.user = user;
                    res.send(200);
                } else {
                    res.send(401);
                }
            }
        });
    });
};

Then in your routes that require auth you can just check for the user session:

if (!req.session.user) {
    res.send(403);
}

Submitting a form by pressing enter without a submit button

Try:

<input type="submit" style="position: absolute; left: -9999px"/>

That will push the button waaay to the left, out of the screen. The nice thing with this is, you'd get graceful degradation when CSS is disabled.

Update - Workaround for IE7

As suggested by Bryan Downing + with tabindex to prevent tab reach this button (by Ates Goral):

<input type="submit" 
       style="position: absolute; left: -9999px; width: 1px; height: 1px;"
       tabindex="-1" />

Dealing with HTTP content in HTTPS pages

If you're looking for a quick solution to load images over HTTPS then the free reverse proxy service at https://images.weserv.nl/ may interest you. It was exactly what I was looking for.

If you're looking for a paid solution, I have previously used Cloudinary.com which also works well but is too expensive solely for this task, in my opinion.

Install a .NET windows service without InstallUtil.exe

The above examples didn't really work for me, and the link to the forum as a #1 solution is awful to dig through. Here is a class I wrote (in part), and the other bit is merged from this link I found buried somewhere

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.ServiceProcess;
using System.Runtime.InteropServices;

namespace SystemControl {
    class Services {

#region "Environment Variables"
        public static string GetEnvironment(string name, bool ExpandVariables=true) {
            if ( ExpandVariables ) {
                return System.Environment.GetEnvironmentVariable( name );
            } else {
                return (string)Microsoft.Win32.Registry.LocalMachine.OpenSubKey( @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment\" ).GetValue( name, "", Microsoft.Win32.RegistryValueOptions.DoNotExpandEnvironmentNames );
            }
        }

        public static void SetEnvironment( string name, string value ) {
            System.Environment.SetEnvironmentVariable(name, value);
        }
#endregion

#region "ServiceCalls Native"
        public static ServiceController[] List { get { return ServiceController.GetServices(); } }

        public static void Start( string serviceName, int timeoutMilliseconds ) {
            ServiceController service=new ServiceController( serviceName );
            try {
                TimeSpan timeout=TimeSpan.FromMilliseconds( timeoutMilliseconds );

                service.Start();
                service.WaitForStatus( ServiceControllerStatus.Running, timeout );
            } catch {
                // ...
            }
        }

        public static void Stop( string serviceName, int timeoutMilliseconds ) {
            ServiceController service=new ServiceController( serviceName );
            try {
                TimeSpan timeout=TimeSpan.FromMilliseconds( timeoutMilliseconds );

                service.Stop();
                service.WaitForStatus( ServiceControllerStatus.Stopped, timeout );
            } catch {
                // ...
            }
        }

        public static void Restart( string serviceName, int timeoutMilliseconds ) {
            ServiceController service=new ServiceController( serviceName );
            try {
                int millisec1=Environment.TickCount;
                TimeSpan timeout=TimeSpan.FromMilliseconds( timeoutMilliseconds );

                service.Stop();
                service.WaitForStatus( ServiceControllerStatus.Stopped, timeout );

                // count the rest of the timeout
                int millisec2=Environment.TickCount;
                timeout=TimeSpan.FromMilliseconds( timeoutMilliseconds-( millisec2-millisec1 ) );

                service.Start();
                service.WaitForStatus( ServiceControllerStatus.Running, timeout );
            } catch {
                // ...
            }
        }

        public static bool IsInstalled( string serviceName ) {
            // get list of Windows services
            ServiceController[] services=ServiceController.GetServices();

            // try to find service name
            foreach ( ServiceController service in services ) {
                if ( service.ServiceName==serviceName )
                    return true;
            }
            return false;
        }
#endregion

#region "ServiceCalls API"
        private const int STANDARD_RIGHTS_REQUIRED = 0xF0000;
        private const int SERVICE_WIN32_OWN_PROCESS = 0x00000010;

        [Flags]
        public enum ServiceManagerRights {
            Connect = 0x0001,
            CreateService = 0x0002,
            EnumerateService = 0x0004,
            Lock = 0x0008,
            QueryLockStatus = 0x0010,
            ModifyBootConfig = 0x0020,
            StandardRightsRequired = 0xF0000,
            AllAccess = (StandardRightsRequired | Connect | CreateService |
            EnumerateService | Lock | QueryLockStatus | ModifyBootConfig)
        }

        [Flags]
        public enum ServiceRights {
            QueryConfig = 0x1,
            ChangeConfig = 0x2,
            QueryStatus = 0x4,
            EnumerateDependants = 0x8,
            Start = 0x10,
            Stop = 0x20,
            PauseContinue = 0x40,
            Interrogate = 0x80,
            UserDefinedControl = 0x100,
            Delete = 0x00010000,
            StandardRightsRequired = 0xF0000,
            AllAccess = (StandardRightsRequired | QueryConfig | ChangeConfig |
            QueryStatus | EnumerateDependants | Start | Stop | PauseContinue |
            Interrogate | UserDefinedControl)
        }

        public enum ServiceBootFlag {
            Start = 0x00000000,
            SystemStart = 0x00000001,
            AutoStart = 0x00000002,
            DemandStart = 0x00000003,
            Disabled = 0x00000004
        }

        public enum ServiceState {
            Unknown = -1, // The state cannot be (has not been) retrieved.
            NotFound = 0, // The service is not known on the host server.
            Stop = 1, // The service is NET stopped.
            Run = 2, // The service is NET started.
            Stopping = 3,
            Starting = 4,
        }

        public enum ServiceControl {
            Stop = 0x00000001,
            Pause = 0x00000002,
            Continue = 0x00000003,
            Interrogate = 0x00000004,
            Shutdown = 0x00000005,
            ParamChange = 0x00000006,
            NetBindAdd = 0x00000007,
            NetBindRemove = 0x00000008,
            NetBindEnable = 0x00000009,
            NetBindDisable = 0x0000000A
        }

        public enum ServiceError {
            Ignore = 0x00000000,
            Normal = 0x00000001,
            Severe = 0x00000002,
            Critical = 0x00000003
        }

        [StructLayout(LayoutKind.Sequential)]
        private class SERVICE_STATUS {
            public int dwServiceType = 0;
            public ServiceState dwCurrentState = 0;
            public int dwControlsAccepted = 0;
            public int dwWin32ExitCode = 0;
            public int dwServiceSpecificExitCode = 0;
            public int dwCheckPoint = 0;
            public int dwWaitHint = 0;
        }

        [DllImport("advapi32.dll", EntryPoint = "OpenSCManagerA")]
        private static extern IntPtr OpenSCManager(string lpMachineName, string lpDatabaseName, ServiceManagerRights dwDesiredAccess);
        [DllImport("advapi32.dll", EntryPoint = "OpenServiceA", CharSet = CharSet.Ansi)]
        private static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, ServiceRights dwDesiredAccess);
        [DllImport("advapi32.dll", EntryPoint = "CreateServiceA")]
        private static extern IntPtr CreateService(IntPtr hSCManager, string lpServiceName, string lpDisplayName, ServiceRights dwDesiredAccess, int dwServiceType, ServiceBootFlag dwStartType, ServiceError dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, IntPtr lpdwTagId, string lpDependencies, string lp, string lpPassword);
        [DllImport("advapi32.dll")]
        private static extern int CloseServiceHandle(IntPtr hSCObject);
        [DllImport("advapi32.dll")]
        private static extern int QueryServiceStatus(IntPtr hService, SERVICE_STATUS lpServiceStatus);
        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern int DeleteService(IntPtr hService);
        [DllImport("advapi32.dll")]
        private static extern int ControlService(IntPtr hService, ServiceControl dwControl, SERVICE_STATUS lpServiceStatus);
        [DllImport("advapi32.dll", EntryPoint = "StartServiceA")]
        private static extern int StartService(IntPtr hService, int dwNumServiceArgs, int lpServiceArgVectors);

        /// <summary>
        /// Takes a service name and tries to stop and then uninstall the windows serviceError
        /// </summary>
        /// <param name="ServiceName">The windows service name to uninstall</param>
        public static void Uninstall(string ServiceName)
        {
            IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);
            try
            {
                IntPtr service = OpenService(scman, ServiceName, ServiceRights.StandardRightsRequired | ServiceRights.Stop | ServiceRights.QueryStatus);
                if (service == IntPtr.Zero)
                {
                    throw new ApplicationException("Service not installed.");
                }
                try
                {
                    StopService(service);
                    int ret = DeleteService(service);
                    if (ret == 0)
                    {
                        int error = Marshal.GetLastWin32Error();
                        throw new ApplicationException("Could not delete service " + error);
                    }
                }
                finally
                {
                    CloseServiceHandle(service);
                }
            }
            finally
            {
                CloseServiceHandle(scman);
            }
        }

        /// <summary>
        /// Accepts a service name and returns true if the service with that service name exists
        /// </summary>
        /// <param name="ServiceName">The service name that we will check for existence</param>
        /// <returns>True if that service exists false otherwise</returns>
        public static bool ServiceIsInstalled(string ServiceName)
        {
            IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);
            try
            {
                IntPtr service = OpenService(scman, ServiceName,
                ServiceRights.QueryStatus);
                if (service == IntPtr.Zero) return false;
                CloseServiceHandle(service);
                return true;
            }
            finally
            {
                CloseServiceHandle(scman);
            }
        }

        /// <summary>
        /// Takes a service name, a service display name and the path to the service executable and installs / starts the windows service.
        /// </summary>
        /// <param name="ServiceName">The service name that this service will have</param>
        /// <param name="DisplayName">The display name that this service will have</param>
        /// <param name="FileName">The path to the executable of the service</param>
        public static void InstallAndStart(string ServiceName, string DisplayName,
        string FileName)
        {
            IntPtr scman = OpenSCManager(ServiceManagerRights.Connect |
            ServiceManagerRights.CreateService);
            try
            {
                IntPtr service = OpenService(scman, ServiceName,
                ServiceRights.QueryStatus | ServiceRights.Start);
                if (service == IntPtr.Zero)
                {
                    service = CreateService(scman, ServiceName, DisplayName,
                    ServiceRights.QueryStatus | ServiceRights.Start, SERVICE_WIN32_OWN_PROCESS,
                    ServiceBootFlag.AutoStart, ServiceError.Normal, FileName, null, IntPtr.Zero,
                    null, null, null);
                }
                if (service == IntPtr.Zero)
                {
                    throw new ApplicationException("Failed to install service.");
                }
                try
                {
                    StartService(service);
                }
                finally
                {
                    CloseServiceHandle(service);
                }
            }
            finally
            {
                CloseServiceHandle(scman);
            }
        }

        /// <summary>
        /// Takes a service name and starts it
        /// </summary>
        /// <param name="Name">The service name</param>
        public static void StartService(string Name)
        {
            IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);
            try
            {
                IntPtr hService = OpenService(scman, Name, ServiceRights.QueryStatus |
                ServiceRights.Start);
                if (hService == IntPtr.Zero)
                {
                    throw new ApplicationException("Could not open service.");
                }
                try
                {
                    StartService(hService);
                }
                finally
                {
                    CloseServiceHandle(hService);
                }
            }
            finally
            {
                CloseServiceHandle(scman);
            }
        }

        /// <summary>
        /// Stops the provided windows service
        /// </summary>
        /// <param name="Name">The service name that will be stopped</param>
        public static void StopService(string Name)
        {
            IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);
            try
            {
                IntPtr hService = OpenService(scman, Name, ServiceRights.QueryStatus |
                ServiceRights.Stop);
                if (hService == IntPtr.Zero)
                {
                    throw new ApplicationException("Could not open service.");
                }
                try
                {
                    StopService(hService);
                }
                finally
                {
                    CloseServiceHandle(hService);
                }
            }
            finally
            {
                CloseServiceHandle(scman);
            }
        }

        /// <summary>
        /// Stars the provided windows service
        /// </summary>
        /// <param name="hService">The handle to the windows service</param>
        private static void StartService(IntPtr hService)
        {
            SERVICE_STATUS status = new SERVICE_STATUS();
            StartService(hService, 0, 0);
            WaitForServiceStatus(hService, ServiceState.Starting, ServiceState.Run);
        }

        /// <summary>
        /// Stops the provided windows service
        /// </summary>
        /// <param name="hService">The handle to the windows service</param>
        private static void StopService(IntPtr hService)
        {
            SERVICE_STATUS status = new SERVICE_STATUS();
            ControlService(hService, ServiceControl.Stop, status);
            WaitForServiceStatus(hService, ServiceState.Stopping, ServiceState.Stop);
        }

        /// <summary>
        /// Takes a service name and returns the <code>ServiceState</code> of the corresponding service
        /// </summary>
        /// <param name="ServiceName">The service name that we will check for his <code>ServiceState</code></param>
        /// <returns>The ServiceState of the service we wanted to check</returns>
        public static ServiceState GetServiceStatus(string ServiceName)
        {
            IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);
            try
            {
                IntPtr hService = OpenService(scman, ServiceName,
                ServiceRights.QueryStatus);
                if (hService == IntPtr.Zero)
                {
                    return ServiceState.NotFound;
                }
                try
                {
                    return GetServiceStatus(hService);
                }
                finally
                {
                    CloseServiceHandle(scman);
                }
            }
            finally
            {
                CloseServiceHandle(scman);
            }
        }

        /// <summary>
        /// Gets the service state by using the handle of the provided windows service
        /// </summary>
        /// <param name="hService">The handle to the service</param>
        /// <returns>The <code>ServiceState</code> of the service</returns>
        private static ServiceState GetServiceStatus(IntPtr hService)
        {
            SERVICE_STATUS ssStatus = new SERVICE_STATUS();
            if (QueryServiceStatus(hService, ssStatus) == 0)
            {
                throw new ApplicationException("Failed to query service status.");
            }
            return ssStatus.dwCurrentState;
        }

        /// <summary>
        /// Returns true when the service status has been changes from wait status to desired status
        /// ,this method waits around 10 seconds for this operation.
        /// </summary>
        /// <param name="hService">The handle to the service</param>
        /// <param name="WaitStatus">The current state of the service</param>
        /// <param name="DesiredStatus">The desired state of the service</param>
        /// <returns>bool if the service has successfully changed states within the allowed timeline</returns>
        private static bool WaitForServiceStatus(IntPtr hService, ServiceState
        WaitStatus, ServiceState DesiredStatus)
        {
            SERVICE_STATUS ssStatus = new SERVICE_STATUS();
            int dwOldCheckPoint;
            int dwStartTickCount;

            QueryServiceStatus(hService, ssStatus);
            if (ssStatus.dwCurrentState == DesiredStatus) return true;
            dwStartTickCount = Environment.TickCount;
            dwOldCheckPoint = ssStatus.dwCheckPoint;

            while (ssStatus.dwCurrentState == WaitStatus)
            {
                // Do not wait longer than the wait hint. A good interval is
                // one tenth the wait hint, but no less than 1 second and no
                // more than 10 seconds.

                int dwWaitTime = ssStatus.dwWaitHint / 10;

                if (dwWaitTime < 1000) dwWaitTime = 1000;
                else if (dwWaitTime > 10000) dwWaitTime = 10000;

                System.Threading.Thread.Sleep(dwWaitTime);

                // Check the status again.

                if (QueryServiceStatus(hService, ssStatus) == 0) break;

                if (ssStatus.dwCheckPoint > dwOldCheckPoint)
                {
                    // The service is making progress.
                    dwStartTickCount = Environment.TickCount;
                    dwOldCheckPoint = ssStatus.dwCheckPoint;
                }
                else
                {
                    if (Environment.TickCount - dwStartTickCount > ssStatus.dwWaitHint)
                    {
                        // No progress made within the wait hint
                        break;
                    }
                }
            }
            return (ssStatus.dwCurrentState == DesiredStatus);
        }

        /// <summary>
        /// Opens the service manager
        /// </summary>
        /// <param name="Rights">The service manager rights</param>
        /// <returns>the handle to the service manager</returns>
        private static IntPtr OpenSCManager(ServiceManagerRights Rights)
        {
            IntPtr scman = OpenSCManager(null, null, Rights);
            if (scman == IntPtr.Zero)
            {
                throw new ApplicationException("Could not connect to service control manager.");
            }
            return scman;
        }

#endregion

    }
}

To install a service, run the InstallAndStart command as follows:

  SystemControl.InstallAndStart(
                                 "apache",
                                 "Apache Web Server",
                                 @"""c:\apache\bin\httpd.exe"" -k runservice"
  );

Make sure the account that is running the program has permission to install services. You can always 'Run As Administrator' on the program.

I have also included several commands for non-api access which do not install or remove services, but you can list them and control several (start, stop, restart). You really only need to elevate permissions for installing or removing services.

There are a couple of commands for getting and setting environment variables as well, such as OPENSSL_CONF or TEMP. For the most part, the parameters and method names should be pretty self-explanatory.

Convert HashBytes to VarChar

With personal experience of using the following code within a Stored Procedure which Hashed a SP Variable I can confirm, although undocumented, this combination works 100% as per my example:

@var=SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('SHA2_512', @SPvar)), 3, 128)

Define constant variables in C++ header

It seems that bames53's answer can be extended to defining integer and non-integer constant values in namespace and class declarations even if they get included in multiple source files. It is not necessary to put the declarations in a header file but the definitions in a source file. The following example works for Microsoft Visual Studio 2015, for z/OS V2.2 XL C/C++ on OS/390, and for g++ (GCC) 8.1.1 20180502 on GNU/Linux 4.16.14 (Fedora 28). Note that the constants are declared/defined in only a single header file that gets included in multiple source files.

In foo.cc:

#include <cstdio>               // for puts

#include "messages.hh"
#include "bar.hh"
#include "zoo.hh"

int main(int argc, const char* argv[])
{
  puts("Hello!");
  bar();
  zoo();
  puts(Message::third);
  return 0;
}

In messages.hh:

#ifndef MESSAGES_HH
#define MESSAGES_HH

namespace Message {
  char const * const first = "Yes, this is the first message!";
  char const * const second = "This is the second message.";
  char const * const third = "Message #3.";
};

#endif

In bar.cc:

#include "messages.hh"
#include <cstdio>

void bar(void)
{
  puts("Wow!");
  printf("bar: %s\n", Message::first);
}

In zoo.cc:

#include <cstdio>
#include "messages.hh"

void zoo(void)
{
  printf("zoo: %s\n", Message::second);
}

In bar.hh:

#ifndef BAR_HH
#define BAR_HH

#include "messages.hh"

void bar(void);

#endif

In zoo.hh:

#ifndef ZOO_HH
#define ZOO_HH

#include "messages.hh"

void zoo(void);

#endif

This yields the following output:

Hello!
Wow!
bar: Yes, this is the first message!
zoo: This is the second message.
Message #3.

The data type char const * const means a constant pointer to an array of constant characters. The first const is needed because (according to g++) "ISO C++ forbids converting a string constant to 'char*'". The second const is needed to avoid link errors due to multiple definitions of the (then insufficiently constant) constants. Your compiler might not complain if you omit one or both of the consts, but then the source code is less portable.

Convert from List into IEnumerable format

Why not use a Single liner ...

IEnumerable<Book> _Book_IE= _Book_List as IEnumerable<Book>;

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

With C#6.0 you also have a new way of formatting date when using string interpolation e.g.

$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"

Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.

More about string interpolation.

How does one target IE7 and IE8 with valid CSS?

I would recommend looking into conditional comments and making a separate sheet for the IEs you are having problems with.

 <!--[if IE 7]>
   <link rel="stylesheet" type="text/css" href="ie7.css" />
 <![endif]-->

Store select query's output in one array in postgres

There are two ways. One is to aggregate:

SELECT array_agg(column_name::TEXT)
FROM information.schema.columns
WHERE table_name = 'aean'

The other is to use an array constructor:

SELECT ARRAY(
SELECT column_name 
FROM information.schema.columns 
WHERE table_name = 'aean')

I'm presuming this is for plpgsql. In that case you can assign it like this:

colnames := ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name='aean'
);

jquery <a> tag click event

<a href="javascript:void(0)" class="aaf" id="users_id">add as a friend</a>

on jquery

$('.aaf').on("click",function(){
  var usersid =  $(this).attr("id");
  //post code
})

//other method is to use the data attribute

<a href="javascript:void(0)" class="aaf" data-id="102" data-username="sample_username">add as a friend</a>

on jquery

$('.aaf').on("click",function(){
    var usersid =  $(this).data("id");
    var username = $(this).data("username");
})

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

On Salesforce platform this error is caused by /, the solution is to escape these as //.

Where do I download JDBC drivers for DB2 that are compatible with JDK 1.5?

I know its late but i recently ran into this situation. After wasting entire day I finally found the solution. I am suprised that I got this info on oracle's website whereas this seems nowhere to be found on IBM's website.

If you want to use JDBC drivers for DB2 that are compatible with JDK 1.5 or 1.4 , you need to use the jar db2jcc.jar, which is available in SQLLIB/java/ folder of your db2 installation.

IE11 meta element Breaks SVG

It sounds as though you're not in a modern document mode. Internet Explorer 11 shows the SVG just fine when you're in Standards Mode. Make sure that if you have an x-ua-compatible meta tag, you have it set to Edge, rather than an earlier mode.

<meta http-equiv="X-UA-Compatible" content="IE=edge">

You can determine your document mode by opening up your F12 Developer Tools and checking either the document mode dropdown (seen at top-right, currently "Edge") or the emulation tab:

enter image description here

If you do not have an x-ua-compatible meta tag (or header), be sure to use a doctype that will put the document into Standards mode, such as <!DOCTYPE html>.

enter image description here

python list in sql query as parameter

This uses parameter substitution and takes care of the single value list case:

l = [1,5,8]

get_operator = lambda x: '=' if len(x) == 1 else 'IN'
get_value = lambda x: int(x[0]) if len(x) == 1 else x

query = 'SELECT * FROM table where id ' + get_operator(l) + ' %s'

cursor.execute(query, (get_value(l),))

How to add parameters to a HTTP GET request in Android?

    HttpClient client = new DefaultHttpClient();

    Uri.Builder builder = Uri.parse(url).buildUpon();

    for (String name : params.keySet()) {
        builder.appendQueryParameter(name, params.get(name).toString());
    }

    url = builder.build().toString();
    HttpGet request = new HttpGet(url);
    HttpResponse response = client.execute(request);
    return EntityUtils.toString(response.getEntity(), "UTF-8");

how to programmatically fake a touch event to a UIButton?

If you want to do this kind of testing, you’ll love the UI Automation support in iOS 4. You can write JavaScript to simulate button presses, etc. fairly easily, though the documentation (especially the getting-started part) is a bit sparse.

Detecting a redirect in ajax request?

While the other folks who answered this question are (sadly) correct that this information is hidden from us by the browser, I thought I'd post a workaround I came up with:

I configured my server app to set a custom response header (X-Response-Url) containing the url that was requested. Whenever my ajax code receives a response, it checks if xhr.getResponseHeader("x-response-url") is defined, in which case it compares it to the url that it originally requested via $.ajax(). If the strings differ, I know there was a redirect, and additionally, what url we actually arrived at.

This does have the drawback of requiring some server-side help, and also may break down if the url gets munged (due to quoting/encoding issues etc) during the round trip... but for 99% of cases, this seems to get the job done.


On the server side, my specific case was a python application using the Pyramid web framework, and I used the following snippet:

import pyramid.events

@pyramid.events.subscriber(pyramid.events.NewResponse)
def set_response_header(event):
    request = event.request
    if request.is_xhr:
        event.response.headers['X-Response-URL'] = request.url

NSRange to Range<String.Index>

As of Swift 4 (Xcode 9), the Swift standard library provides methods to convert between Swift string ranges (Range<String.Index>) and NSString ranges (NSRange). Example:

let str = "abc"
let r1 = str.range(of: "")!

// String range to NSRange:
let n1 = NSRange(r1, in: str)
print((str as NSString).substring(with: n1)) // 

// NSRange back to String range:
let r2 = Range(n1, in: str)!
print(str[r2]) // 

Therefore the text replacement in the text field delegate method can now be done as

func textField(_ textField: UITextField,
               shouldChangeCharactersIn range: NSRange,
               replacementString string: String) -> Bool {

    if let oldString = textField.text {
        let newString = oldString.replacingCharacters(in: Range(range, in: oldString)!,
                                                      with: string)
        // ...
    }
    // ...
}

(Older answers for Swift 3 and earlier:)

As of Swift 1.2, String.Index has an initializer

init?(_ utf16Index: UTF16Index, within characters: String)

which can be used to convert NSRange to Range<String.Index> correctly (including all cases of Emojis, Regional Indicators or other extended grapheme clusters) without intermediate conversion to an NSString:

extension String {
    func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
        let from16 = advance(utf16.startIndex, nsRange.location, utf16.endIndex)
        let to16 = advance(from16, nsRange.length, utf16.endIndex)
        if let from = String.Index(from16, within: self),
            let to = String.Index(to16, within: self) {
                return from ..< to
        }
        return nil
    }
}

This method returns an optional string range because not all NSRanges are valid for a given Swift string.

The UITextFieldDelegate delegate method can then be written as

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    if let swRange = textField.text.rangeFromNSRange(range) {
        let newString = textField.text.stringByReplacingCharactersInRange(swRange, withString: string)
        // ...
    }
    return true
}

The inverse conversion is

extension String {
    func NSRangeFromRange(range : Range<String.Index>) -> NSRange {
        let utf16view = self.utf16
        let from = String.UTF16View.Index(range.startIndex, within: utf16view) 
        let to = String.UTF16View.Index(range.endIndex, within: utf16view)
        return NSMakeRange(from - utf16view.startIndex, to - from)
    }
}

A simple test:

let str = "abc"
let r1 = str.rangeOfString("")!

// String range to NSRange:
let n1 = str.NSRangeFromRange(r1)
println((str as NSString).substringWithRange(n1)) // 

// NSRange back to String range:
let r2 = str.rangeFromNSRange(n1)!
println(str.substringWithRange(r2)) // 

Update for Swift 2:

The Swift 2 version of rangeFromNSRange() was already given by Serhii Yakovenko in this answer, I am including it here for completeness:

extension String {
    func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
        let from16 = utf16.startIndex.advancedBy(nsRange.location, limit: utf16.endIndex)
        let to16 = from16.advancedBy(nsRange.length, limit: utf16.endIndex)
        if let from = String.Index(from16, within: self),
            let to = String.Index(to16, within: self) {
                return from ..< to
        }
        return nil
    }
}

The Swift 2 version of NSRangeFromRange() is

extension String {
    func NSRangeFromRange(range : Range<String.Index>) -> NSRange {
        let utf16view = self.utf16
        let from = String.UTF16View.Index(range.startIndex, within: utf16view)
        let to = String.UTF16View.Index(range.endIndex, within: utf16view)
        return NSMakeRange(utf16view.startIndex.distanceTo(from), from.distanceTo(to))
    }
}

Update for Swift 3 (Xcode 8):

extension String {
    func nsRange(from range: Range<String.Index>) -> NSRange {
        let from = range.lowerBound.samePosition(in: utf16)
        let to = range.upperBound.samePosition(in: utf16)
        return NSRange(location: utf16.distance(from: utf16.startIndex, to: from),
                       length: utf16.distance(from: from, to: to))
    }
}

extension String {
    func range(from nsRange: NSRange) -> Range<String.Index>? {
        guard
            let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
            let to16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location + nsRange.length, limitedBy: utf16.endIndex),
            let from = from16.samePosition(in: self),
            let to = to16.samePosition(in: self)
            else { return nil }
        return from ..< to
    }
}

Example:

let str = "abc"
let r1 = str.range(of: "")!

// String range to NSRange:
let n1 = str.nsRange(from: r1)
print((str as NSString).substring(with: n1)) // 

// NSRange back to String range:
let r2 = str.range(from: n1)!
print(str.substring(with: r2)) // 

Do not want scientific notation on plot axis

You could try lattice:

require(lattice)
x <- 1:100000
y <- 1:100000
xyplot(y~x, scales=list(x = list(log = 10)), type="l")

enter image description here

Run task only if host does not belong to a group

You can set a control variable in vars files located in group_vars/ or directly in hosts file like this:

[vagrant:vars]
test_var=true

[location-1]
192.168.33.10 hostname=apollo

[location-2]
192.168.33.20 hostname=zeus

[vagrant:children]
location-1
location-2

And run tasks like this:

- name: "test"
  command: "echo {{test_var}}"
  when: test_var is defined and test_var

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

Python 3.9+ only

Merge (|) and update (|=) operators have been added to the built-in dict class.

>>> d = {'spam': 1, 'eggs': 2, 'cheese': 3}
>>> e = {'cheese': 'cheddar', 'aardvark': 'Ethel'}
>>> d | e
{'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}

The augmented assignment version operates in-place:

>>> d |= e
>>> d
{'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}

See PEP 584

The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

I found solution. It works fine when I throw away next line from form:

enctype="multipart/form-data"

And now it pass all parameters at request ok:

 <form action="/registration" method="post">
   <%-- error messages --%>
   <div class="form-group">
    <c:forEach items="${registrationErrors}" var="error">
    <p class="error">${error}</p>
     </c:forEach>
   </div>

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

create table employee
(
   empid int,
   empname varchar(40),
   designation varchar(30),
   hiredate datetime, 
   Bsalary int,
   depno constraint emp_m foreign key references department(depno)
)

We should have an primary key to create foreign key or relationship between two or more table .

Stripping non printable characters from a string in python

Iterating over strings is unfortunately rather slow in Python. Regular expressions are over an order of magnitude faster for this kind of thing. You just have to build the character class yourself. The unicodedata module is quite helpful for this, especially the unicodedata.category() function. See Unicode Character Database for descriptions of the categories.

import unicodedata, re, itertools, sys

all_chars = (chr(i) for i in range(sys.maxunicode))
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)
# or equivalently and much more efficiently
control_chars = ''.join(map(chr, itertools.chain(range(0x00,0x20), range(0x7f,0xa0))))

control_char_re = re.compile('[%s]' % re.escape(control_chars))

def remove_control_chars(s):
    return control_char_re.sub('', s)

For Python2

import unicodedata, re, sys

all_chars = (unichr(i) for i in xrange(sys.maxunicode))
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)
# or equivalently and much more efficiently
control_chars = ''.join(map(unichr, range(0x00,0x20) + range(0x7f,0xa0)))

control_char_re = re.compile('[%s]' % re.escape(control_chars))

def remove_control_chars(s):
    return control_char_re.sub('', s)

For some use-cases, additional categories (e.g. all from the control group might be preferable, although this might slow down the processing time and increase memory usage significantly. Number of characters per category:

  • Cc (control): 65
  • Cf (format): 161
  • Cs (surrogate): 2048
  • Co (private-use): 137468
  • Cn (unassigned): 836601

Edit Adding suggestions from the comments.

How do I pass a value from a child back to the parent form?

Use public property of child form

frmOptions {
     public string Result; }

frmMain {
     frmOptions.ShowDialog(); string r = frmOptions.Result; }

Use events

frmMain {
     frmOptions.OnResult += new ResultEventHandler(frmMain.frmOptions_Resukt);
     frmOptions.ShowDialog(); }

Use public property of main form

frmOptions {
     public frmMain MainForm; MainForm.Result = "result"; }

frmMain {
     public string Result;
     frmOptions.MainForm = this;
     frmOptions.ShowDialog();
     string r = this.Result; }

Use object Control.Tag; This is common for all controls public property which can contains a System.Object. You can hold there string or MyClass or MainForm - anything!

frmOptions {
     this.Tag = "result": }
frmMain {
     frmOptions.ShowDialog();
     string r = frmOptions.Tag as string; }

Passing an Object from an Activity to a Fragment

To pass an object to a fragment, do the following:

First store the objects in Bundle, don't forget to put implements serializable in class.

            CategoryRowFragment fragment = new CategoryRowFragment();

            // pass arguments to fragment
            Bundle bundle = new Bundle();

            // event list we want to populate
            bundle.putSerializable("eventsList", eventsList);

            // the description of the row
            bundle.putSerializable("categoryRow", categoryRow);

            fragment.setArguments(bundle);

Then retrieve bundles in Fragment

_x000D_
_x000D_
       // events that will be populated in this row_x000D_
        mEventsList = (ArrayList<Event>)getArguments().getSerializable("eventsList");_x000D_
_x000D_
        // description of events to be populated in this row_x000D_
        mCategoryRow = (CategoryRow)getArguments().getSerializable("categoryRow");
_x000D_
_x000D_
_x000D_

How to check for a Null value in VB.NET

If Not editTransactionRow.pay_id AndAlso String.IsNullOrEmpty(editTransactionRow.pay_id.ToString()) = False Then
    stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value
End If

How can I select an element by name with jQuery?

You forgot the second set of quotes, which makes the accepted answer incorrect:

$('td[name="tcol1"]') 

Swift addsubview and remove it

I've a view inside my custom CollectionViewCell, and embedding a graph on that view. In order to refresh it, I've to check if there is already a graph placed on that view, remove it and then apply new. Here's the solution

cell.cellView.addSubview(graph)
graph.tag = 10

now, in code block where you want to remove it (in your case gestureRecognizerFunction)

if let removable = cell.cellView.viewWithTag(10){
   removable.removeFromSuperview()
}

to embed it again

cell.cellView.addSubview(graph)
graph.tag = 10

How do I get my C# program to sleep for 50 msec?

Since now you have async/await feature, the best way to sleep for 50ms is by using Task.Delay:

async void foo()
{
    // something
    await Task.Delay(50);
}

Or if you are targeting .NET 4 (with Async CTP 3 for VS2010 or Microsoft.Bcl.Async), you must use:

async void foo()
{
    // something
    await TaskEx.Delay(50);
}

This way you won't block UI thread.

PPT to PNG with transparent background

I could do it like this

  1. Saved Powerpoint as PDF
  2. Opened PDF in Illustrator, removed background there and saved as PNG

print variable and a string in python

Something that (surprisingly) hasn't been mentioned here is simple concatenation.

Example:

foo = "seven"

print("She lives with " + foo + " small men")

Result:

She lives with seven small men

Additionally, as of Python 3, the % method is deprecated. Don't use that.

How to subscribe to an event on a service in Angular2?

Using alpha 28, I accomplished programmatically subscribing to event emitters by way of the eventEmitter.toRx().subscribe(..) method. As it is not intuitive, it may perhaps change in a future release.

How to clear variables in ipython?

Apart from the methods mentioned earlier. You can also use the command del to remove multiple variables

del variable1,variable2

How to display Oracle schema size with SQL query?

SELECT table_name as Table_Name, row_cnt as Row_Count, SUM(mb) as Size_MB
FROM
  (SELECT in_tbl.table_name,   to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from ' ||ut.table_name)),'/ROWSET/ROW/C')) AS row_cnt , mb
FROM
(SELECT CASE WHEN lob_tables IS NULL THEN table_name WHEN lob_tables IS NOT NULL THEN lob_tables END AS table_name , mb
FROM (SELECT ul.table_name AS lob_tables, us.segment_name AS table_name , us.bytes/1024/1024 MB FROM user_segments us
LEFT JOIN user_lobs ul ON us.segment_name = ul.segment_name ) ) in_tbl INNER JOIN user_tables ut ON in_tbl.table_name = ut.table_name ) GROUP BY table_name, row_cnt ORDER BY 3 DESC;``

Above query will give, Table_name, Row_count, Size_in_MB(includes lob column size) of specific user.

What is the best way to prevent session hijacking?

Let us consider that during the login phase the client and server can agree on a secret salt value. Thereafter the server provides a count value with each update and expects the client to respond with the hash of the (secret salt + count). The potential hijacker does not have any way to obtain this secret salt value and thus cannot generate the next hash.

git ignore exception

If you're working with Visual Studio and your .dll happens to be in a bin folder, then you'll need to add an exception for the particular bin folder itself, before you can add the exception for the .dll file. E.g.

!SourceCode/Solution/Project/bin
!SourceCode/Solution/Project/bin/My.dll

This is because the default Visual Studio .gitignore file includes an ignore pattern for [Bbin]/

This pattern is zapping all bin folders (and consequently their contents), which makes any attempt to include the contents redundant (since the folder itself is already ignored).

I was able to find why my file wasn't being excepted by running

git check-ignore -v -- SourceCode/Solution/Project/bin/My.dll

from a Git Bash window. This returned the [Bbin]/ pattern.

How to automatically generate unique id in SQL like UID12345678?

CREATE TABLE dbo.tblUsers
(
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
    UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED, 
    [Name] VARCHAR(50) NOT NULL,
)

marc_s's Answer Snap

marc_s's Answer Snap

Xcode 6.1 - How to uninstall command line tools?

If you installed the command line tools separately, delete them using:

sudo rm -rf /Library/Developer/CommandLineTools

How to increase Neo4j's maximum file open limit (ulimit) in Ubuntu?

I have lots of trouble getting this to work.

Using the following allows you to update it regardless of your user permission.

sudo sysctl -w fs.inotify.max_user_watches=100000

Edit

Just saw this from another user also on another stackexchange site (both work, but this version permanently updates the system setting, rather than temporarily):

echo fs.inotify.max_user_watches=100000 | sudo tee -a /etc/sysctl.conf; 
sudo sysctl -p

ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

This issue could be because adb incompatibility with the newest version of the platform SDK.

Try the following:

  1. If you are using Genymotion, manually set the Android SDK within Genymotion settings to your sdk path. Go to Genymotion -> settings -> ADB -> Use custom SDK Tools -> Browse and ender your local SDK path.

  2. If you haverecently updated your platform-tools plugin version, revert back to 23.0.1.

Its a bug within ADB, one of the above must most likely be your solution.

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

4.6.1-2 in VS2017 users may experience the unwanted replacement of their version of System.Net.Http by the one VS2017 or Msbuild 15 wants to use.

We deleted this version here:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\net461\lib\System.Net.Http.dll

and here:

C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\net461\lib\System.Net.Http.dll

Then the project builds with the version we have referenced via NuGet.

Is there a way to compile node.js source files?

Node.js runs on top of the V8 Javascript engine, which itself optimizes performance by compiling javascript code into native code... so no reason really for compiling then, is there?

https://developers.google.com/v8/design#mach_code

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

In the case where the problem is that System.loadLibrary cannot find the DLL in question, one common misconception (reinforced by Java's error message) is that the system property java.library.path is the answer. If you set the system property java.library.path to the directory where your DLL is located, then System.loadLibrary will indeed find your DLL. However, if your DLL in turn depends on other DLLs, as is often the case, then java.library.path cannot help, because the loading of the dependent DLLs is managed entirely by the operating system, which knows nothing of java.library.path. Thus, it is almost always better to bypass java.library.path and simply add your DLL's directory to LD_LIBRARY_PATH (Linux), DYLD_LIBRARY_PATH (MacOS), or Path (Windows) prior to starting the JVM.

(Note: I am using the term "DLL" in the generic sense of DLL or shared library.)

What does the "at" (@) symbol do in Python?

Decorators were added in Python to make function and method wrapping (a function that receives a function and returns an enhanced one) easier to read and understand. The original use case was to be able to define the methods as class methods or static methods on the head of their definition. Without the decorator syntax, it would require a rather sparse and repetitive definition:

class WithoutDecorators:
def some_static_method():
    print("this is static method")
some_static_method = staticmethod(some_static_method)

def some_class_method(cls):
    print("this is class method")
some_class_method = classmethod(some_class_method)

If the decorator syntax is used for the same purpose, the code is shorter and easier to understand:

class WithDecorators:
    @staticmethod
    def some_static_method():
        print("this is static method")

    @classmethod
    def some_class_method(cls):
        print("this is class method")

General syntax and possible implementations

The decorator is generally a named object ( lambda expressions are not allowed) that accepts a single argument when called (it will be the decorated function) and returns another callable object. "Callable" is used here instead of "function" with premeditation. While decorators are often discussed in the scope of methods and functions, they are not limited to them. In fact, anything that is callable (any object that implements the _call__ method is considered callable), can be used as a decorator and often objects returned by them are not simple functions but more instances of more complex classes implementing their own __call_ method.

The decorator syntax is simply only a syntactic sugar. Consider the following decorator usage:

@some_decorator
def decorated_function():
    pass

This can always be replaced by an explicit decorator call and function reassignment:

def decorated_function():
    pass
decorated_function = some_decorator(decorated_function)

However, the latter is less readable and also very hard to understand if multiple decorators are used on a single function. Decorators can be used in multiple different ways as shown below:

As a function

There are many ways to write custom decorators, but the simplest way is to write a function that returns a subfunction that wraps the original function call.

The generic patterns is as follows:

def mydecorator(function):
    def wrapped(*args, **kwargs):
        # do some stuff before the original
        # function gets called
        result = function(*args, **kwargs)
        # do some stuff after function call and
        # return the result
        return result
    # return wrapper as a decorated function
    return wrapped

As a class

While decorators almost always can be implemented using functions, there are some situations when using user-defined classes is a better option. This is often true when the decorator needs complex parametrization or it depends on a specific state.

The generic pattern for a nonparametrized decorator as a class is as follows:

class DecoratorAsClass:
    def __init__(self, function):
        self.function = function

    def __call__(self, *args, **kwargs):
        # do some stuff before the original
        # function gets called
        result = self.function(*args, **kwargs)
        # do some stuff after function call and
        # return the result
        return result

Parametrizing decorators

In real code, there is often a need to use decorators that can be parametrized. When the function is used as a decorator, then the solution is simple—a second level of wrapping has to be used. Here is a simple example of the decorator that repeats the execution of a decorated function the specified number of times every time it is called:

def repeat(number=3):
"""Cause decorated function to be repeated a number of times.

Last value of original function call is returned as a result
:param number: number of repetitions, 3 if not specified
"""
def actual_decorator(function):
    def wrapper(*args, **kwargs):
        result = None
        for _ in range(number):
            result = function(*args, **kwargs)
        return result
    return wrapper
return actual_decorator

The decorator defined this way can accept parameters:

>>> @repeat(2)
... def foo():
...     print("foo")
...
>>> foo()
foo
foo

Note that even if the parametrized decorator has default values for its arguments, the parentheses after its name is required. The correct way to use the preceding decorator with default arguments is as follows:

>>> @repeat()
... def bar():
...     print("bar")
...
>>> bar()
bar
bar
bar

Finally lets see decorators with Properties.

Properties

The properties provide a built-in descriptor type that knows how to link an attribute to a set of methods. A property takes four optional arguments: fget , fset , fdel , and doc . The last one can be provided to define a docstring that is linked to the attribute as if it were a method. Here is an example of a Rectangle class that can be controlled either by direct access to attributes that store two corner points or by using the width , and height properties:

class Rectangle:
    def __init__(self, x1, y1, x2, y2):
        self.x1, self.y1 = x1, y1
        self.x2, self.y2 = x2, y2

    def _width_get(self):
        return self.x2 - self.x1

    def _width_set(self, value):
        self.x2 = self.x1 + value

    def _height_get(self):
        return self.y2 - self.y1

    def _height_set(self, value):
        self.y2 = self.y1 + value

    width = property(
        _width_get, _width_set,
        doc="rectangle width measured from left"
    )
    height = property(
        _height_get, _height_set,
        doc="rectangle height measured from top"
    )

    def __repr__(self):
        return "{}({}, {}, {}, {})".format(
            self.__class__.__name__,
            self.x1, self.y1, self.x2, self.y2
    )

The best syntax for creating properties is using property as a decorator. This will reduce the number of method signatures inside of the class and make code more readable and maintainable. With decorators the above class becomes:

class Rectangle:
    def __init__(self, x1, y1, x2, y2):
        self.x1, self.y1 = x1, y1
        self.x2, self.y2 = x2, y2

    @property
    def width(self):
        """rectangle height measured from top"""
        return self.x2 - self.x1

    @width.setter
    def width(self, value):
        self.x2 = self.x1 + value

    @property
    def height(self):
        """rectangle height measured from top"""
        return self.y2 - self.y1

    @height.setter
    def height(self, value):
        self.y2 = self.y1 + value

Change size of text in text input tag?

To change the font size of the <input /> tag in HTML, use this:

<input style="font-size:20px" type="text" value="" />

It will create a text input box and the text inside the text box will be 20 pixels.

Different ways of loading a file as an InputStream

All these answers around here, as well as the answers in this question, suggest that loading absolute URLs, like "/foo/bar.properties" treated the same by class.getResourceAsStream(String) and class.getClassLoader().getResourceAsStream(String). This is NOT the case, at least not in my Tomcat configuration/version (currently 7.0.40).

MyClass.class.getResourceAsStream("/foo/bar.properties"); // works!  
MyClass.class.getClassLoader().getResourceAsStream("/foo/bar.properties"); // does NOT work!

Sorry, I have absolutely no satisfying explanation, but I guess that tomcat does dirty tricks and his black magic with the classloaders and cause the difference. I always used class.getResourceAsStream(String) in the past and haven't had any problems.

PS: I also posted this over here

Android studio doesn't list my phone under "Choose Device"

In my case, android studio selectively doesnt recognize my device for projects with COMPILE AND TARGET SDKVERSION 29 under the app level build.gradle.

I fixed this either by downloading 'sources for android 29' which comes up after clicking the 'show package details' under the sdk manager tab or by reducing the compile and targetsdkversions to 28

Difference between Console.Read() and Console.ReadLine()?

Difference between Read(),Readline() and ReadKey() in C#

Read()-Accept the string value and return the string value. Readline() -Accept the string and return Integer ReadKey() -Accept the character and return Character

Summary:

1.The above mentioned three methods are mainly used in Console application and these are used for return the different values . 2.If we use Read line or Read() we need press Enter button to come back to code. 3.If we using Read key() we can press any key to come back code in application

Android Fragment onAttach() deprecated

Activity is a context so if you can simply check the context is an Activity and cast it if necessary.

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    Activity a;

    if (context instanceof Activity){
        a=(Activity) context;
    }

}

Update: Some are claiming that the new Context override is never called. I have done some tests and cannot find a scenario where this is true and according to the source code, it should never be true. In all cases I tested, both pre and post SDK23, both the Activity and the Context versions of onAttach were called. If you can find a scenario where this is not the case, I would suggest you create a sample project illustrating the issue and report it to the Android team.

Update 2: I only ever use the Android Support Library fragments as bugs get fixed faster there. It seems the above issue where the overrides do not get called correctly only comes to light if you use the framework fragments.

Setting the classpath in java using Eclipse IDE

Try this:

Project -> Properties -> Java Build Path -> Add Class Folder.

If it doesnt work, please be specific in what way your compilation fails, specifically post the error messages Eclipse returns, and i will know what to do about it.

android fragment- How to save states of views in a fragment when another fragment is pushed on top of it

The Best Solution I found is below:

onSavedInstanceState(): always called inside fragment when activity is going to shut down(Move activity from one to another or config changes). So if we are calling multiple fragments on same activity then We have to use the following approach:

Use OnDestroyView() of the fragment and save the whole object inside that method. Then OnActivityCreated(): Check that if object is null or not(Because this method calls every time). Now restore state of an object here.

Its works always!

Inline list initialization in VB.NET

Use this syntax for VB.NET 2005/2008 compatibility:

Dim theVar As New List(Of String)(New String() {"one", "two", "three"})

Although the VB.NET 2010 syntax is prettier.

How to check whether a string contains a substring in JavaScript?

ECMAScript 6 introduced String.prototype.includes:

_x000D_
_x000D_
const string = "foo";_x000D_
const substring = "oo";_x000D_
_x000D_
console.log(string.includes(substring));
_x000D_
_x000D_
_x000D_

includes doesn’t have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:

_x000D_
_x000D_
var string = "foo";_x000D_
var substring = "oo";_x000D_
_x000D_
console.log(string.indexOf(substring) !== -1);
_x000D_
_x000D_
_x000D_

Allowing Java to use an untrusted certificate for SSL/HTTPS connection

Following code from here is a useful solution. No keystores etc. Just call method SSLUtilities.trustAllHttpsCertificates() before initializing the service and port (in SOAP).

import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * This class provide various static methods that relax X509 certificate and
 * hostname verification while using the SSL over the HTTP protocol.
 *  
 * @author Jiramot.info
 */
public final class SSLUtilities {

  /**
   * Hostname verifier for the Sun's deprecated API.
   *
   * @deprecated see {@link #_hostnameVerifier}.
   */
  private static com.sun.net.ssl.HostnameVerifier __hostnameVerifier;
  /**
   * Thrust managers for the Sun's deprecated API.
   *
   * @deprecated see {@link #_trustManagers}.
   */
  private static com.sun.net.ssl.TrustManager[] __trustManagers;
  /**
   * Hostname verifier.
   */
  private static HostnameVerifier _hostnameVerifier;
  /**
   * Thrust managers.
   */
  private static TrustManager[] _trustManagers;

  /**
   * Set the default Hostname Verifier to an instance of a fake class that
   * trust all hostnames. This method uses the old deprecated API from the
   * com.sun.ssl package.
   *  
   * @deprecated see {@link #_trustAllHostnames()}.
   */
  private static void __trustAllHostnames() {
    // Create a trust manager that does not validate certificate chains
    if (__hostnameVerifier == null) {
        __hostnameVerifier = new SSLUtilities._FakeHostnameVerifier();
    } // if
    // Install the all-trusting host name verifier
    com.sun.net.ssl.HttpsURLConnection
            .setDefaultHostnameVerifier(__hostnameVerifier);
  } // __trustAllHttpsCertificates

  /**
   * Set the default X509 Trust Manager to an instance of a fake class that
   * trust all certificates, even the self-signed ones. This method uses the
   * old deprecated API from the com.sun.ssl package.
   *
   * @deprecated see {@link #_trustAllHttpsCertificates()}.
   */
  private static void __trustAllHttpsCertificates() {
    com.sun.net.ssl.SSLContext context;

    // Create a trust manager that does not validate certificate chains
    if (__trustManagers == null) {
        __trustManagers = new com.sun.net.ssl.TrustManager[]{new SSLUtilities._FakeX509TrustManager()};
    } // if
    // Install the all-trusting trust manager
    try {
        context = com.sun.net.ssl.SSLContext.getInstance("SSL");
        context.init(null, __trustManagers, new SecureRandom());
    } catch (GeneralSecurityException gse) {
        throw new IllegalStateException(gse.getMessage());
    } // catch
    com.sun.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context
            .getSocketFactory());
  } // __trustAllHttpsCertificates

  /**
   * Return true if the protocol handler property java. protocol.handler.pkgs
   * is set to the Sun's com.sun.net.ssl. internal.www.protocol deprecated
   * one, false otherwise.
   *
   * @return true if the protocol handler property is set to the Sun's
   * deprecated one, false otherwise.
   */
  private static boolean isDeprecatedSSLProtocol() {
    return ("com.sun.net.ssl.internal.www.protocol".equals(System
            .getProperty("java.protocol.handler.pkgs")));
  } // isDeprecatedSSLProtocol

  /**
   * Set the default Hostname Verifier to an instance of a fake class that
   * trust all hostnames.
   */
  private static void _trustAllHostnames() {
      // Create a trust manager that does not validate certificate chains
      if (_hostnameVerifier == null) {
          _hostnameVerifier = new SSLUtilities.FakeHostnameVerifier();
      } // if
      // Install the all-trusting host name verifier:
      HttpsURLConnection.setDefaultHostnameVerifier(_hostnameVerifier);
  } // _trustAllHttpsCertificates

  /**
   * Set the default X509 Trust Manager to an instance of a fake class that
   * trust all certificates, even the self-signed ones.
   */
  private static void _trustAllHttpsCertificates() {
    SSLContext context;

      // Create a trust manager that does not validate certificate chains
      if (_trustManagers == null) {
          _trustManagers = new TrustManager[]{new SSLUtilities.FakeX509TrustManager()};
      } // if
      // Install the all-trusting trust manager:
      try {
          context = SSLContext.getInstance("SSL");
          context.init(null, _trustManagers, new SecureRandom());
      } catch (GeneralSecurityException gse) {
          throw new IllegalStateException(gse.getMessage());
      } // catch
      HttpsURLConnection.setDefaultSSLSocketFactory(context
            .getSocketFactory());
  } // _trustAllHttpsCertificates

  /**
   * Set the default Hostname Verifier to an instance of a fake class that
   * trust all hostnames.
   */
  public static void trustAllHostnames() {
      // Is the deprecated protocol setted?
      if (isDeprecatedSSLProtocol()) {
          __trustAllHostnames();
      } else {
          _trustAllHostnames();
      } // else
  } // trustAllHostnames

  /**
   * Set the default X509 Trust Manager to an instance of a fake class that
   * trust all certificates, even the self-signed ones.
   */
  public static void trustAllHttpsCertificates() {
    // Is the deprecated protocol setted?
    if (isDeprecatedSSLProtocol()) {
        __trustAllHttpsCertificates();
    } else {
        _trustAllHttpsCertificates();
    } // else
  } // trustAllHttpsCertificates

  /**
   * This class implements a fake hostname verificator, trusting any host
   * name. This class uses the old deprecated API from the com.sun. ssl
   * package.
   *
   * @author Jiramot.info
   *
   * @deprecated see {@link SSLUtilities.FakeHostnameVerifier}.
   */
  public static class _FakeHostnameVerifier implements
        com.sun.net.ssl.HostnameVerifier {

    /**
     * Always return true, indicating that the host name is an acceptable
     * match with the server's authentication scheme.
     *
     * @param hostname the host name.
     * @param session the SSL session used on the connection to host.
     * @return the true boolean value indicating the host name is trusted.
     */
    public boolean verify(String hostname, String session) {
        return (true);
    } // verify
  } // _FakeHostnameVerifier

  /**
   * This class allow any X509 certificates to be used to authenticate the
   * remote side of a secure socket, including self-signed certificates. This
   * class uses the old deprecated API from the com.sun.ssl package.
   *
   * @author Jiramot.info
   *
   * @deprecated see {@link SSLUtilities.FakeX509TrustManager}.
   */
  public static class _FakeX509TrustManager implements
        com.sun.net.ssl.X509TrustManager {

    /**
     * Empty array of certificate authority certificates.
     */
    private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};

    /**
     * Always return true, trusting for client SSL chain peer certificate
     * chain.
     *
     * @param chain the peer certificate chain.
     * @return the true boolean value indicating the chain is trusted.
     */
    public boolean isClientTrusted(X509Certificate[] chain) {
        return (true);
    } // checkClientTrusted

    /**
     * Always return true, trusting for server SSL chain peer certificate
     * chain.
     *
     * @param chain the peer certificate chain.
     * @return the true boolean value indicating the chain is trusted.
     */
    public boolean isServerTrusted(X509Certificate[] chain) {
        return (true);
    } // checkServerTrusted

    /**
     * Return an empty array of certificate authority certificates which are
     * trusted for authenticating peers.
     *
     * @return a empty array of issuer certificates.
     */
    public X509Certificate[] getAcceptedIssuers() {
        return (_AcceptedIssuers);
    } // getAcceptedIssuers
  } // _FakeX509TrustManager

  /**
   * This class implements a fake hostname verificator, trusting any host
   * name.
   *
   * @author Jiramot.info
   */
  public static class FakeHostnameVerifier implements HostnameVerifier {

    /**
     * Always return true, indicating that the host name is an acceptable
     * match with the server's authentication scheme.
     *
     * @param hostname the host name.
     * @param session the SSL session used on the connection to host.
     * @return the true boolean value indicating the host name is trusted.
     */
    public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
        return (true);
    } // verify
  } // FakeHostnameVerifier

  /**
   * This class allow any X509 certificates to be used to authenticate the
   * remote side of a secure socket, including self-signed certificates.
   *
   * @author Jiramot.info
   */
  public static class FakeX509TrustManager implements X509TrustManager {

    /**
     * Empty array of certificate authority certificates.
     */
    private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};

    /**
     * Always trust for client SSL chain peer certificate chain with any
     * authType authentication types.
     *
     * @param chain the peer certificate chain.
     * @param authType the authentication type based on the client
     * certificate.
     */
    public void checkClientTrusted(X509Certificate[] chain, String authType) {
    } // checkClientTrusted

    /**
     * Always trust for server SSL chain peer certificate chain with any
     * authType exchange algorithm types.
     *
     * @param chain the peer certificate chain.
     * @param authType the key exchange algorithm used.
     */
    public void checkServerTrusted(X509Certificate[] chain, String authType) {
    } // checkServerTrusted

    /**
     * Return an empty array of certificate authority certificates which are
     * trusted for authenticating peers.
     *
     * @return a empty array of issuer certificates.
     */
    public X509Certificate[] getAcceptedIssuers() {
        return (_AcceptedIssuers);
    } // getAcceptedIssuers
  } // FakeX509TrustManager
} // SSLUtilities

How to install PyQt5 on Windows?

I'm new to both Python and PyQt5. I tried to use pip, but I was having problems with it using a Windows machine. If you have a version of Python 3.4 or above, pip is installed and ready to use like so:

python -m pip install pyqt5 

That's of course assuming that the path for Python executable is in your PATH environment variable. Otherwise include the full path to Python executable (you can type where python to the Command Window to find it) like:

C:\users\userName\AppData\Local\Programs\Python\Python34\python.exe -m pip install pyqt5

Embedding Windows Media Player for all browsers

Elizabeth Castro has an interesting article on this problem: Bye Bye Embed. Worth a read on how she attacked this problem, as well as handling QuickTime content.

Reading/parsing Excel (xls) files with Python

I highly recommend xlrd for reading .xls files.

voyager mentioned the use of COM automation. Having done this myself a few years ago, be warned that doing this is a real PITA. The number of caveats is huge and the documentation is lacking and annoying. I ran into many weird bugs and gotchas, some of which took many hours to figure out.

UPDATE: For newer .xlsx files, the recommended library for reading and writing appears to be openpyxl (thanks, Ikar Pohorský).

java.util.zip.ZipException: error in opening zip file

In my case SL4j-api.jar with multiple versions are conflicting in the maven repo. Than I deleted the entire SL4j-api folder in m2 maven repo and updated maven project, build maven project than ran the project in JBOSS server. issue got resolved.

How to give color to each class in scatter plot in R?

Here is an example that I built based on this page.

library(e1071); library(ggplot2)

mysvm      <- svm(Species ~ ., iris)
Predicted  <- predict(mysvm, iris)

mydf = cbind(iris, Predicted)
qplot(Petal.Length, Petal.Width, colour = Species, shape = Predicted, 
   data = iris)

This gives you the output. You can easily spot the misclassified species from this figure.

enter image description here

ERROR: Cannot open source file " "

You need to check your project settings, under C++, check include directories and make sure it points to where GameEngine.h resides, the other issue could be that GameEngine.h is not in your source file folder or in any include directory and resides in a different folder relative to your project folder. For instance you have 2 projects ProjectA and ProjectB, if you are including GameEngine.h in some source/header file in ProjectA then to include it properly, assuming that ProjectB is in the same parent folder do this:

include "../ProjectB/GameEngine.h"

This is if you have a structure like this:

Root\ProjectA

Root\ProjectB <- GameEngine.h actually lives here

Git clone without .git directory

since you only want the files, you don't need to treat it as a git repo.

rsync -rlp --exclude '.git' user@host:path/to/git/repo/ .

and this only works with local path and remote ssh/rsync path, it may not work if the remote server only provides git:// or https:// access.

Angular 2 'component' is not a known element

This convoluted framework is driving me nuts. Given that you defined the custom component in the the template of another component part of the SAME module, then you do not need to use exports in the module (e.g. app.module.ts). You simply need to specify the declaration in the @NgModule directive of the aforementioned module:

// app.module.ts

import { JsonInputComponent } from './json-input/json-input.component';

@NgModule({
  declarations: [
    AppComponent,
    JsonInputComponent
  ],
  ...

You do NOT need to import the JsonInputComponent (in this example) into AppComponent (in this example) to use the JsonInputComponent custom component in AppComponent template. You simply need to prefix the custom component with the module name of which both components have been defined (e.g. app):

<form [formGroup]="reactiveForm">
  <app-json-input formControlName="result"></app-json-input>
</form>

Notice app-json-input not json-input!

Demo here: https://github.com/lovefamilychildrenhappiness/AngularCustomComponentValidation

nginx error connect to php5-fpm.sock failed (13: Permission denied)

Simple but works..

listen.owner = nginx
listen.group = nginx

chown nginx:nginx /var/run/php-fpm/php-fpm.sock

u'\ufeff' in Python string

I ran into this on Python 3 and found this question (and solution). When opening a file, Python 3 supports the encoding keyword to automatically handle the encoding.

Without it, the BOM is included in the read result:

>>> f = open('file', mode='r')
>>> f.read()
'\ufefftest'

Giving the correct encoding, the BOM is omitted in the result:

>>> f = open('file', mode='r', encoding='utf-8-sig')
>>> f.read()
'test'

Just my 2 cents.

std::string to char*

(This answer applies to C++98 only.)

Please, don't use a raw char*.

std::string str = "string";
std::vector<char> chars(str.c_str(), str.c_str() + str.size() + 1u);
// use &chars[0] as a char*

Javascript to convert UTC to local time

Here is another option that outputs mm/dd/yy:

const date = new Date('2012-11-29 17:00:34 UTC');
date.toLocaleString();
//output 11/29/2012

C# naming convention for constants?

I actually tend to prefer PascalCase here - but out of habit, I'm guilty of UPPER_CASE...

java.lang.IllegalArgumentException: No converter found for return value of type

I faced the same problem but I was using Lombok and my UploadFileResponse pojo was a builder.

public ResponseEntity<UploadFileResponse> 

To solve I added @Getter annotation:

@Builder
@NoArgsConstructor
@AllArgsConstructor
@Getter
public class UploadFileResponse

Write-back vs Write-Through caching?

Write-Back is a more complex one and requires a complicated Cache Coherence Protocol(MOESI) but it is worth it as it makes the system fast and efficient.

The only benefit of Write-Through is that it makes the implementation extremely simple and no complicated cache coherency protocol is required.

Make elasticsearch only return certain fields?

I found the docs for the get api to be helpful - especially the two sections, Source filtering and Fields: https://www.elastic.co/guide/en/elasticsearch/reference/7.3/docs-get.html#get-source-filtering

They state about source filtering:

If you only need one or two fields from the complete _source, you can use the _source_include & _source_exclude parameters to include or filter out that parts you need. This can be especially helpful with large documents where partial retrieval can save on network overhead

Which fitted my use case perfectly. I ended up simply filtering the source like so (using the shorthand):

{
    "_source": ["field_x", ..., "field_y"],
    "query": {      
        ...
    }
}

FYI, they state in the docs about the fields parameter:

The get operation allows specifying a set of stored fields that will be returned by passing the fields parameter.

It seems to cater for fields that have been specifically stored, where it places each field in an array. If the specified fields haven't been stored it will fetch each one from the _source, which could result in 'slower' retrievals. I also had trouble trying to get it to return fields of type object.

So in summary, you have two options, either though source filtering or [stored] fields.

set dropdown value by text using jquery

try this..

$(element).find("option:contains(" + theText+ ")").attr('selected', 'selected');

Python: maximum recursion depth exceeded while calling a Python object

You can increase the capacity of the stack by the following :

import sys
sys.setrecursionlimit(10000)

Determining 32 vs 64 bit in C++

You could do this:

#if __WORDSIZE == 64
char *size = "64bits";
#else
char *size = "32bits";
#endif

Bootstrap Dropdown menu is not working

For Bootstrap 4 you need an additional library. If you read your browser console, Bootstrap will actually print an error message telling you that you need it for drop down to work.

Error: Bootstrap dropdown require Popper.js (https://popper.js.org)

Creating random numbers with no duplicates

Your problem seems to reduce to choose k elements at random from a collection of n elements. The Collections.shuffle answer is thus correct, but as pointed out inefficient: its O(n).

Wikipedia: Fisher–Yates shuffle has a O(k) version when the array already exists. In your case, there is no array of elements and creating the array of elements could be very expensive, say if max were 10000000 instead of 20.

The shuffle algorithm involves initializing an array of size n where every element is equal to its index, picking k random numbers each number in a range with the max one less than the previous range, then swapping elements towards the end of the array.

You can do the same operation in O(k) time with a hashmap although I admit its kind of a pain. Note that this is only worthwhile if k is much less than n. (ie k ~ lg(n) or so), otherwise you should use the shuffle directly.

You will use your hashmap as an efficient representation of the backing array in the shuffle algorithm. Any element of the array that is equal to its index need not appear in the map. This allows you to represent an array of size n in constant time, there is no time spent initializing it.

  1. Pick k random numbers: the first is in the range 0 to n-1, the second 0 to n-2, the third 0 to n-3 and so on, thru n-k.

  2. Treat your random numbers as a set of swaps. The first random index swaps to the final position. The second random index swaps to the second to last position. However, instead of working against a backing array, work against your hashmap. Your hashmap will store every item that is out of position.

int getValue(i) { if (map.contains(i)) return map[i]; return i; } void setValue(i, val) { if (i == val) map.remove(i); else map[i] = val; } int[] chooseK(int n, int k) { for (int i = 0; i < k; i++) { int randomIndex = nextRandom(0, n - i); //(n - i is exclusive) int desiredIndex = n-i-1; int valAtRandom = getValue(randomIndex); int valAtDesired = getValue(desiredIndex); setValue(desiredIndex, valAtRandom); setValue(randomIndex, valAtDesired); } int[] output = new int[k]; for (int i = 0; i < k; i++) { output[i] = (getValue(n-i-1)); } return output; }

How to style SVG <g> element?

The style that you give the "g" element will apply the child elements, not the "g" element itself.

Add a rectangle element and position around the group you wish to style.

See: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g

EDIT: updated wording and added fiddle in comments.

why I can't get value of label with jquery and javascript?

You need text() or html() for label not val() The function should not be called for label instead it is used to get values of input like text or checkbox etc.

Change

value = $("#telefon").val(); 

To

value = $("#telefon").text(); 

How to make the Facebook Like Box responsive?

As of August 4 2015, the native facebook like box have a responsive code snippet available at Facebook Developers page.

You can generate your responsive Facebook likebox here

https://developers.facebook.com/docs/plugins/page-plugin

This is the best solution ever rather than hacking CSS.

Linux/Unix command to determine if process is running?

On most Linux distributions, you can use pidof(8).

It will print the process ids of all running instances of specified processes, or nothing if there are no instances running.

For instance, on my system (I have four instances of bashand one instance of remmina running):

$ pidof bash remmina
6148 6147 6144 5603 21598

On other Unices, pgrep or a combination of ps and grep will achieve the same thing, as others have rightfully pointed out.

What's the actual use of 'fail' in JUnit test case?

I, for example, use fail() to indicate tests that are not yet finished (it happens); otherwise, they would show as successful.

This is perhaps due to the fact that I am unaware of some sort of incomplete() functionality, which exists in NUnit.

Simplest two-way encryption using PHP

Encrypting using openssl_encrypt() The openssl_encrypt function provides a secured and easy way to encrypt your data.

In the script below, we use the AES128 encryption method, but you may consider other kind of encryption method depending on what you want to encrypt.

<?php
$message_to_encrypt = "Yoroshikune";
$secret_key = "my-secret-key";
$method = "aes128";
$iv_length = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($iv_length);

$encrypted_message = openssl_encrypt($message_to_encrypt, $method, $secret_key, 0, $iv);

echo $encrypted_message;
?>

Here is an explanation of the variables used :

message_to_encrypt : the data you want to encrypt secret_key : it is your ‘password’ for encryption. Be sure not to choose something too easy and be careful not to share your secret key with other people method : the method of encryption. Here we chose AES128. iv_length and iv : prepare the encryption using bytes encrypted_message : the variable including your encrypted message

Decrypting using openssl_decrypt() Now you encrypted your data, you may need to decrypt it in order to re-use the message you first included into a variable. In order to do so, we will use the function openssl_decrypt().

<?php
$message_to_encrypt = "Yoroshikune";
$secret_key = "my-secret-key";
$method = "aes128";
$iv_length = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($iv_lenght);
$encrypted_message = openssl_encrypt($message_to_encrypt, $method, $secret_key, 0, $iv);

$decrypted_message = openssl_decrypt($encrypted_message, $method, $secret_key, 0, $iv);

echo $decrypted_message;
?>

The decrypt method proposed by openssl_decrypt() is close to openssl_encrypt().

The only difference is that instead of adding $message_to_encrypt, you will need to add your already encrypted message as the first argument of openssl_decrypt().

That is all you have to do.

How to persist data in a dockerized postgres database using volumes

I would avoid using a relative path. Remember that docker is a daemon/client relationship.

When you are executing the compose, it's essentially just breaking down into various docker client commands, which are then passed to the daemon. That ./database is then relative to the daemon, not the client.

Now, the docker dev team has some back and forth on this issue, but the bottom line is it can have some unexpected results.

In short, don't use a relative path, use an absolute path.

Sorting a list with stream.sorted() in Java

This might help for people ending up here searching how to sort list alphabetically.

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class SortService {
    public static void main(String[] args) {
        List<TestData> test = new ArrayList<>();
        test.add(prepareTestData("Asmin",1));
        test.add(prepareTestData("saurav",4));
        test.add(prepareTestData("asmin",2));
        test.add(prepareTestData("Saurav",3));

        test.forEach(data-> System.out.println(data));
        /** Output
         *  TestData(name=Asmin, id=1)
         *  TestData(name=saurav, id=4)
         *  TestData(name=asmin, id=2)
         *  TestData(name=Saurav, id=3)
         */

        test.sort(Comparator.comparing(TestData::getName,String::compareToIgnoreCase));
        test.forEach(data-> System.out.println(data));
        /**Sorted Output
         * TestData(name=Asmin, id=1)
         * TestData(name=asmin, id=2)
         * TestData(name=saurav, id=4)
         * TestData(name=Saurav, id=3)
         */
    }
    private static TestData prepareTestData(String name, int id){
        TestData testData= new TestData();
        testData.setId(id);
        testData.setName(name);
        return testData;
    }
}

@Getter
@Setter
@ToString
class TestData{
    private String name;
    private int id;
}

How to get base url in CodeIgniter 2.*

To use base_url() (shorthand), you have to load the URL Helper first

$this->load->helper('url');

Or you can autoload it by changing application/config/autoload.php

Or just use

$this->config->base_url();

Same applies to site_url().

Also I can see you are missing echo (though its not your current problem), use the code below to solve the problem

<link rel="stylesheet" href="<?php echo base_url(); ?>css/default.css" type="text/css" />

How to capture a list of specific type with mockito

There is an open issue in Mockito's GitHub about this exact problem.

I have found a simple workaround that does not force you to use annotations in your tests:

import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;

public final class MockitoCaptorExtensions {

    public static <T> ArgumentCaptor<T> captorFor(final CaptorTypeReference<T> argumentTypeReference) {
        return new CaptorContainer<T>().captor;
    }

    public static <T> ArgumentCaptor<T> captorFor(final Class<T> argumentClass) {
        return ArgumentCaptor.forClass(argumentClass);
    }

    public interface CaptorTypeReference<T> {

        static <T> CaptorTypeReference<T> genericType() {
            return new CaptorTypeReference<T>() {
            };
        }

        default T nullOfGenericType() {
            return null;
        }

    }

    private static final class CaptorContainer<T> {

        @Captor
        private ArgumentCaptor<T> captor;

        private CaptorContainer() {
            MockitoAnnotations.initMocks(this);
        }

    }

}

What happens here is that we create a new class with the @Captor annotation and inject the captor into it. Then we just extract the captor and return it from our static method.

In your test you can use it like so:

ArgumentCaptor<Supplier<Set<List<Object>>>> fancyCaptor = captorFor(genericType());

Or with syntax that resembles Jackson's TypeReference:

ArgumentCaptor<Supplier<Set<List<Object>>>> fancyCaptor = captorFor(
    new CaptorTypeReference<Supplier<Set<List<Object>>>>() {
    }
);

It works, because Mockito doesn't actually need any type information (unlike serializers, for example).

How to return a value from __init__ in Python?

init() return none value solved perfectly

class Solve:
def __init__(self,w,d):
    self.value=w
    self.unit=d
def __str__(self):
    return str("my speed is "+str(self.value)+" "+str(self.unit))
ob=Solve(21,'kmh')
print (ob)

output: my speed is 21 kmh

C#: Waiting for all threads to complete

Off the top of my head, why don't you just Thread.Join(timeout) and remove the time it took to join from the total timeout?

// pseudo-c#:

TimeSpan timeout = timeoutPerThread * threads.Count();

foreach (Thread thread in threads)
{
    DateTime start = DateTime.Now;

    if (!thread.Join(timeout))
        throw new TimeoutException();

    timeout -= (DateTime.Now - start);
}

Edit: code is now less pseudo. don't understand why you would mod an answer -2 when the answer you modded +4 is exactly the same, only less detailed.

Display image as grayscale using matplotlib

Try to use a grayscale colormap?

E.g. something like

imshow(..., cmap=pyplot.cm.binary)

For a list of colormaps, see http://scipy-cookbook.readthedocs.org/items/Matplotlib_Show_colormaps.html

Disabled form fields not submitting data

We can also use the readonly only with below attributes -

readonly onclick='return false;'

This is because if we will only use the readonly then radio buttons will be editable. To avoid this situation we can use readonly with above combination. It will restrict the editing and element's values will also passed during form submission.

How to add text to a WPF Label in code?

In normal winForms, value of Label object is changed by,

myLabel.Text= "Your desired string";

But in WPF Label control, you have to use .content property of Label control for example,

myLabel.Content= "Your desired string";

HTML5: Slider with two inputs possible?

The question was: "Is it possible to make a HTML5 slider with two input values, for example to select a price range? If so, how can it be done?"

Ten years ago the answer was probably 'No'. However, times have changed. In 2020 it is finally possible to create a fully accessible, native, non-jquery HTML5 slider with two thumbs for price ranges. If found this posted after I already created this solution and I thought that it would be nice to share my implementation here.

This implementation has been tested on mobile Chrome and Firefox (Android) and Chrome and Firefox (Linux). I am not sure about other platforms, but it should be quite good. I would love to get your feedback and improve this solution.

This solution allows multiple instances on one page and it consists of just two inputs (each) with descriptive labels for screen readers. You can set the thumb size in the amount of grid labels. Also, you can use touch, keyboard and mouse to interact with the slider. The value is updated during adjustment, due to the 'on input' event listener.

My first approach was to overlay the sliders and clip them. However, that resulted in complex code with a lot of browser dependencies. Then I recreated the solution with two sliders that were 'inline'. This is the solution you will find below.

_x000D_
_x000D_
var thumbsize = 14;

function draw(slider,splitvalue) {

    /* set function vars */
    var min = slider.querySelector('.min');
    var max = slider.querySelector('.max');
    var lower = slider.querySelector('.lower');
    var upper = slider.querySelector('.upper');
    var legend = slider.querySelector('.legend');
    var thumbsize = parseInt(slider.getAttribute('data-thumbsize'));
    var rangewidth = parseInt(slider.getAttribute('data-rangewidth'));
    var rangemin = parseInt(slider.getAttribute('data-rangemin'));
    var rangemax = parseInt(slider.getAttribute('data-rangemax'));

    /* set min and max attributes */
    min.setAttribute('max',splitvalue);
    max.setAttribute('min',splitvalue);

    /* set css */
    min.style.width = parseInt(thumbsize + ((splitvalue - rangemin)/(rangemax - rangemin))*(rangewidth - (2*thumbsize)))+'px';
    max.style.width = parseInt(thumbsize + ((rangemax - splitvalue)/(rangemax - rangemin))*(rangewidth - (2*thumbsize)))+'px';
    min.style.left = '0px';
    max.style.left = parseInt(min.style.width)+'px';
    min.style.top = lower.offsetHeight+'px';
    max.style.top = lower.offsetHeight+'px';
    legend.style.marginTop = min.offsetHeight+'px';
    slider.style.height = (lower.offsetHeight + min.offsetHeight + legend.offsetHeight)+'px';
    
    /* correct for 1 off at the end */
    if(max.value>(rangemax - 1)) max.setAttribute('data-value',rangemax);

    /* write value and labels */
    max.value = max.getAttribute('data-value'); 
    min.value = min.getAttribute('data-value');
    lower.innerHTML = min.getAttribute('data-value');
    upper.innerHTML = max.getAttribute('data-value');

}

function init(slider) {
    /* set function vars */
    var min = slider.querySelector('.min');
    var max = slider.querySelector('.max');
    var rangemin = parseInt(min.getAttribute('min'));
    var rangemax = parseInt(max.getAttribute('max'));
    var avgvalue = (rangemin + rangemax)/2;
    var legendnum = slider.getAttribute('data-legendnum');

    /* set data-values */
    min.setAttribute('data-value',rangemin);
    max.setAttribute('data-value',rangemax);
    
    /* set data vars */
    slider.setAttribute('data-rangemin',rangemin); 
    slider.setAttribute('data-rangemax',rangemax); 
    slider.setAttribute('data-thumbsize',thumbsize); 
    slider.setAttribute('data-rangewidth',slider.offsetWidth);

    /* write labels */
    var lower = document.createElement('span');
    var upper = document.createElement('span');
    lower.classList.add('lower','value');
    upper.classList.add('upper','value');
    lower.appendChild(document.createTextNode(rangemin));
    upper.appendChild(document.createTextNode(rangemax));
    slider.insertBefore(lower,min.previousElementSibling);
    slider.insertBefore(upper,min.previousElementSibling);
    
    /* write legend */
    var legend = document.createElement('div');
    legend.classList.add('legend');
    var legendvalues = [];
    for (var i = 0; i < legendnum; i++) {
        legendvalues[i] = document.createElement('div');
        var val = Math.round(rangemin+(i/(legendnum-1))*(rangemax - rangemin));
        legendvalues[i].appendChild(document.createTextNode(val));
        legend.appendChild(legendvalues[i]);

    } 
    slider.appendChild(legend);

    /* draw */
    draw(slider,avgvalue);

    /* events */
    min.addEventListener("input", function() {update(min);});
    max.addEventListener("input", function() {update(max);});
}

function update(el){
    /* set function vars */
    var slider = el.parentElement;
    var min = slider.querySelector('#min');
    var max = slider.querySelector('#max');
    var minvalue = Math.floor(min.value);
    var maxvalue = Math.floor(max.value);
    
    /* set inactive values before draw */
    min.setAttribute('data-value',minvalue);
    max.setAttribute('data-value',maxvalue);

    var avgvalue = (minvalue + maxvalue)/2;

    /* draw */
    draw(slider,avgvalue);
}

var sliders = document.querySelectorAll('.min-max-slider');
sliders.forEach( function(slider) {
    init(slider);
});
_x000D_
* {padding: 0; margin: 0;}
body {padding: 40px;}

.min-max-slider {position: relative; width: 200px; text-align: center; margin-bottom: 50px;}
.min-max-slider > label {display: none;}
span.value {height: 1.7em; font-weight: bold; display: inline-block;}
span.value.lower::before {content: "€"; display: inline-block;}
span.value.upper::before {content: "- €"; display: inline-block; margin-left: 0.4em;}
.min-max-slider > .legend {display: flex; justify-content: space-between;}
.min-max-slider > .legend > * {font-size: small; opacity: 0.25;}
.min-max-slider > input {cursor: pointer; position: absolute;}

/* webkit specific styling */
.min-max-slider > input {
  -webkit-appearance: none;
  outline: none!important;
  background: transparent;
  background-image: linear-gradient(to bottom, transparent 0%, transparent 30%, silver 30%, silver 60%, transparent 60%, transparent 100%);
}
.min-max-slider > input::-webkit-slider-thumb {
  -webkit-appearance: none; /* Override default look */
  appearance: none;
  width: 14px; /* Set a specific slider handle width */
  height: 14px; /* Slider handle height */
  background: #eee; /* Green background */
  cursor: pointer; /* Cursor on hover */
  border: 1px solid gray;
  border-radius: 100%;
}
.min-max-slider > input::-webkit-slider-runnable-track {cursor: pointer;}
_x000D_
<div class="min-max-slider" data-legendnum="2">
    <label for="min">Minimum price</label>
    <input id="min" class="min" name="min" type="range" step="1" min="0" max="3000" />
    <label for="max">Maximum price</label>
    <input id="max" class="max" name="max" type="range" step="1" min="0" max="3000" />
</div>
_x000D_
_x000D_
_x000D_

Note that you should keep the step size to 1 to prevent the values to change due to redraws/redraw bugs.

View online at: https://codepen.io/joosts/pen/rNLdxvK

Cast Object to Generic Type for returning

I stumble upon this question and it grabbed my interest. The accepted answer is completely correct, but I thought I do provide my findings at JVM byte code level to explain why the OP encounter the ClassCastException.

I have the code which is pretty much the same as OP's code:

public static <T> T convertInstanceOfObject(Object o) {
    try {
       return (T) o;
    } catch (ClassCastException e) {
        return null;
    }
}

public static void main(String[] args) {
    String k = convertInstanceOfObject(345435.34);
    System.out.println(k);
}

and the corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object);
    Code:
       0: aload_0
       1: areturn
       2: astore_1
       3: aconst_null
       4: areturn
    Exception table:
       from    to  target type
           0     1     2   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #3                  // double 345435.34d
       3: invokestatic  #5                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: invokestatic  #6                  // Method convertInstanceOfObject:(Ljava/lang/Object;)Ljava/lang/Object;
       9: checkcast     #7                  // class java/lang/String
      12: astore_1
      13: getstatic     #8                  // Field java/lang/System.out:Ljava/io/PrintStream;
      16: aload_1
      17: invokevirtual #9                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      20: return

Notice that checkcast byte code instruction happens in the main method not the convertInstanceOfObject and convertInstanceOfObject method does not have any instruction that can throw ClassCastException. Because the main method does not catch the ClassCastException hence when you execute the main method you will get a ClassCastException and not the expectation of printing null.

Now I modify the code to the accepted answer:

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
        try {
            return clazz.cast(o);
        } catch (ClassCastException e) {
            return null;
        }
    }
    public static void main(String[] args) {
        String k = convertInstanceOfObject(345435.34, String.class);
        System.out.println(k);
    }

The corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object, java.lang.Class<T>);
    Code:
       0: aload_1
       1: aload_0
       2: invokevirtual #2                  // Method java/lang/Class.cast:(Ljava/lang/Object;)Ljava/lang/Object;
       5: areturn
       6: astore_2
       7: aconst_null
       8: areturn
    Exception table:
       from    to  target type
           0     5     6   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #4                  // double 345435.34d
       3: invokestatic  #6                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: ldc           #7                  // class java/lang/String
       8: invokestatic  #8                  // Method convertInstanceOfObject:(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;
      11: checkcast     #7                  // class java/lang/String
      14: astore_1
      15: getstatic     #9                  // Field java/lang/System.out:Ljava/io/PrintStream;
      18: aload_1
      19: invokevirtual #10                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      22: return

Notice that there is an invokevirtual instruction in the convertInstanceOfObject method that calls Class.cast() method which throws ClassCastException which will be catch by the catch(ClassCastException e) bock and return null; hence, "null" is printed to console without any exception.

Delete empty lines using sed

You can say:

sed -n '/ / p' filename    #there is a space between '//'

LF will be replaced by CRLF in git - What is that and is it important?

If you want, you can deactivate this feature in your git core config using

git config core.autocrlf false

But it would be better to just get rid of the warnings using

git config core.autocrlf true

Export MySQL data to Excel in PHP

PHPExcel is your friend. Very easy to use and works like a charm.

https://github.com/PHPOffice/PHPExcel

How do I run a class in a WAR from the command line?

In Maven project, You can build jar automatically using Maven War plugin by setting archiveClasses to true. Example below.

<plugin>
       <groupId>org.apache.maven.plugins</groupId>
       <artifactId>maven-war-plugin</artifactId>
       <configuration>
        <archiveClasses>true</archiveClasses>
       </configuration>
</plugin>

Only get hash value using md5sum (without filename)

One way:

set -- $(md5sum $file)
md5=$1

Another way:

md5=$(md5sum $file | while read sum file; do echo $sum; done)

Another way:

md5=$(set -- $(md5sum $file); echo $1)

(Do not try that with back-ticks unless you're very brave and very good with backslashes.)

The advantage of these solutions over other solutions is that they only invoke md5sum and the shell, rather than other programs such as awk or sed. Whether that actually matters is then a separate question; you'd probably be hard pressed to notice the difference.

How do I write good/correct package __init__.py files

__all__ is very good - it helps guide import statements without automatically importing modules http://docs.python.org/tutorial/modules.html#importing-from-a-package

using __all__ and import * is redundant, only __all__ is needed

I think one of the most powerful reasons to use import * in an __init__.py to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave __init__.py files empty.

for example:

foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo

then the app grows and now it's a whole folder

foo/
    __init__.py
    foofactories.py
    tallFoos.py
    shortfoos.py
    mediumfoos.py
    santaslittlehelperfoo.py
    superawsomefoo.py
    anotherfoo.py

then the init script can say

__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
           'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo

so that a script written to do the following does not break during the change:

from foo import fooFactory, tallFoo, shortFoo

The condition has length > 1 and only the first element will be used

You get the error because if can only evaluate a logical vector of length 1.

Maybe you miss the difference between & (|) and && (||). The shorter version works element-wise and the longer version uses only the first element of each vector, e.g.:

c(TRUE, TRUE) & c(TRUE, FALSE)
# [1] TRUE FALSE

# c(TRUE, TRUE) && c(TRUE, FALSE)
[1] TRUE

You don't need the if statement at all:

mut1 <- trip$Ref.y=='G' & trip$Variant.y=='T'|trip$Ref.y=='C' & trip$Variant.y=='A'
trip[mut1, "mutType"] <- "G:C to T:A"

How to take complete backup of mysql database using mysqldump command line utility

On MySQL 5.7 its work for me, I'm using CentOS7.

For taking Dump.

Command :

mysqldump -u user_name -p database_name -R -E > file_name.sql

Exemple :

mysqldump -u root -p mr_sbc_clean -R -E > mr_sbc_clean_dump.sql

For deploying Dump.

Command :

mysql -u user_name -p database_name < file_name.sql

Exemple :

mysql -u root -p mr_sbc_clean_new < mr_sbc_clean_dump.sql

Comparing two hashmaps for equal values and same key sets?

/* JAVA 8 using streams*/
   public static void main(String args[])
    {
        Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();
        map.put(100, true);
        map.put(1011, false);
        map.put(1022, false);

        Map<Integer, Boolean> map1 = new HashMap<Integer, Boolean>();
        map1.put(100, false);
        map1.put(101, false);
        map1.put(102, false);

        boolean b = map.entrySet().stream().filter(value -> map1.entrySet().stream().anyMatch(value1 -> (value1.getKey() == value.getKey() && value1.getValue() == value.getValue()))).findAny().isPresent();
        System.out.println(b);
    }

Making a list of evenly spaced numbers in a certain range in python

You can use the folowing code:

def float_range(initVal, itemCount, step):
    for x in xrange(itemCount):
        yield initVal
        initVal += step

[x for x in float_range(1, 3, 0.1)]

Setting java locale settings

I believe java gleans this from the environment variables in which it was launched, so you'll need to make sure your LANG and LC_* environment variables are set appropriately.

The locale manpage has full info on said environment variables.

How to concat a string to xsl:value-of select="...?

You can use the rather sensibly named xpath function called concat here

<a>
   <xsl:attribute name="href">
      <xsl:value-of select="concat('myText:', /*/properties/property[@name='report']/@value)" />
   </xsl:attribute>
</a>  

Of course, it doesn't have to be text here, it can be another xpath expression to select an element or attribute. And you can have any number of arguments in the concat expression.

Do note, you can make use of Attribute Value Templates (represented by the curly braces) here to simplify your expression

<a href="{concat('myText:', /*/properties/property[@name='report']/@value)}"></a>

Some dates recognized as dates, some dates not recognized. Why?

Here is what worked for me. I highlighted the column with all my dates. Under the Data tab, I selected 'text to columns' and selected the 'Delimited' box, I hit next and finish. Although it didn't seem like anything changed, Excel now read the column as dates and I was able to sort by dates.

Code line wrapping - how to handle long lines

In general, I break lines before operators, and indent the subsequent lines:

Map<long parameterization> longMap
    = new HashMap<ditto>();

String longString = "some long text"
                  + " some more long text";

To me, the leading operator clearly conveys that "this line was continued from something else, it doesn't stand on its own." Other people, of course, have different preferences.

SCRIPT5: Access is denied in IE9 on xmlhttprequest

On IE7, IE8, and IE9 just go to Settings->Internet Options->Security->Custom Level and change security settings under "Miscellaneous" set "Access data sources across domains" to Enable.

What is the difference between Views and Materialized Views in Oracle?

Materialized views are disk based and are updated periodically based upon the query definition.

Views are virtual only and run the query definition each time they are accessed.

Setting std=c99 flag in GCC

How about alias gcc99= gcc -std=c99?

Swap x and y axis without manually swapping values

-Right click on either axis

-Click "Select Data..."

-Then Press the "Edit" button

-Copy the "Series X values" to the "Series Y values" and vise versa finally hit ok

I found this answer on this youtube video https://www.youtube.com/watch?v=xLKIWWIWltE

How to get response from S3 getObject in Node.js?

Based on the answer by @peteb, but using Promises and Async/Await:

const AWS = require('aws-sdk');

const s3 = new AWS.S3();

async function getObject (bucket, objectKey) {
  try {
    const params = {
      Bucket: bucket,
      Key: objectKey 
    }

    const data = await s3.getObject(params).promise();

    return data.Body.toString('utf-8');
  } catch (e) {
    throw new Error(`Could not retrieve file from S3: ${e.message}`)
  }
}

// To retrieve you need to use `await getObject()` or `getObject().then()`
getObject('my-bucket', 'path/to/the/object.txt').then(...);

How to See the Contents of Windows library (*.lib)

DUMPBIN /EXPORTS Will get most of that information and hitting MSDN will get the rest.

Get one of the Visual Studio packages; C++

How to remove any URL within a string in Python

This worked for me:

import re
thestring = "text1\ntext2\nhttp://url.com/bla1/blah1/\ntext3\ntext4\nhttp://url.com/bla2/blah2/\ntext5\ntext6"

URLless_string = re.sub(r'\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*(?:(?:\/[^\s/]*))*', '', thestring)
print URLless_string

Result:

text1
text2

text3
text4

text5
text6

Procedure expects parameter which was not supplied

I came across this error today when null values were passed to my stored procedure's parameters. I was able easily fix by altering the stored procedure by adding default value = null.

JSON datetime between Python and JavaScript

If you're certain that only Javascript will be consuming the JSON, I prefer to pass Javascript Date objects directly.

The ctime() method on datetime objects will return a string that the Javascript Date object can understand.

import datetime
date = datetime.datetime.today()
json = '{"mydate":new Date("%s")}' % date.ctime()

Javascript will happily use that as an object literal, and you've got your Date object built right in.

error code 1292 incorrect date value mysql

I happened to be working in localhost , in windows 10, using WAMP, as it turns out, Wamp has a really accessible configuration interface to change the MySQL configuration. You just need to go to the Wamp panel, then to MySQL, then to settings and change the mode to sql-mode: none.(essentially disabling the strict mode) The following picture illustrates this.

enter image description here

Hide div after a few seconds

$.fn.delay = function(time, callback){
    // Empty function:
    jQuery.fx.step.delay = function(){};
    // Return meaningless animation, (will be added to queue)
    return this.animate({delay:1}, time, callback);
}

From http://james.padolsey.com/javascript/jquery-delay-plugin/

(Allows chaining of methods)

Editing legend (text) labels in ggplot

The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2 package.

An example with your data:

# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")

# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) + 
  geom_point(size=5) +
  labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
        axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
        plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))

this results in:

enter image description here

As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888")) instead of scale_color_manual().

Throughput and bandwidth difference?

In most cases with "bandwidth" and "throughput" it is OVER complicated; like trying to learn calculus in one day. There is NO need for this, in MOST cases when referencing "Bandwidth" and "Throughput".

All you need to know in MOST cases is this:

"MB" means mega "BYTES"; OR 8 bits and 8 bits and 8 bits, etc; is being sent down the line. Mb means mega "bits". OR a single bit and bit and bit, etc; down the line.

Example: IF your carrier says this is a "6 Mb line"; it means that is the maximum Bandwidth. More succinctly it means that you ONLY are going to benefit 750 kilobytes per/sec "throughput". Now why? Because the line is only sending a series of "bits", which uses 8 bits/sec to create a byte. Thus; you must divide bits/sec by 8 to get to bytes/sec. Thus: a 6Mb line can ONLY deliver 750 thousand bytes/sec.

Another example: I just got a fiber optic line from A T & T; and they LOVE to talk about "bits". So they advertise a whopping "100 mega bits per second". Big deal. Because that is only 12.5 "MBytes/per second.

Remember, EACH "character" on your keyboard or printed on the screen, etc, requires 8 bits; for the other end to "distinguish" what character it is, etc.

So even though I have a "Gargantuan" fiber line touted as "100Mb"; it is really only 12.5 MBytes (characters) per second (100 divided by 8).

Worse: MOST interchange the terms "MB" and "Mb". Worse yet; EVEN The technician that installed the Fiber Optic line and router in my home, did not know what the terms meant. So he thought, and his co-workers (according to him) believed the same. IE: That 100Mb line was a 100MB line. This is very sad.

A T & T reps on the phone rarely know the difference either. Even some of their supervisors do not know it either. Even sadder.

To summarize: "Bandwidth" uses "bits". "Throughput" uses "bytes". And...one byte takes up 8 bits. So again: a 100Mb line (bandwidth) can ONLY produce 12.5 MBytes/sec (throughput).

For whatever it's worth.

"Javac" doesn't work correctly on Windows 10

The PATH is for current user, instead you can add a CLASSPATH and below link would help you more PATH and CLASSPATH

Error "There is already an open DataReader associated with this Command which must be closed first" when using 2 distinct commands

Try to combine the query, it will run much faster than executing an additional query per row. Ik don't like the string[] you're using, i would create a class for holding the information.

    public List<string[]> get_dados_historico_verificacao_email_WEB(string email)
    {
        List<string[]> historicos = new List<string[]>();

        using (SqlConnection conexao = new SqlConnection("ConnectionString"))
        {
            string sql =
                @"SELECT    *, 
                            (   SELECT      COUNT(e.cd_historico_verificacao_email) 
                                FROM        emails_lidos e 
                                WHERE       e.cd_historico_verificacao_email = a.nm_email ) QT
                  FROM      historico_verificacao_email a
                  WHERE     nm_email = @email
                  ORDER BY  dt_verificacao_email DESC, 
                            hr_verificacao_email DESC";

            using (SqlCommand com = new SqlCommand(sql, conexao))
            {
                com.Parameters.Add("email", SqlDbType.VarChar).Value = email;

                SqlDataReader dr = com.ExecuteReader();

                while (dr.Read())
                {
                    string[] dados_historico = new string[6];
                    dados_historico[0] = dr["nm_email"].ToString();
                    dados_historico[1] = dr["dt_verificacao_email"].ToString();
                    dados_historico[1] = dados_historico[1].Substring(0, 10);
                    //System.Windows.Forms.MessageBox.Show(dados_historico[1]);
                    dados_historico[2] = dr["hr_verificacao_email"].ToString();
                    dados_historico[3] = dr["ds_tipo_verificacao"].ToString();
                    dados_historico[4] = dr["QT"].ToString();
                    dados_historico[5] = dr["cd_login_usuario"].ToString();

                    historicos.Add(dados_historico);
                }
            }
        }
        return historicos;
    }

Untested, but maybee gives some idea.

Script to get the HTTP status code of a list of urls?

Extending the answer already provided by Phil. Adding parallelism to it is a no brainer in bash if you use xargs for the call.

Here the code:

xargs -n1 -P 10 curl -o /dev/null --silent --head --write-out '%{url_effective}: %{http_code}\n' < url.lst

-n1: use just one value (from the list) as argument to the curl call

-P10: Keep 10 curl processes alive at any time (i.e. 10 parallel connections)

Check the write_out parameter in the manual of curl for more data you can extract using it (times, etc).

In case it helps someone this is the call I'm currently using:

xargs -n1 -P 10 curl -o /dev/null --silent --head --write-out '%{url_effective};%{http_code};%{time_total};%{time_namelookup};%{time_connect};%{size_download};%{speed_download}\n' < url.lst | tee results.csv

It just outputs a bunch of data into a csv file that can be imported into any office tool.

How can I explicitly free memory in Python?

As other answers already say, Python can keep from releasing memory to the OS even if it's no longer in use by Python code (so gc.collect() doesn't free anything) especially in a long-running program. Anyway if you're on Linux you can try to release memory by invoking directly the libc function malloc_trim (man page). Something like:

import ctypes
libc = ctypes.CDLL("libc.so.6")
libc.malloc_trim(0)

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One-to-many

The one-to-many table relationship looks as follows:

One-to-many

In a relational database system, a one-to-many table relationship links two tables based on a Foreign Key column in the child which references the Primary Key of the parent table row.

In the table diagram above, the post_id column in the post_comment table has a Foreign Key relationship with the post table id Primary Key column:

ALTER TABLE
    post_comment
ADD CONSTRAINT
    fk_post_comment_post_id
FOREIGN KEY (post_id) REFERENCES post

One-to-one

The one-to-one table relationship looks as follows:

One-to-one

In a relational database system, a one-to-one table relationship links two tables based on a Primary Key column in the child which is also a Foreign Key referencing the Primary Key of the parent table row.

Therefore, we can say that the child table shares the Primary Key with the parent table.

In the table diagram above, the id column in the post_details table has also a Foreign Key relationship with the post table id Primary Key column:

ALTER TABLE
    post_details
ADD CONSTRAINT
    fk_post_details_id
FOREIGN KEY (id) REFERENCES post

Many-to-many

The many-to-many table relationship looks as follows:

Many-to-many

In a relational database system, a many-to-many table relationship links two parent tables via a child table which contains two Foreign Key columns referencing the Primary Key columns of the two parent tables.

In the table diagram above, the post_id column in the post_tag table has also a Foreign Key relationship with the post table id Primary Key column:

ALTER TABLE
    post_tag
ADD CONSTRAINT
    fk_post_tag_post_id
FOREIGN KEY (post_id) REFERENCES post

And, the tag_id column in the post_tag table has a Foreign Key relationship with the tag table id Primary Key column:

ALTER TABLE
    post_tag
ADD CONSTRAINT
    fk_post_tag_tag_id
FOREIGN KEY (tag_id) REFERENCES tag

Post a json object to mvc controller with jquery and ajax

instead of receiving the json string a model binding is better. For example:

[HttpPost]       
public ActionResult AddUser(UserAddModel model)
{
    if (ModelState.IsValid) {
        return Json(new { Response = "Success" });
    }
    return Json(new { Response = "Error" });
}

<script>
function submitForm() {    
    $.ajax({
        type: 'POST',
        url: "@Url.Action("AddUser")",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: $("form[name=UserAddForm]").serialize(),
        success: function (data) {
            console.log(data);
        }
    });
}
</script>

Check that an email address is valid on iOS

Good cocoa function:

-(BOOL) NSStringIsValidEmail:(NSString *)checkString
{
   BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
   NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
   NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
   NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
   NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
   return [emailTest evaluateWithObject:checkString];
}

Discussion on Lax vs. Strict - http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/

And because categories are just better, you could also add an interface:

@interface NSString (emailValidation) 
  - (BOOL)isValidEmail;
@end

Implement

@implementation NSString (emailValidation)
-(BOOL)isValidEmail
{
  BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
  NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
  NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
  NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
  NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
  return [emailTest evaluateWithObject:self];
}
@end

And then utilize:

if([@"[email protected]" isValidEmail]) { /* True */ }
if([@"InvalidEmail@notreallyemailbecausenosuffix" isValidEmail]) { /* False */ }

How do I put text on ProgressBar?

Just want to point out something on @codingbadger answer. When using "ProgressBarRenderer" you should always check for "ProgressBarRenderer.IsSupported" before using the class. For me, this has been a nightmare with Visual Styles errors in Win7 that I couldn't fix. So, a better approach and workaround for the solution would be:

Rectangle clip = new Rectangle(rect.X, rect.Y, (int)Math.Round(((float)Value / Maximum) * rect.Width), rect.Height);
if (ProgressBarRenderer.IsSupported)
  ProgressBarRenderer.DrawHorizontalChunks(g, clip);
else
  g.FillRectangle(new SolidBrush(this.ForeColor), clip);

Notice that the fill will be a simple rectangle and not chunks. Chunks will be used only if ProgressBarRenderer is supported

Export table from database to csv file

And when you want all tables for some reason ?

You can generate these commands in SSMS:

SELECT 
CONCAT('sqlcmd -S ',
'Your(local?)SERVERhere'
,' -d',
'YourDB'
,' -E -s, -W -Q "SELECT * FROM ',
TABLE_NAME,
'" >',
TABLE_NAME,
'.csv') FROM INFORMATION_SCHEMA.TABLES

And get again rows like this

sqlcmd -S ... -d... -E -s, -W -Q "SELECT * FROM table1" >table1.csv
sqlcmd -S ... -d... -E -s, -W -Q "SELECT * FROM table2" >table2.csv
...

There is also option to use better TAB as delimiter, but it would need a strange Unicode character - using Alt+9 in CMD, it came like this ? (Unicode CB25), but works only by copy/paste to command line not in batch.

What Ruby IDE do you prefer?

In last 3 months, I have tried RadRails, Netbeans and RubyMine and finally settled on RubyMine not so much for features but for responsiveness and stability reasons.

In terms of features, RubyMine has slightly better code completion, debugging and code navigation, but only ruby beginners(like myself) need them most. Relying on code completion and code navigation is anti-ruby/rails, as ruby/rails names are supposed to be natural and each line of code needs to be in its convention determined location.

Extract filename and extension in Bash

Usually you already know the extension, so you might wish to use:

basename filename .extension

for example:

basename /path/to/dir/filename.txt .txt

and we get

filename

How to make code wait while calling asynchronous calls like Ajax

Real programmers do it with semaphores.

Have a variable set to 0. Increment it before each AJAX call. Decrement it in each success handler, and test for 0. If it is, you're done.