Programs & Examples On #Httpconnection

ConnectionTimeout versus SocketTimeout

A connection timeout is the maximum amount of time that the program is willing to wait to setup a connection to another process. You aren't getting or posting any application data at this point, just establishing the connection, itself.

A socket timeout is the timeout when waiting for individual packets. It's a common misconception that a socket timeout is the timeout to receive the full response. So if you have a socket timeout of 1 second, and a response comprised of 3 IP packets, where each response packet takes 0.9 seconds to arrive, for a total response time of 2.7 seconds, then there will be no timeout.

Sending POST data in Android

for Android = > 5

The org.apache.http classes and the AndroidHttpClient class have been deprecated in Android 5.1. These classes are no longer being maintained and you should migrate any app code using these APIs to the URLConnection classes as soon as possible.

https://developer.android.com/about/versions/android-5.1.html#http

Thought of sharing my code using HttpUrlConnection

public String  performPostCall(String requestURL,
        HashMap<String, String> postDataParams) {

    URL url;
    String response = "";
    try {
        url = new URL(requestURL);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.setDoOutput(true);


        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(getPostDataString(postDataParams));

        writer.flush();
        writer.close();
        os.close();
        int responseCode=conn.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String line;
            BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line=br.readLine()) != null) {
                response+=line;
            }
        }
        else {
            response="";    

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

    return response;
}

...

private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }

also you can Post method :

conn.setRequestMethod("POST");

Update 21/02/2016

for post request with json , see this example :

public class Empty extends
        AsyncTask<Void, Void, Boolean> {

    String urlString = "http://www.yoursite.com/";

    private final String TAG = "post json example";
    private Context context;

    private int advertisementId;

    public Empty(Context contex, int advertisementId) {

        this.context = contex;
        this.advertisementId = advertisementId;
    }

    @Override
    protected void onPreExecute() {
        Log.e(TAG, "1 - RequestVoteTask is about to start...");

    }

    @Override
    protected Boolean doInBackground(Void... params) {
        boolean status = false;

        String response = "";
        Log.e(TAG, "2 - pre Request to response...");

        try {
            response = performPostCall(urlString, new HashMap<String, String>() {

                        private static final long serialVersionUID = 1L;

                        {
                            put("Accept", "application/json");
                            put("Content-Type", "application/json");
                        }
                    });
            Log.e(TAG, "3 - give Response...");
            Log.e(TAG, "4 " + response.toString());
        } catch (Exception e) {
            // displayLoding(false);

            Log.e(TAG, "Error ...");
        }
        Log.e(TAG, "5 - after Response...");

        if (!response.equalsIgnoreCase("")) {
            try {
                Log.e(TAG, "6 - response !empty...");
                //
                JSONObject jRoot = new JSONObject(response);
                JSONObject d = jRoot.getJSONObject("d");

                int ResultType = d.getInt("ResultType");
                Log.e("ResultType", ResultType + "");

                if (ResultType == 1) {

                    status = true;

                }

            } catch (JSONException e) {
                // displayLoding(false);
                // e.printStackTrace();
                Log.e(TAG, "Error " + e.getMessage());
            } finally {

            }
        } else {
            Log.e(TAG, "6 - response is empty...");

            status = false;
        }

        return status;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        //
        Log.e(TAG, "7 - onPostExecute ...");

        if (result) {
            Log.e(TAG, "8 - Update UI ...");

            // setUpdateUI(adv);
        } else {
            Log.e(TAG, "8 - Finish ...");

            // displayLoding(false);
            // finish();
        }

    }

    public String performPostCall(String requestURL,
                                  HashMap<String, String> postDataParams) {

        URL url;
        String response = "";
        try {
            url = new URL(requestURL);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(context.getResources().getInteger(
                    R.integer.maximum_timeout_to_server));
            conn.setConnectTimeout(context.getResources().getInteger(
                    R.integer.maximum_timeout_to_server));
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            conn.setRequestProperty("Content-Type", "application/json");

            Log.e(TAG, "11 - url : " + requestURL);

            /*
             * JSON
             */

            JSONObject root = new JSONObject();
            //
            String token = Static.getPrefsToken(context);

            root.put("securityInfo", Static.getSecurityInfo(context));
            root.put("advertisementId", advertisementId);

            Log.e(TAG, "12 - root : " + root.toString());

            String str = root.toString();
            byte[] outputBytes = str.getBytes("UTF-8");
            OutputStream os = conn.getOutputStream();
            os.write(outputBytes);

            int responseCode = conn.getResponseCode();

            Log.e(TAG, "13 - responseCode : " + responseCode);

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                Log.e(TAG, "14 - HTTP_OK");

                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response += line;
                }
            } else {
                Log.e(TAG, "14 - False - HTTP_OK");
                response = "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }
}

UPDATE 24/08/2016

Use some best library , such as :

because :

  • Avoid HttpUrlConnection and HttpClient

On lower API levels (mostly on Gingerbread and Froyo), HttpUrlConnection and HttpClient are far from being perfect

  • And Avoid AsyncTask Too
  • They are Much Faster
  • They Caches Everything

Since the introduction of Honeycomb (API 11), it's been mandatory to perform network operations on a separate thread, different from the main thread

How do you connect localhost in the Android emulator?

Use 10.0.2.2 to access your actual machine.

As you've learned, when you use the emulator, localhost (127.0.0.1) refers to the device's own loopback service, not the one on your machine as you may expect.

You can use 10.0.2.2 to access your actual machine, it is an alias set up to help in development.

Java: how to use UrlConnection to post request with authorization?

On API 22 The Use Of BasicNamevalue Pair is depricated, instead use the HASMAP for that. To know more about the HasMap visit here more on hasmap developer.android

package com.yubraj.sample.datamanager;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.yubaraj.sample.utilities.GeneralUtilities;


import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

/**
 * Created by yubraj on 7/30/15.
 */
public class ServerRequestHandler {
    private static final String TAG = "Server Request";
    OnServerRequestComplete listener;

    public ServerRequestHandler (){

    }
    public void doServerRequest(HashMap<String, String> parameters, String url, int requestType, OnServerRequestComplete listener){

        debug("ServerRequest", "server request called, url  = " + url);
        if(listener != null){
            this.listener = listener;
        }
        try {
            new BackgroundDataSync(getPostDataString(parameters), url, requestType).execute();
            debug(TAG , " asnyc task called");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public void doServerRequest(HashMap<String, String> parameters, String url, int requestType){
        doServerRequest(parameters, url, requestType, null);
    }

    public interface OnServerRequestComplete{
        void onSucess(Bundle bundle);
        void onFailed(int status_code, String mesage, String url);
    }

    public void setOnServerRequestCompleteListener(OnServerRequestComplete listener){
        this.listener = listener;
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }

    class BackgroundDataSync extends AsyncTask<String, Void , String>{
        String params;
        String mUrl;
        int request_type;

        public BackgroundDataSync(String params, String url, int request_type){
            this.mUrl = url;
            this.params = params;
            this.request_type = request_type;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... urls) {
            debug(TAG, "in Background, urls = " + urls.length);
            HttpURLConnection connection;
                debug(TAG, "in Background, url = " + mUrl);
                String response = "";
                switch (request_type) {
                    case 1:
                        try {
                            connection = iniitializeHTTPConnection(mUrl, "POST");
                            OutputStream os = connection.getOutputStream();
                            BufferedWriter writer = new BufferedWriter(
                                    new OutputStreamWriter(os, "UTF-8"));
                            writer.write(params);
                            writer.flush();
                            writer.close();
                            os.close();
                            int responseCode = connection.getResponseCode();
                            if (responseCode == HttpsURLConnection.HTTP_OK) {
                           /* String line;
                            BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
                            while ((line=br.readLine()) != null) {
                                response+=line;
                            }*/
                                response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
                            } else {
                                response = "";
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        break;
                    case 0:
                        connection = iniitializeHTTPConnection(mUrl, "GET");

                        try {
                            if (connection.getResponseCode() == connection.HTTP_OK) {
                                response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            response = "";
                        }
                        break;
                }
                return response;


        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(TextUtils.isEmpty(s) || s.length() == 0){
                listener.onFailed(DbConstants.NOT_FOUND, "Data not found", mUrl);
            }
            else{
                Bundle bundle = new Bundle();
                bundle.putInt(DbConstants.STATUS_CODE, DbConstants.HTTP_OK);
                bundle.putString(DbConstants.RESPONSE, s);
                bundle.putString(DbConstants.URL, mUrl);
                listener.onSucess(bundle);
            }
            //System.out.println("Data Obtained = " + s);
        }

        private HttpURLConnection iniitializeHTTPConnection(String url, String requestType) {
            try {
                debug("ServerRequest", "url = " + url + "requestType = " + requestType);
                URL link = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) link.openConnection();
                conn.setRequestMethod(requestType);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                return conn;
            }
            catch(Exception e){
                e.printStackTrace();
            }
            return null;
        }

    }
    private String getDataFromInputStream(InputStreamReader reader){
        String line;
        String response = "";
        try {

            BufferedReader br = new BufferedReader(reader);
            while ((line = br.readLine()) != null) {
                response += line;

                debug("ServerRequest", "response length = " + response.length());
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }

    private void debug(String tag, String string) {
        Log.d(tag, string);
    }
}

and Just call the function when you needed to get the data from server either by post or get like this

HashMap<String, String>params = new HashMap<String, String>();
                    params.put("action", "request_sample");
                    params.put("name", uname);
                    params.put("message", umsg);
                    params.put("email", getEmailofUser());
                    params.put("type", "bio");
dq.doServerRequest(params, "your_url", DbConstants.METHOD_POST);
                    dq.setOnServerRequestCompleteListener(new ServerRequestHandler.OnServerRequestComplete() {
                        @Override
                        public void onSucess(Bundle bundle) {
                            debug("data", bundle.getString(DbConstants.RESPONSE));
                                                    }

                        @Override
                        public void onFailed(int status_code, String mesage, String url) {
                            debug("sample", mesage);

                        }
                    });

Now it is complete.Enjoy!!! Comment it if find any problem.

GitHub "fatal: remote origin already exists"

update the origin if it exist already using this command

git remote set-url origin https://github.com/SriramUmapathy/ReduxLearning.git

What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?

To answer you first question:
Yes, it means that 1 byte allocates for 1 character. Look at this example

SQL> conn / as sysdba
Connected.
SQL> create table test (id number(10), v_char varchar2(10));

Table created.

SQL> insert into test values(11111111111,'darshan');
insert into test values(11111111111,'darshan')
*
ERROR at line 1:
ORA-01438: value larger than specified precision allows for this column


SQL> insert into test values(11111,'darshandarsh');
insert into test values(11111,'darshandarsh')
*
ERROR at line 1:
ORA-12899: value too large for column "SYS"."TEST"."V_CHAR" (actual: 12,
maximum: 10)


SQL> insert into test values(111,'Darshan');

1 row created.

SQL> 

And to answer your next one: The difference between varchar2 and varchar :

  1. VARCHAR can store up to 2000 bytes of characters while VARCHAR2 can store up to 4000 bytes of characters.
  2. If we declare datatype as VARCHAR then it will occupy space for NULL values, In case of VARCHAR2 datatype it will not occupy any space.

Most efficient way to convert an HTMLCollection to an Array

This works in all browsers including earlier IE versions.

var arr = [];
[].push.apply(arr, htmlCollection);

Since jsperf is still down at the moment, here is a jsfiddle that compares the performance of different methods. https://jsfiddle.net/qw9qf48j/

How do I set/unset a cookie with jQuery?

A simple example of set cookie in your browser:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>jquery.cookie Test Suite</title>

        <script src="jquery-1.9.0.min.js"></script>
        <script src="jquery.cookie.js"></script>
        <script src="JSON-js-master/json.js"></script>
        <script src="JSON-js-master/json_parse.js"></script>
        <script>
            $(function() {

               if ($.cookie('cookieStore')) {
                    var data=JSON.parse($.cookie("cookieStore"));
                    $('#name').text(data[0]);
                    $('#address').text(data[1]);
              }

              $('#submit').on('click', function(){

                    var storeData = new Array();
                    storeData[0] = $('#inputName').val();
                    storeData[1] = $('#inputAddress').val();

                    $.cookie("cookieStore", JSON.stringify(storeData));
                    var data=JSON.parse($.cookie("cookieStore"));
                    $('#name').text(data[0]);
                    $('#address').text(data[1]);
              });
            });

       </script>
    </head>
    <body>
            <label for="inputName">Name</label>
            <br /> 
            <input type="text" id="inputName">
            <br />      
            <br /> 
            <label for="inputAddress">Address</label>
            <br /> 
            <input type="text" id="inputAddress">
            <br />      
            <br />   
            <input type="submit" id="submit" value="Submit" />
            <hr>    
            <p id="name"></p>
            <br />      
            <p id="address"></p>
            <br />
            <hr>  
     </body>
</html>

Simple just copy/paste and use this code for set your cookie.

What is the difference between Document style and RPC style communication?

The main scenario where JAX-WS RPC and Document style are used as follows:

  • The Remote Procedure Call (RPC) pattern is used when the consumer views the web service as a single logical application or component with encapsulated data. The request and response messages map directly to the input and output parameters of the procedure call.

    Examples of this type the RPC pattern might include a payment service or a stock quote service.

  • The document-based pattern is used in situations where the consumer views the web service as a longer running business process where the request document represents a complete unit of information. This type of web service may involve human interaction for example as with a credit application request document with a response document containing bids from lending institutions. Because longer running business processes may not be able to return the requested document immediately, the document-based pattern is more commonly found in asynchronous communication architectures. The Document/literal variation of SOAP is used to implement the document-based web service pattern.

How to drop all tables from a database with one SQL query?

If you want to use only one SQL query to delete all tables you can use this:

EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"

This is a hidden Stored Procedure in sql server, and will be executed for each table in the database you're connected.

Note: You may need to execute the query a few times to delete all tables due to dependencies.

Note2: To avoid the first note, before running the query, first check if there foreign keys relations to any table. If there are then just disable foreign key constraint by running the query bellow:

EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

How can I get the sha1 hash of a string in node.js?

Tips to prevent issue (bad hash) :

I experienced that NodeJS is hashing the UTF-8 representation of the string. Other languages (like Python, PHP or PERL...) are hashing the byte string.

We can add binary argument to use the byte string.

const crypto = require("crypto");

function sha1(data) {
    return crypto.createHash("sha1").update(data, "binary").digest("hex");
}

sha1("Your text ;)");

You can try with : "\xac", "\xd1", "\xb9", "\xe2", "\xbb", "\x93", etc...

Other languages (Python, PHP, ...):

sha1("\xac") //39527c59247a39d18ad48b9947ea738396a3bc47

Nodejs:

sha1 = crypto.createHash("sha1").update("\xac", "binary").digest("hex") //39527c59247a39d18ad48b9947ea738396a3bc47
//without:
sha1 = crypto.createHash("sha1").update("\xac").digest("hex") //f50eb35d94f1d75480496e54f4b4a472a9148752

.NET NewtonSoft JSON deserialize map to a different property name

Expanding Rentering.com's answer, in scenarios where a whole graph of many types is to be taken care of, and you're looking for a strongly typed solution, this class can help, see usage (fluent) below. It operates as either a black-list or white-list per type. A type cannot be both (Gist - also contains global ignore list).

public class PropertyFilterResolver : DefaultContractResolver
{
  const string _Err = "A type can be either in the include list or the ignore list.";
  Dictionary<Type, IEnumerable<string>> _IgnorePropertiesMap = new Dictionary<Type, IEnumerable<string>>();
  Dictionary<Type, IEnumerable<string>> _IncludePropertiesMap = new Dictionary<Type, IEnumerable<string>>();
  public PropertyFilterResolver SetIgnoredProperties<T>(params Expression<Func<T, object>>[] propertyAccessors)
  {
    if (propertyAccessors == null) return this;

    if (_IncludePropertiesMap.ContainsKey(typeof(T))) throw new ArgumentException(_Err);

    var properties = propertyAccessors.Select(GetPropertyName);
    _IgnorePropertiesMap[typeof(T)] = properties.ToArray();
    return this;
  }

  public PropertyFilterResolver SetIncludedProperties<T>(params Expression<Func<T, object>>[] propertyAccessors)
  {
    if (propertyAccessors == null)
      return this;

    if (_IgnorePropertiesMap.ContainsKey(typeof(T))) throw new ArgumentException(_Err);

    var properties = propertyAccessors.Select(GetPropertyName);
    _IncludePropertiesMap[typeof(T)] = properties.ToArray();
    return this;
  }

  protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
  {
    var properties = base.CreateProperties(type, memberSerialization);

    var isIgnoreList = _IgnorePropertiesMap.TryGetValue(type, out IEnumerable<string> map);
    if (!isIgnoreList && !_IncludePropertiesMap.TryGetValue(type, out map))
      return properties;

    Func<JsonProperty, bool> predicate = jp => map.Contains(jp.PropertyName) == !isIgnoreList;
    return properties.Where(predicate).ToArray();
  }

  string GetPropertyName<TSource, TProperty>(
  Expression<Func<TSource, TProperty>> propertyLambda)
  {
    if (!(propertyLambda.Body is MemberExpression member))
      throw new ArgumentException($"Expression '{propertyLambda}' refers to a method, not a property.");

    if (!(member.Member is PropertyInfo propInfo))
      throw new ArgumentException($"Expression '{propertyLambda}' refers to a field, not a property.");

    var type = typeof(TSource);
    if (!type.GetTypeInfo().IsAssignableFrom(propInfo.DeclaringType.GetTypeInfo()))
      throw new ArgumentException($"Expresion '{propertyLambda}' refers to a property that is not from type '{type}'.");

    return propInfo.Name;
  }
}

Usage:

var resolver = new PropertyFilterResolver()
  .SetIncludedProperties<User>(
    u => u.Id, 
    u => u.UnitId)
  .SetIgnoredProperties<Person>(
    r => r.Responders)
  .SetIncludedProperties<Blog>(
    b => b.Id)
  .Ignore(nameof(IChangeTracking.IsChanged)); //see gist

Gitignore not working

After going down a bit of a bit of a rabbit hole trying to follow the answers to this question (maybe because I had to do this in a visual studio project), I found the easier path was to

  1. Cut and paste the file(s) I no longer want to track into a temporary location

  2. Commit the "deletion" of those files

  3. Commit a modification of the .gitignore to exclude the files I had temporarily moved

  4. Move the files back into the folder.

I found this to be the most straight forward way to go about it (at least in a visual studio, or I would assume other IDE heave based environment like Android Studio), without accidentally shooting myself in the foot with a pretty pervasive git rm -rf --cached . , after which the visual studio project I was working on didn't load.

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

FLAG_ACTIVITY_NEW_TASK is the problem here which initiates a new task .Just remove it & you are done.

Well I recommend you to read what every Flag does before working with them

Read this & Intent Flags here

How to add an ORDER BY clause using CodeIgniter's Active Record methods?

function getProductionGroupItems($itemId){
     $this->db->select("*");
     $this->db->where("id",$itemId);
     $this->db->or_where("parent_item_id",$itemId);

    /*********** order by *********** */
     $this->db->order_by("id", "asc");

     $q=$this->db->get("recipe_products");
     if($q->num_rows()>0){
         foreach($q->result() as $row){
             $data[]=$row;
         }
         return $data;
     }
    return false;
}

How can I suppress column header output for a single SQL statement?

Invoke mysql with the -N (the alias for -N is --skip-column-names) option:

mysql -N ...
use testdb;
select * from names;

+------+-------+
|    1 | pete  |
|    2 | john  |
|    3 | mike  |
+------+-------+
3 rows in set (0.00 sec)

Credit to ErichBSchulz for pointing out the -N alias.

To remove the grid (the vertical and horizontal lines) around the results use -s (--silent). Columns are separated with a TAB character.

mysql -s ...
use testdb;
select * from names;

id  name
1   pete
2   john
3   mike

To output the data with no headers and no grid just use both -s and -N.

mysql -sN ...

Remove array element based on object property

One possibility:

myArray = myArray.filter(function( obj ) {
    return obj.field !== 'money';
});

Please note that filter creates a new array. Any other variables referring to the original array would not get the filtered data although you update your original variable myArray with the new reference. Use with caution.

How to generate a QR Code for an Android application?

Have you looked into ZXING? I've been using it successfully to create barcodes. You can see a full working example in the bitcoin application src

// this is a small sample use of the QRCodeEncoder class from zxing
try {
    // generate a 150x150 QR code
    Bitmap bm = encodeAsBitmap(barcode_content, BarcodeFormat.QR_CODE, 150, 150);

    if(bm != null) {
        image_view.setImageBitmap(bm);
    }
} catch (WriterException e) { //eek }

Default Values to Stored Procedure in Oracle

Default-Values are only considered for parameters NOT given to the function.

So given a function

procedure foo( bar1 IN number DEFAULT 3,
     bar2 IN number DEFAULT 5,
     bar3 IN number DEFAULT 8 );

if you call this procedure with no arguments then it will behave as if called with

foo( bar1 => 3,
     bar2 => 5,
     bar3 => 8 );

but 'NULL' is still a parameter.

foo( 4,
     bar3 => NULL );

This will then act like

foo( bar1 => 4,
     bar2 => 5,
     bar3 => Null );

( oracle allows you to either give the parameter in order they are specified in the procedure, specified by name, or first in order and then by name )

one way to treat NULL the same as a default value would be to default the value to NULL

procedure foo( bar1 IN number DEFAULT NULL,
     bar2 IN number DEFAULT NULL,
     bar3 IN number DEFAULT NULL );

and using a variable with the desired value then

procedure foo( bar1 IN number DEFAULT NULL,
     bar2 IN number DEFAULT NULL,
     bar3 IN number DEFAULT NULL )
AS
     v_bar1    number := NVL( bar1, 3);
     v_bar2    number := NVL( bar2, 5);
     v_bar3    number := NVL( bar3, 8);

Why is there no xrange function in Python3?

comp:~$ python Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2

>>> import timeit
>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)

5.656799077987671

>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)

5.579368829727173

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

21.54827117919922

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

22.014557123184204

With timeit number=1 param:

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=1)

0.2245171070098877

>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=1)

0.10750913619995117

comp:~$ python3 Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

9.113872020003328

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

9.07014398300089

With timeit number=1,2,3,4 param works quick and in linear way:

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=1)

0.09329321900440846

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=2)

0.18501482300052885

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=3)

0.2703447980020428

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=4)

0.36209142999723554

So it seems if we measure 1 running loop cycle like timeit.timeit("[x for x in range(1000000) if x%4]",number=1) (as we actually use in real code) python3 works quick enough, but in repeated loops python 2 xrange() wins in speed against range() from python 3.

printf, wprintf, %s, %S, %ls, char* and wchar*: Errors not announced by a compiler warning?

At least in Visual C++: printf (and other ACSII functions): %s represents an ASCII string %S is a Unicode string wprintf (and other Unicode functions): %s is a Unicode string %S is an ASCII string

As far as no compiler warnings, printf uses a variable argument list, with only the first argument able to be type checked. The compiler is not designed to parse the format string and type check the parameters that match. In cases of functions like printf, that is up to the programmer

Reading numbers from a text file into an array in C

for (i = 0; i < 16; i++)
{
    fscanf(myFile, "%d", &numberArray[i]);
}

This is attempting to read the whole string, "5623125698541159" into &numArray[0]. You need spaces between the numbers:

5 6 2 3 ...

Conditional Replace Pandas

Try this:

df.my_channel = df.my_channel.where(df.my_channel <= 20000, other= 0)

or

df.my_channel = df.my_channel.mask(df.my_channel > 20000, other= 0)

input type="submit" Vs button tag are they interchangeable?

<input type='submit' /> doesn't support HTML inside of it, since it's a single self-closing tag. <button>, on the other hand, supports HTML, images, etc. inside because it's a tag pair: <button><img src='myimage.gif' /></button>. <button> is also more flexible when it comes to CSS styling.

The disadvantage of <button> is that it's not fully supported by older browsers. IE6/7, for example, don't display it correctly.

Unless you have some specific reason, it's probably best to stick to <input type='submit' />.

How to select the row with the maximum value in each group

I wasn't sure what you wanted to do about the Event column, but if you want to keep that as well, how about

isIDmax <- with(dd, ave(Value, ID, FUN=function(x) seq_along(x)==which.max(x)))==1
group[isIDmax, ]

#   ID Value Event
# 3  1     5     2
# 7  2    17     2
# 9  3     5     2

Here we use ave to look at the "Value" column for each "ID". Then we determine which value is the maximal and then turn that into a logical vector we can use to subset the original data.frame.

Catching multiple exception types in one catch block

Besides fall-through, it's also possible to step over by using goto. It's very useful if you want to see the world burn.

<?php

class A_Error extends Exception {}
class B_Error extends Exception {}
class C_Error extends Exception {}

try {
    throw new A_Error();
} 
catch (A_Error $e) { goto abc; }
catch (B_Error $e) { goto abc; }
catch (C_Error $e) {
abc:
    var_dump(get_class($e));
    echo "Gotta Catch 'Em All\n";
}

3v4l.org

Trigger validation of all fields in Angular Form submit

To validate all fields of my form when I want, I do a validation on each field of $$controls like this :

angular.forEach($scope.myform.$$controls, function (field) {
    field.$validate();
});

SameSite warning Chrome 77

To elaborate on Rahul Mahadik's answer, this works for MVC5 C#.NET:

AllowSameSiteAttribute.cs

public class AllowSameSiteAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var response = filterContext.RequestContext.HttpContext.Response;

        if(response != null)
        {
            response.AddHeader("Set-Cookie", "HttpOnly;Secure;SameSite=Strict");
            //Add more headers...
        }

        base.OnActionExecuting(filterContext);
    }
}

HomeController.cs

    [AllowSameSite] //For the whole controller
    public class UserController : Controller
    {
    }

or

    public class UserController : Controller
    {
        [AllowSameSite] //For the method
        public ActionResult Index()
        {
            return View();
        }
    }

C# Form.Close vs Form.Dispose

If you use form.close() in your form and set the FormClosing Event of your form and either use form.close() in this Event ,you fall in unlimited loop and Argument out of range happened and the solution is that change the form.close() with form.dispose() in Event of FormClosing. I hope this little tip help you!!!

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

Solution»

Pass a keyword argument name with value as your view name e.g home or home-view etc. to url() function.

Throws Error»

url(r'^home$', 'common.views.view1', 'home'),

Correct»

url(r'^home$', 'common.views.view1', name='home'),

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

I have Windows 8 installed on my machine, and the aspnet_regiis.exe tool did not worked for me either.

The solution that worked for me is posted on this link, on the answer by Neha: System.ServiceModel.Activation.HttpModule error

Everywhere the problem to this solution was mentioned as re-registering aspNet by using aspnet_regiis.exe. But this did not work for me.

Though this is a valid solution (as explained beautifully here)

but it did not work with Windows 8.

For Windows 8 you need to Windows features and enable everything under ".Net Framework 3.5" and ".Net Framework 4.5 Advanced Services".

Thanks Neha

Select All Rows Using Entity Framework

I used the entitydatasource and it provide everything I needed for what I wanted to do.

_repository.[tablename].ToList();

Conda update failed: SSL error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

For those of us on corporate networks using web filters that implement trusted man in the middle SSL solutions, it is necessary to add the web-filter certificate to the certifi cacert.pem.

A guide to doing this is here.

Main steps are:

  1. connect to https site with browser
  2. view and save root certificate
  3. convert cert to .pem
  4. copy and paste onto end of existing cacert.pem
  5. save
  6. SSL happiness

Xlib: extension "RANDR" missing on display ":21". - Trying to run headless Google Chrome

Try this:

Xvfb :21 -screen 0 1024x768x24 +extension RANDR &
Xvfb --help

+extension name        Enable extension
-extension name        Disable extension

How do I create executable Java program?

I'm not quite sure what you mean.

But I assume you mean either 1 of 2 things.

  • You want to create an executable .jar file

Eclipse can do this really easily File --> Export and create a jar and select the appropriate Main-Class and it'll generate the .jar for you. In windows you may have to associate .jar with the java runtime. aka Hold shift down, Right Click "open with" browse to your jvm and associate it with javaw.exe

  • create an actual .exe file then you need to use an extra library like

http://jsmooth.sourceforge.net/ or http://launch4j.sourceforge.net/ will create a native .exe stub with a nice icon that will essentially bootstrap your app. They even figure out if your customer hasn't got a JVM installed and prompt you to get one.

CSS div element - how to show horizontal scroll bars only?

CSS3 has the overflow-x property, but I wouldn't expect great support for that. In CSS2 all you can do is set a general scroll policy and work your widths and heights not to mess them up.

How to copy Docker images from one host to another without using a repository

For a flattened export of a container's filesystem, use;

docker export CONTAINER_ID > my_container.tar

Use cat my_container.tar | docker import - to import said image.

XPath OR operator for different nodes

All title nodes with zipcode or book node as parent:

Version 1:

//title[parent::zipcode|parent::book]

Version 2:

//bookstore/book/title|//bookstore/city/zipcode/title

Version 3: (results are sorted based on source data rather than the order of book then zipcode)

//title[../../../*[book or magazine] or ../../../../*[city/zipcode]]

or - used within true/false - a Boolean operator in xpath

| - a Union operator in xpath that appends the query to the right of the operator to the result set from the left query.

How to edit default dark theme for Visual Studio Code?

The simplest way is to edit the user settings and customise workbench.colorCustomizations

Editing color customizations

If you want to make your theme

There is also the option modify the current theme which will copy the current theme settings and let you save it as a *.color-theme.json JSON5 file

Generate color theme from current settings

Are PHP Variables passed by value or by reference?

Variables containing primitive types are passed by value in PHP5. Variables containing objects are passed by reference. There's quite an interesting article from Linux Journal from 2006 which mentions this and other OO differences between 4 and 5.

http://www.linuxjournal.com/article/9170

Format date in a specific timezone

A couple of answers already mention that moment-timezone is the way to go with named timezone. I just want to clarify something about this library that was pretty confusing to me. There is a difference between these two statements:

moment.tz(date, format, timezone)

moment(date, format).tz(timezone)

Assuming that a timezone is not specified in the date passed in:

The first code takes in the date and assumes the timezone is the one passed in. The second one will take date, assume the timezone from the browser and then change the time and timezone according to the timezone passed in.

Example:

moment.tz('2018-07-17 19:00:00', 'YYYY-MM-DD HH:mm:ss', 'UTC').format() // "2018-07-17T19:00:00Z"

moment('2018-07-17 19:00:00', 'YYYY-MM-DD HH:mm:ss').tz('UTC').format() // "2018-07-18T00:00:00Z"

My timezone is +5 from utc. So in the first case it does not change and it sets the date and time to have utc timezone.

In the second case, it assumes the date passed in is in -5, then turns it into UTC, and that's why it spits out the date "2018-07-18T00:00:00Z"

NOTE: The format parameter is really important. If omitted moment might fall back to the Date class which can unpredictable behaviors


Assuming the timezone is specified in the date passed in:

In this case they both behave equally


Even though now I understand why it works that way, I thought this was a pretty confusing feature and worth explaining.

find difference between two text files with one item per line

You can use the comm command to compare two sorted files

comm -13 <(sort file1) <(sort file2)

How to refresh page on back button click?

A more recent solution is using the The PerformanceNavigation interface:

if(!!window.performance && window.performance.navigation.type === 2)
{
    console.log('Reloading');
    window.location.reload();
}

Where the value 2 means "The page was accessed by navigating into the history".

View browser support here: http://caniuse.com/#search=Navigation%20Timing%20API

Reload the site when reached via browsers back button

Difference between static and shared libraries?

Shared libraries are .so (or in Windows .dll, or in OS X .dylib) files. All the code relating to the library is in this file, and it is referenced by programs using it at run-time. A program using a shared library only makes reference to the code that it uses in the shared library.

Static libraries are .a (or in Windows .lib) files. All the code relating to the library is in this file, and it is directly linked into the program at compile time. A program using a static library takes copies of the code that it uses from the static library and makes it part of the program. [Windows also has .lib files which are used to reference .dll files, but they act the same way as the first one].

There are advantages and disadvantages in each method:

  • Shared libraries reduce the amount of code that is duplicated in each program that makes use of the library, keeping the binaries small. It also allows you to replace the shared object with one that is functionally equivalent, but may have added performance benefits without needing to recompile the program that makes use of it. Shared libraries will, however have a small additional cost for the execution of the functions as well as a run-time loading cost as all the symbols in the library need to be connected to the things they use. Additionally, shared libraries can be loaded into an application at run-time, which is the general mechanism for implementing binary plug-in systems.

  • Static libraries increase the overall size of the binary, but it means that you don't need to carry along a copy of the library that is being used. As the code is connected at compile time there are not any additional run-time loading costs. The code is simply there.

Personally, I prefer shared libraries, but use static libraries when needing to ensure that the binary does not have many external dependencies that may be difficult to meet, such as specific versions of the C++ standard library or specific versions of the Boost C++ library.

An efficient way to transpose a file in Bash

I was looking for a solution to transpose any kind of matrix (nxn or mxn) with any kind of data (numbers or data) and got the following solution:

Row2Trans=number1
Col2Trans=number2

for ((i=1; $i <= Line2Trans; i++));do
    for ((j=1; $j <=Col2Trans ; j++));do
        awk -v var1="$i" -v var2="$j" 'BEGIN { FS = "," }  ; NR==var1 {print $((var2)) }' $ARCHIVO >> Column_$i
    done
done

paste -d',' `ls -mv Column_* | sed 's/,//g'` >> $ARCHIVO

PHP display image BLOB from MySQL

Try Like this.

For Inserting into DB

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
//you keep your column name setting for insertion. I keep image type Blob.
$query = "INSERT INTO products (id,image) VALUES('','$image')";  
$qry = mysqli_query($db, $query);

For Accessing image From Blob

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';

Hope It will help you.

Thanks.

Difference between onCreate() and onStart()?

onCreate() method gets called when activity gets created, and its called only once in whole Activity life cycle. where as onStart() is called when activity is stopped... I mean it has gone to background and its onStop() method is called by the os. onStart() may be called multiple times in Activity life cycle.More details here

C: socket connection timeout

This article might help:

Connect with timeout (or another use for select() )

Looks like you put the socket into non-blocking mode until you've connected, and then put it back into blocking mode once the connection's established.

void connect_w_to(void) { 
  int res; 
  struct sockaddr_in addr; 
  long arg; 
  fd_set myset; 
  struct timeval tv; 
  int valopt; 
  socklen_t lon; 

  // Create socket 
  soc = socket(AF_INET, SOCK_STREAM, 0); 
  if (soc < 0) { 
     fprintf(stderr, "Error creating socket (%d %s)\n", errno, strerror(errno)); 
     exit(0); 
  } 

  addr.sin_family = AF_INET; 
  addr.sin_port = htons(2000); 
  addr.sin_addr.s_addr = inet_addr("192.168.0.1"); 

  // Set non-blocking 
  if( (arg = fcntl(soc, F_GETFL, NULL)) < 0) { 
     fprintf(stderr, "Error fcntl(..., F_GETFL) (%s)\n", strerror(errno)); 
     exit(0); 
  } 
  arg |= O_NONBLOCK; 
  if( fcntl(soc, F_SETFL, arg) < 0) { 
     fprintf(stderr, "Error fcntl(..., F_SETFL) (%s)\n", strerror(errno)); 
     exit(0); 
  } 
  // Trying to connect with timeout 
  res = connect(soc, (struct sockaddr *)&addr, sizeof(addr)); 
  if (res < 0) { 
     if (errno == EINPROGRESS) { 
        fprintf(stderr, "EINPROGRESS in connect() - selecting\n"); 
        do { 
           tv.tv_sec = 15; 
           tv.tv_usec = 0; 
           FD_ZERO(&myset); 
           FD_SET(soc, &myset); 
           res = select(soc+1, NULL, &myset, NULL, &tv); 
           if (res < 0 && errno != EINTR) { 
              fprintf(stderr, "Error connecting %d - %s\n", errno, strerror(errno)); 
              exit(0); 
           } 
           else if (res > 0) { 
              // Socket selected for write 
              lon = sizeof(int); 
              if (getsockopt(soc, SOL_SOCKET, SO_ERROR, (void*)(&valopt), &lon) < 0) { 
                 fprintf(stderr, "Error in getsockopt() %d - %s\n", errno, strerror(errno)); 
                 exit(0); 
              } 
              // Check the value returned... 
              if (valopt) { 
                 fprintf(stderr, "Error in delayed connection() %d - %s\n", valopt, strerror(valopt) 
); 
                 exit(0); 
              } 
              break; 
           } 
           else { 
              fprintf(stderr, "Timeout in select() - Cancelling!\n"); 
              exit(0); 
           } 
        } while (1); 
     } 
     else { 
        fprintf(stderr, "Error connecting %d - %s\n", errno, strerror(errno)); 
        exit(0); 
     } 
  } 
  // Set to blocking mode again... 
  if( (arg = fcntl(soc, F_GETFL, NULL)) < 0) { 
     fprintf(stderr, "Error fcntl(..., F_GETFL) (%s)\n", strerror(errno)); 
     exit(0); 
  } 
  arg &= (~O_NONBLOCK); 
  if( fcntl(soc, F_SETFL, arg) < 0) { 
     fprintf(stderr, "Error fcntl(..., F_SETFL) (%s)\n", strerror(errno)); 
     exit(0); 
  } 
  // I hope that is all 
}

postgresql duplicate key violates unique constraint

For future searchs, use ON CONFLICT DO NOTHING.

How to scanf only integer and repeat reading if the user enters non-numeric characters?

char check1[10], check2[10];
int foo;

do{
  printf(">> ");
  scanf(" %s", check1);
  foo = strtol(check1, NULL, 10); // convert the string to decimal number
  sprintf(check2, "%d", foo); // re-convert "foo" to string for comparison
} while (!(strcmp(check1, check2) == 0 && 0 < foo && foo < 24)); // repeat if the input is not number

If the input is number, you can use foo as your input.

python multithreading wait till all threads finished

You need to use join method of Thread object in the end of the script.

t1 = Thread(target=call_script, args=(scriptA + argumentsA))
t2 = Thread(target=call_script, args=(scriptA + argumentsB))
t3 = Thread(target=call_script, args=(scriptA + argumentsC))

t1.start()
t2.start()
t3.start()

t1.join()
t2.join()
t3.join()

Thus the main thread will wait till t1, t2 and t3 finish execution.

What is a MIME type?

Explanation by analogy

Imagine that you wrote a letter to your pen pal but that you wrote it in different languages each time.

For example, you might have chosen to write your first letter in Tamil, and the second in German etc.

In order for your friend to translate those letters, your friend would need to:

  • (i) identify the language type, and
  • (ii) and then translate it accordingly. But identifying a language is not that easy - it's going to take a lot of computational energy. It would be much easier if you wrote the language you are sending across on the top of your letter - that would make life a lot easier for your friend.

So then, in order to highlight the language you are writing in, you simple annotate the language (e.g. "French") on the top of your letter.

An Example of a letter

How would your friend know or be able to read or distinguish between the different language types you are specifying at the top of your letter? That's easy: you agree upon this beforehand.

Tying the analogy back in with HTML

Because there are different types of data formats which need to be sent over the internet, specifying the data type up front would allow the corresponding client to properly interpret and render the data accordingly to the user.

Why do we have different data formats?

Principally because they serve different purposes and have different abilities.

For example, a PDF format is very different from a picture format - which is also different from a sound format - both serve very different purposes and accordingly are written different prior to being sent over the internet.

Regular expression - starting and ending with a character string

^wp.*\.php$ Should do the trick.

The .* means "any character, repeated 0 or more times". The next . is escaped because it's a special character, and you want a literal period (".php"). Don't forget that if you're typing this in as a literal string in something like C#, Java, etc., you need to escape the backslash because it's a special character in many literal strings.

Keeping ASP.NET Session Open / Alive

Whenever you make a request to the server the session timeout resets. So you can just make an ajax call to an empty HTTP handler on the server, but make sure the handler's cache is disabled, otherwise the browser will cache your handler and won't make a new request.

KeepSessionAlive.ashx.cs

public class KeepSessionAlive : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            context.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
            context.Response.Cache.SetNoStore();
            context.Response.Cache.SetNoServerCaching();
        }
    }

.JS:

window.onload = function () {
        setInterval("KeepSessionAlive()", 60000)
}

 function KeepSessionAlive() {
 url = "/KeepSessionAlive.ashx?";
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", url, true);
        xmlHttp.send();
        }

@veggerby - There is no need for the overhead of storing variables in the session. Just preforming a request to the server is enough.

R: Print list to a text file

depending on your tastes, an alternative to nico's answer:

d<-lapply(mylist, write, file=" ... ", append=T);

How to reduce the image file size using PIL

If you hava a fact png (1MB for 400x400 etc.):

__import__("importlib").import_module("PIL.Image").open("out.png").save("out.png")

sort dict by value python

Thanks for all answers. You are all my heros ;-)

Did in the end something like this:

d = sorted(data, key = data.get)

for key in d:
    text = data[key]

How to send a pdf file directly to the printer using JavaScript?

Try this: Have a button/link which opens a webpage (in a new window) with just the pdf file embedded in it, and print the webpage.

In head of the main page:

<script type="text/javascript">
function printpdf() 
{
myWindow=window.open("pdfwebpage.html");
myWindow.close;  //optional, to close the new window as soon as it opens
//this ensures user doesn't have to close the pop-up manually
}
</script>

And in body of the main page:

<a href="printpdf()">Click to Print the PDF</a>

Inside pdfwebpage.html:

<html>
<head>    
</head>

<body onload="window.print()">
<embed src="pdfhere.pdf"/>

</body>
</html>

Django URLs TypeError: view must be a callable or a list/tuple in the case of include()

Django 1.10 no longer allows you to specify views as a string (e.g. 'myapp.views.home') in your URL patterns.

The solution is to update your urls.py to include the view callable. This means that you have to import the view in your urls.py. If your URL patterns don't have names, then now is a good time to add one, because reversing with the dotted python path no longer works.

from django.conf.urls import include, url

from django.contrib.auth.views import login
from myapp.views import home, contact

urlpatterns = [
    url(r'^$', home, name='home'),
    url(r'^contact/$', contact, name='contact'),
    url(r'^login/$', login, name='login'),
]

If there are many views, then importing them individually can be inconvenient. An alternative is to import the views module from your app.

from django.conf.urls import include, url

from django.contrib.auth import views as auth_views
from myapp import views as myapp_views

urlpatterns = [
    url(r'^$', myapp_views.home, name='home'),
    url(r'^contact/$', myapp_views.contact, name='contact'),
    url(r'^login/$', auth_views.login, name='login'),
]

Note that we have used as myapp_views and as auth_views, which allows us to import the views.py from multiple apps without them clashing.

See the Django URL dispatcher docs for more information about urlpatterns.

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

Every service that is bound in activity must be unbind on app close.

So try using

 onPause(){
   unbindService(YOUR_SERVICE);
   super.onPause();
 }

How to set xampp open localhost:8080 instead of just localhost

you can get loccalhost page by writing localhost/xampp or by writing http://127.0.0.1 you will get the local host page. After starting the apache serve that can be from wamp, xamp or lamp.

Difference between drop table and truncate table?

In the SQL standard, DROP table removes the table and the table schema - TRUNCATE removes all rows.

Difference between using gradlew and gradle

The difference lies in the fact that ./gradlew indicates you are using a gradle wrapper. The wrapper is generally part of a project and it facilitates installation of gradle. If you were using gradle without the wrapper you would have to manually install it - for example, on a mac brew install gradle and then invoke gradle using the gradle command. In both cases you are using gradle, but the former is more convenient and ensures version consistency across different machines.

Each Wrapper is tied to a specific version of Gradle, so when you first run one of the commands above for a given Gradle version, it will download the corresponding Gradle distribution and use it to execute the build.

Not only does this mean that you don’t have to manually install Gradle yourself, but you are also sure to use the version of Gradle that the build is designed for. This makes your historical builds more reliable

Read more here - https://docs.gradle.org/current/userguide/gradle_wrapper.html

Also, Udacity has a neat, high level video explaining the concept of the gradle wrapper - https://www.youtube.com/watch?v=1aA949H-shk

Excel 2007 - Compare 2 columns, find matching values

VLOOKUP deosnt work for String literals

Convert timestamp to date in MySQL query

you can try this
The date is of timestamp type which has the following format: ‘YYYY-MM-DD HH:MM:SS’ or ‘2008-10-05 21:34:02.’

$res = mysql_query("SELECT date FROM times;");
while ( $row = mysql_fetch_array($res) ) {
   echo $row['date'] . "
";
}

The PHP strtotime function parses the MySQL timestamp into a Unix timestamp which can be utilized for further parsing or formatting in the PHP date function.

Here are some other sample date output formats that may be of practical use:

echo date("F j, Y g:i a", strtotime($row["date"]));                  // October 5, 2008 9:34 pm
echo date("m.d.y", strtotime($row["date"]));                         // 10.05.08
echo date("j, n, Y", strtotime($row["date"]));                       // 5, 10, 2008
echo date("Ymd", strtotime($row["date"]));                           // 20081005
echo date('\i\t \i\s \t\h\e jS \d\a\y.', strtotime($row["date"]));   // It is the 5th day.
echo date("D M j G:i:s T Y", strtotime($row["date"]));               // Sun Oct 5 21:34:02 PST 2008

Difference between one-to-many and many-to-one relationship

There's no practical difference. Just use the relationship which makes the most sense given the way you see your problem as Devendra illustrated.

How to make war file in Eclipse

File -> Export -> Web -> WAR file

OR in Kepler follow as shown below :

enter image description here

How do you transfer or export SQL Server 2005 data to Excel

I've found an easy way to export query results from SQL Server Management Studio 2005 to Excel.

1) Select menu item Query -> Query Options.

2) Set check box in Results -> Grid -> Include column headers when copying or saving the results.

After that, when you Select All and Copy the query results, you can paste them to Excel, and the column headers will be present.

Convert JsonObject to String

JSONObject metadata = (JSONObject) data.get("map"); //for example
String jsonString = metadata.**toJSONString()**;

C - reading command line parameters

When you write your main function, you typically see one of two definitions:

  • int main(void)
  • int main(int argc, char **argv)

The second form will allow you to access the command line arguments passed to the program, and the number of arguments specified (arguments are separated by spaces).

The arguments to main are:

  • int argc - the number of arguments passed into your program when it was run. It is at least 1.
  • char **argv - this is a pointer-to-char *. It can alternatively be this: char *argv[], which means 'array of char *'. This is an array of C-style-string pointers.

Basic Example

For example, you could do this to print out the arguments passed to your C program:

#include <stdio.h>

int main(int argc, char **argv)
{
    for (int i = 0; i < argc; ++i)
    {
        printf("argv[%d]: %s\n", i, argv[i]);
    }
}

I'm using GCC 4.5 to compile a file I called args.c. It'll compile and build a default a.out executable.

[birryree@lilun c_code]$ gcc -std=c99 args.c

Now run it...

[birryree@lilun c_code]$ ./a.out hello there
argv[0]: ./a.out
argv[1]: hello
argv[2]: there

So you can see that in argv, argv[0] is the name of the program you ran (this is not standards-defined behavior, but is common. Your arguments start at argv[1] and beyond.

So basically, if you wanted a single parameter, you could say...

./myprogram integral


A Simple Case for You

And you could check if argv[1] was integral, maybe like strcmp("integral", argv[1]) == 0.

So in your code...

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    if (argc < 2) // no arguments were passed
    {
        // do something
    }

    if (strcmp("integral", argv[1]) == 0)
    {
        runIntegral(...); //or something
    }
    else
    {
        // do something else.
    }
}

Better command line parsing

Of course, this was all very rudimentary, and as your program gets more complex, you'll likely want more advanced command line handling. For that, you could use a library like GNU getopt.

error: package com.android.annotations does not exist

Annotations come from the support's library which are packaged in android.support.annotation.

As another option you can use @NonNull annotation which denotes that a parameter, field or method return value can never be null.
It is imported from import android.support.annotation.NonNull;

Python 3.4.0 with MySQL database

There is a Ubuntu solution available either through the Ubuntu Software Center or through the Synaptic Package Manager. This will connect Python version 3.4.0 to MySQL. Download "python3-mysql.connector" version 1.1.6-1.

Note that the connection syntax does not use "MySQLdb". Instead read: Connecting to MySQL Using Connector/Python

Execute method on startup in Spring

If by "application startup" you mean "application context startup", then yes, there are many ways to do this, the easiest (for singletons beans, anyway) being to annotate your method with @PostConstruct. Take a look at the link to see the other options, but in summary they are:

  • Methods annotated with @PostConstruct
  • afterPropertiesSet() as defined by the InitializingBean callback interface
  • A custom configured init() method

Technically, these are hooks into the bean lifecycle, rather than the context lifecycle, but in 99% of cases, the two are equivalent.

If you need to hook specifically into the context startup/shutdown, then you can implement the Lifecycle interface instead, but that's probably unnecessary.

Custom HTTP Authorization Header

The format defined in RFC2617 is credentials = auth-scheme #auth-param. So, in agreeing with fumanchu, I think the corrected authorization scheme would look like

Authorization: FIRE-TOKEN apikey="0PN5J17HBGZHT7JJ3X82", hash="frJIUN8DYpKDtOLCwo//yllqDzg="

Where FIRE-TOKEN is the scheme and the two key-value pairs are the auth parameters. Though I believe the quotes are optional (from Apendix B of p7-auth-19)...

auth-param = token BWS "=" BWS ( token / quoted-string )

I believe this fits the latest standards, is already in use (see below), and provides a key-value format for simple extension (if you need additional parameters).

Some examples of this auth-param syntax can be seen here...

http://tools.ietf.org/html/draft-ietf-httpbis-p7-auth-19#section-4.4

https://developers.google.com/youtube/2.0/developers_guide_protocol_clientlogin

https://developers.google.com/accounts/docs/AuthSub#WorkingAuthSub

gradient descent using python and numpy

Following @thomas-jungblut implementation in python, i did the same for Octave. If you find something wrong please let me know and i will fix+update.

Data comes from a txt file with the following rows:

1 10 1000
2 20 2500
3 25 3500
4 40 5500
5 60 6200

think about it as a very rough sample for features [number of bedrooms] [mts2] and last column [rent price] which is what we want to predict.

Here is the Octave implementation:

%
% Linear Regression with multiple variables
%

% Alpha for learning curve
alphaNum = 0.0005;

% Number of features
n = 2;

% Number of iterations for Gradient Descent algorithm
iterations = 10000

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% No need to update after here
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

DATA = load('CHANGE_WITH_DATA_FILE_PATH');

% Initial theta values
theta = ones(n + 1, 1);

% Number of training samples
m = length(DATA(:, 1));

% X with one mor column (x0 filled with '1's)
X = ones(m, 1);
for i = 1:n
  X = [X, DATA(:,i)];
endfor

% Expected data must go always in the last column  
y = DATA(:, n + 1)

function gradientDescent(x, y, theta, alphaNum, iterations)
  iterations = [];
  costs = [];

  m = length(y);

  for iteration = 1:10000
    hypothesis = x * theta;

    loss = hypothesis - y;

    % J(theta)    
    cost = sum(loss.^2) / (2 * m);

    % Save for the graphic to see if the algorithm did work
    iterations = [iterations, iteration];
    costs = [costs, cost];

    gradient = (x' * loss) / m; % /m is for the average

    theta = theta - (alphaNum * gradient);
  endfor    

  % Show final theta values
  display(theta)

  % Show J(theta) graphic evolution to check it worked, tendency must be zero
  plot(iterations, costs);

endfunction

% Execute gradient descent
gradientDescent(X, y, theta, alphaNum, iterations);

Re-assign host access permission to MySQL user

I haven't had to do this, so take this with a grain of salt and a big helping of "test, test, test".

What happens if (in a safe controlled test environment) you directly modify the Host column in the mysql.user and probably mysql.db tables? (E.g., with an update statement.) I don't think MySQL uses the user's host as part of the password encoding (the PASSWORD function doesn't suggest it does), but you'll have to try it to be sure. You may need to issue a FLUSH PRIVILEGES command (or stop and restart the server).

For some storage engines (MyISAM, for instance), you may also need to check/modify the .frm file any views that user has created. The .frm file stores the definer, including the definer's host. (I have had to do this, when moving databases between hosts where there had been a misconfiguration causing the wrong host to be recorded...)

LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

I had this problem minutes ago. It went away when I added 'extern "C"' to the main() definition.

Oddly, another simple program I wrote yesterday is almost identical, does not have the extern "C", yet compiled without this linker error.

This makes me think the problem is some subtle setting to be found deep in some configuration dialog, and that 'extern "C"' doesn't really solve the underlying problem, but superficially makes things work.

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv'

Try to give the full path to your csv file

open('/users/gcameron/Desktop/map/data.csv')

The python process is looking for file in the directory it is running from.

WCF on IIS8; *.svc handler mapping doesn't work

I had to enable HTTP Activation in .NET Framework 4.5 Advanced Services > WCF Services

Enable HTTP Activation

In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

This is because JavaScript uses type coercion in Boolean contexts and your code

if ("0") 

will be coerced to true in boolean contexts.

There are other truthy values in Javascript which will be coerced to true in boolean contexts, and thus execute the if block are:-

if (true)
if ({})
if ([])
if (42)
if ("0")
if ("false")
if (new Date())
if (-42)
if (12n)
if (3.14)
if (-3.14)
if (Infinity)
if (-Infinity)

jQuery scroll to ID from different page

I've written something that detects if the page contains the anchor that was clicked on, and if not, goes to the normal page, otherwise it scrolls to the specific section:

$('a[href*=\\#]').on('click',function(e) {

    var target = this.hash;
    var $target = $(target);
    console.log(targetname);
    var targetname = target.slice(1, target.length);

    if(document.getElementById(targetname) != null) {
         e.preventDefault();
    }
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top-120 //or the height of your fixed navigation 

    }, 900, 'swing', function () {
        window.location.hash = target;
  });
});

How do I view executed queries within SQL Server Management Studio?

Use SQL Profiler and use a filter on it to get the most expensive queries.

MySQL: What's the difference between float and double?

Thought I'd add my own example that helped me see the difference using the value 1.3 when adding or multiplying with another float, decimal, and double .

1.3 float ADDED to 1.3 of different types:

|float              | double | decimal |
+-------------------+------------+-----+
|2.5999999046325684 | 2.6    | 2.60000 |

1.3 float MULTIPLIED by 1.3 of different types:

| float              | double             | decimal      |
+--------------------+--------------------+--------------+
| 1.6899998760223411 | 1.6900000000000002 | 1.6900000000 |

This is using MySQL 6.7

Query:

SELECT 
    float_1 + float_2 as 'float add',
    double_1 + double_2 as 'double add',
    decimal_1 + decimal_2 as 'decimal add',

    float_1 * float_2 as 'float multiply',
    double_1 * double_2 as 'double multiply',
    decimal_1 * decimal_2 as 'decimal multiply'
FROM numerics

Create Table and Insert Data:

CREATE TABLE `numerics` (
  `float_1` float DEFAULT NULL,
  `float_2` float DEFAULT NULL,
  `double_1` double DEFAULT NULL,
  `double_2` double DEFAULT NULL,
  `decimal_1` decimal(10,5) DEFAULT NULL,
  `decimal_2` decimal(10,5) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `_numerics` 
    (
        `float_1`,
        `float_2`,
        `double_1`,
        `double_2`,
        `decimal_1`,
        `decimal_2`
    )
VALUES
    (
        1.3,
        1.3,
        1.3,
        1.3,
        1.30000,
        1.30000
    );

Display MessageBox in ASP

<% response.write("<script language=""javascript"">alert('Hello!');</script>") %>

Accessing Session Using ASP.NET Web API

I followed @LachlanB approach and indeed the session was available when the session cookie was present on the request. The missing part is how the Session cookie is sent to the client the first time?

I created a HttpModule which not only enabling the HttpSessionState availability but also sends the cookie to the client when a new session is created.

public class WebApiSessionModule : IHttpModule
{
    private static readonly string SessionStateCookieName = "ASP.NET_SessionId";

    public void Init(HttpApplication context)
    {
        context.PostAuthorizeRequest += this.OnPostAuthorizeRequest;
        context.PostRequestHandlerExecute += this.PostRequestHandlerExecute;
    }

    public void Dispose()
    {
    }

    protected virtual void OnPostAuthorizeRequest(object sender, EventArgs e)
    {
        HttpContext context = HttpContext.Current;

        if (this.IsWebApiRequest(context))
        {
            context.SetSessionStateBehavior(SessionStateBehavior.Required);
        }
    }

    protected virtual void PostRequestHandlerExecute(object sender, EventArgs e)
    {
        HttpContext context = HttpContext.Current;

        if (this.IsWebApiRequest(context))
        {
            this.AddSessionCookieToResponseIfNeeded(context);
        }
    }

    protected virtual void AddSessionCookieToResponseIfNeeded(HttpContext context)
    {
        HttpSessionState session = context.Session;

        if (session == null)
        {
            // session not available
            return;
        }

        if (!session.IsNewSession)
        {
            // it's safe to assume that the cookie was
            // received as part of the request so there is
            // no need to set it
            return;
        }

        string cookieName = GetSessionCookieName();
        HttpCookie cookie = context.Response.Cookies[cookieName];
        if (cookie == null || cookie.Value != session.SessionID)
        {
            context.Response.Cookies.Remove(cookieName);
            context.Response.Cookies.Add(new HttpCookie(cookieName, session.SessionID));
        }
    }

    protected virtual string GetSessionCookieName()
    {
        var sessionStateSection = (SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState");

        return sessionStateSection != null && !string.IsNullOrWhiteSpace(sessionStateSection.CookieName) ? sessionStateSection.CookieName : SessionStateCookieName;
    }

    protected virtual bool IsWebApiRequest(HttpContext context)
    {
        string requestPath = context.Request.AppRelativeCurrentExecutionFilePath;

        if (requestPath == null)
        {
            return false;
        }

        return requestPath.StartsWith(WebApiConfig.UrlPrefixRelative, StringComparison.InvariantCultureIgnoreCase);
    }
}

$_POST Array from html form

You should get the array like in $_POST['id']. So you should be able to do this:

foreach ($_POST['id'] as $key => $value) {
    echo $value . "<br />";
}

Input names should be same:

<input name='id[]' type='checkbox' value='1'>
<input name='id[]' type='checkbox' value='2'>
...

How to find row number of a value in R code

If you want to know the row and column of a value in a matrix or data.frame, consider using the arr.ind=TRUE argument to which:

> which(mydata_2 == 1578, arr.ind=TRUE)
  row col
7   7   3

So 1578 is in column 3 (which you already know) and row 7.

Python Set Comprehension

You can generate pairs like this:

{(x, x + 2) for x in r if x + 2 in r}

Then all that is left to do is to get a condition to make them prime, which you have already done in the first example.

A different way of doing it: (Although slower for large sets of primes)

{(x, y) for x in r for y in r if x + 2 == y}

Omitting all xsi and xsd namespaces when serializing an object in .NET?

XmlSerializer sr = new XmlSerializer(objectToSerialize.GetType());
TextWriter xmlWriter = new StreamWriter(filename);
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
sr.Serialize(xmlWriter, objectToSerialize, namespaces);

-bash: syntax error near unexpected token `newline'

The characters '<', and '>', are to indicate a place-holder, you should remove them to read:

php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME

How to save and extract session data in codeigniter

CI Session Class track information about each user while they browse site.Ci Session class generates its own session data, offering more flexibility for developers.

Initializing a Session

To initialize the Session class manually in our controller constructor use following code.

Adding Custom Session Data

We can add our custom data in session array.To add our data to the session array involves passing an array containing your new data to this function.

$this->session->set_userdata($newarray);

Where $newarray is an associative array containing our new data.

$newarray = array( 'name' => 'manish', 'email' => '[email protected]'); $this->session->set_userdata($newarray); 

Retrieving Session

$session_id = $this->session->userdata('session_id');

Above function returns FALSE (boolean) if the session array does not exist.

Retrieving All Session Data

$this->session->all_userdata()

I have taken reference from http://www.tutsway.com/codeigniter-session.php.

How can I list all tags for a Docker image on a remote registry?

Building on Yan Foto's answer (the v2 api), I created a simple Python script to list the tags for a given image.

Usage:

./docker-registry-list.py alpine

Output:

{
  "name": "library/alpine",
  "tags": [
    "2.6",
    "2.7",
    "3.1",
    "3.2",
    "3.3",
    "3.4",
    "3.5",
    "3.6",
    "3.7",
    "edge",
    "latest"
  ]
}

Page scroll up or down in Selenium WebDriver (Selenium 2) using java

This may not be an exact answer to your question (in terms of WebDriver), but I've found that the java.awt library is more stable than selenium.Keys. So, a page down action using the former will be:

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_PAGE_DOWN);
robot.keyRelease(KeyEvent.VK_PAGE_DOWN);

Access all Environment properties as a Map or Properties object

I had the requirement to retrieve all properties whose key starts with a distinct prefix (e.g. all properties starting with "log4j.appender.") and wrote following Code (using streams and lamdas of Java 8).

public static Map<String,Object> getPropertiesStartingWith( ConfigurableEnvironment aEnv,
                                                            String aKeyPrefix )
{
    Map<String,Object> result = new HashMap<>();

    Map<String,Object> map = getAllProperties( aEnv );

    for (Entry<String, Object> entry : map.entrySet())
    {
        String key = entry.getKey();

        if ( key.startsWith( aKeyPrefix ) )
        {
            result.put( key, entry.getValue() );
        }
    }

    return result;
}

public static Map<String,Object> getAllProperties( ConfigurableEnvironment aEnv )
{
    Map<String,Object> result = new HashMap<>();
    aEnv.getPropertySources().forEach( ps -> addAll( result, getAllProperties( ps ) ) );
    return result;
}

public static Map<String,Object> getAllProperties( PropertySource<?> aPropSource )
{
    Map<String,Object> result = new HashMap<>();

    if ( aPropSource instanceof CompositePropertySource)
    {
        CompositePropertySource cps = (CompositePropertySource) aPropSource;
        cps.getPropertySources().forEach( ps -> addAll( result, getAllProperties( ps ) ) );
        return result;
    }

    if ( aPropSource instanceof EnumerablePropertySource<?> )
    {
        EnumerablePropertySource<?> ps = (EnumerablePropertySource<?>) aPropSource;
        Arrays.asList( ps.getPropertyNames() ).forEach( key -> result.put( key, ps.getProperty( key ) ) );
        return result;
    }

    // note: Most descendants of PropertySource are EnumerablePropertySource. There are some
    // few others like JndiPropertySource or StubPropertySource
    myLog.debug( "Given PropertySource is instanceof " + aPropSource.getClass().getName()
                 + " and cannot be iterated" );

    return result;

}

private static void addAll( Map<String, Object> aBase, Map<String, Object> aToBeAdded )
{
    for (Entry<String, Object> entry : aToBeAdded.entrySet())
    {
        if ( aBase.containsKey( entry.getKey() ) )
        {
            continue;
        }

        aBase.put( entry.getKey(), entry.getValue() );
    }
}

Note that the starting point is the ConfigurableEnvironment which is able to return the embedded PropertySources (the ConfigurableEnvironment is a direct descendant of Environment). You can autowire it by:

@Autowired
private ConfigurableEnvironment  myEnv;

If you not using very special kinds of property sources (like JndiPropertySource, which is usually not used in spring autoconfiguration) you can retrieve all properties held in the environment.

The implementation relies on the iteration order which spring itself provides and takes the first found property, all later found properties with the same name are discarded. This should ensure the same behaviour as if the environment were asked directly for a property (returning the first found one).

Note also that the returned properties are not yet resolved if they contain aliases with the ${...} operator. If you want to have a particular key resolved you have to ask the Environment directly again:

myEnv.getProperty( key );

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

If you need to just empty the style of an element then:
element.style.cssText = null;
This should do good. Hope it helps!

selenium - chromedriver executable needs to be in PATH

Another way is download and unzip chromedriver and put 'chromedriver.exe' in C:\Python27\Scripts and then you need not to provide the path of driver, just

driver= webdriver.Chrome()

will work

Can testify that this also works for Python3.7.

How to automatically generate N "distinct" colors?

I think this simple recursive algorithm complementes the accepted answer, in order to generate distinct hue values. I made it for hsv, but can be used for other color spaces too.

It generates hues in cycles, as separate as possible to each other in each cycle.

/**
 * 1st cycle: 0, 120, 240
 * 2nd cycle (+60): 60, 180, 300
 * 3th cycle (+30): 30, 150, 270, 90, 210, 330
 * 4th cycle (+15): 15, 135, 255, 75, 195, 315, 45, 165, 285, 105, 225, 345
 */
public static float recursiveHue(int n) {
    // if 3: alternates red, green, blue variations
    float firstCycle = 3;

    // First cycle
    if (n < firstCycle) {
        return n * 360f / firstCycle;
    }
    // Each cycle has as much values as all previous cycles summed (powers of 2)
    else {
        // floor of log base 2
        int numCycles = (int)Math.floor(Math.log(n / firstCycle) / Math.log(2));
        // divDown stores the larger power of 2 that is still lower than n
        int divDown = (int)(firstCycle * Math.pow(2, numCycles));
        // same hues than previous cycle, but summing an offset (half than previous cycle)
        return recursiveHue(n % divDown) + 180f / divDown;
    }
}

I was unable to find this kind of algorithm here. I hope it helps, it's my first post here.

Regex to validate password strength

For PHP, this works fine!

 if(preg_match("/^(?=(?:[^A-Z]*[A-Z]){2})(?=(?:[^0-9]*[0-9]){2}).{8,}$/", 
 'CaSu4Li8')){
    return true;
 }else{
    return fasle;
 }

in this case the result is true

Thsks for @ridgerunner

Converting HTML files to PDF

The Flying Saucer XHTML renderer project has support for outputting XHTML to PDF. Have a look at an example here.

Validating URL in Java

The java.net.URL class is in fact not at all a good way of validating URLs. MalformedURLException is not thrown on all malformed URLs during construction. Catching IOException on java.net.URL#openConnection().connect() does not validate URL either, only tell wether or not the connection can be established.

Consider this piece of code:

    try {
        new URL("http://.com");
        new URL("http://com.");
        new URL("http:// ");
        new URL("ftp://::::@example.com");
    } catch (MalformedURLException malformedURLException) {
        malformedURLException.printStackTrace();
    }

..which does not throw any exceptions.

I recommend using some validation API implemented using a context free grammar, or in very simplified validation just use regular expressions. However I need someone to suggest a superior or standard API for this, I only recently started searching for it myself.

Note It has been suggested that URL#toURI() in combination with handling of the exception java.net. URISyntaxException can facilitate validation of URLs. However, this method only catches one of the very simple cases above.

The conclusion is that there is no standard java URL parser to validate URLs.

GridLayout and Row/Column Span Woe

You have to set both layout_gravity and layout_columntWeight on your columns

<android.support.v7.widget.GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView android:text="??? ???"
        app:layout_gravity="fill_horizontal"
        app:layout_columnWeight="1"
        />

    <TextView android:text="??? ???"
        app:layout_gravity="fill_horizontal"
        app:layout_columnWeight="1"
        />

    <TextView android:text="??? ???"
        app:layout_gravity="fill_horizontal"
        app:layout_columnWeight="1"
        />
 </android.support.v7.widget.GridLayout>

Where is JAVA_HOME on macOS Mojave (10.14) to Lion (10.7)?

On Mac OS X Lion, to set visualgc to run, I used:

export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

How to remove a branch locally?

you need switch into another branch and try the same.

git branch -d

Opening database file from within SQLite command-line shell

The same way you do it in other db system, you can use the name of the db for identifying double named tables. unique tablenames can used directly.

select * from ttt.table_name;

or if table name in all attached databases is unique

select * from my_unique_table_name;

But I think the of of sqlite-shell is only for manual lookup or manual data manipulation and therefor this way is more inconsequential

normally you would use sqlite-command-line in a script

string.split - by multiple character delimiter

Another option:

Replace the string delimiter with a single character, then split on that character.

string input = "abc][rfd][5][,][.";
string[] parts1 = input.Replace("][","-").Split('-');

What does the "+=" operator do in Java?

It's one of the assignment operators. It takes the value of x, adds 0.1 to it, and then stores the result of (x + 0.1) back into x.

So:

double x = 1.3;
x += 0.1;    // sets 'x' to 1.4

It's functionally identical to, but shorter than:

double x = 1.3;
x = x + 0.1;

NOTE: When doing floating-point math, things don't always work the way you think they will.

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

Another, and more streamlined, approach to deserializing a camel-cased JSON string to a pascal-cased POCO object is to use the CamelCasePropertyNamesContractResolver.

It's part of the Newtonsoft.Json.Serialization namespace. This approach assumes that the only difference between the JSON object and the POCO lies in the casing of the property names. If the property names are spelled differently, then you'll need to resort to using JsonProperty attributes to map property names.

using Newtonsoft.Json; 
using Newtonsoft.Json.Serialization;

. . .

private User LoadUserFromJson(string response) 
{
    JsonSerializerSettings serSettings = new JsonSerializerSettings();
    serSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    User outObject = JsonConvert.DeserializeObject<User>(jsonValue, serSettings);

    return outObject; 
}

How to open maximized window with Javascript?

If I use Firefox then screen.width and screen.height works fine but in IE and Chrome they don't work properly instead it opens with the minimum size.

And yes I tried giving too large numbers too like 10000 for both height and width but not exactly the maximized effect.

Getting value from a cell from a gridview on RowDataBound event

The above are good suggestions, but you can get at the text value of a cell in a grid view without wrapping it in a literal or label control. You just have to know what event to wire up. In this case, use the DataBound event instead, like so:

protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.Cells[0].Text.Contains("sometext"))
        {
            e.Row.Cells[0].Font.Bold = true;
        }
    }
}

When running a debugger, you will see the text appear in this method.

How to set the range of y-axis for a seaborn boxplot?

It is standard matplotlib.pyplot:

...
import matplotlib.pyplot as plt
plt.ylim(10, 40)

Or simpler, as mwaskom comments below:

ax.set(ylim=(10, 40))

enter image description here

How do you share constants in NodeJS modules?

ES6 way.

export in foo.js

const FOO = 'bar';
module.exports = {
  FOO
}

import in bar.js

const {FOO} = require('foo');

type object 'datetime.datetime' has no attribute 'datetime'

For python 3.3

from datetime import datetime, timedelta
futuredate = datetime.now() + timedelta(days=10)

Using subprocess to run Python script on Windows

It looks like windows tries to run the script using its own EXE framework rather than call it like

python /the/script.py

Try,

subprocess.Popen(["python", "/the/script.py"])

Edit: "python" would need to be on your path.

jquery onclick change css background image

I think this should be:

$('.home').click(function() {
     $(this).css('background', 'url(images/tabs3.png)');
 });

and remove this:

<div class="home" onclick="function()">
     //-----------^^^^^^^^^^^^^^^^^^^^---------no need for this

You have to make sure you have a correct path to your image.

How do I use variables in Oracle SQL Developer?

I think that the Easiest way in your case is :

DEFINE EmpIDVar = 1234;

SELECT *
FROM Employees
WHERE EmployeeID = &EmpIDVar

For the string values it will be like :

DEFINE EmpIDVar = '1234';

SELECT *
FROM Employees
WHERE EmployeeID = '&EmpIDVar'

When should we use mutex and when should we use semaphore

A mutex is a special case of a semaphore. A semaphore allows several threads to go into the critical section. When creating a semaphore you define how may threads are allowed in the critical section. Of course your code must be able to handle several accesses to this critical section.

Base table or view not found: 1146 Table Laravel 5

Check your migration file, maybe you are using Schema::table, like this:

Schema::table('table_name', function ($table)  {
    // ...
});

If you want to create a new table you must use Schema::create:

Schema::create('table_name', function ($table)  {
    // ...
});

Change EditText hint color when using TextInputLayout

I only wanted to change the label color when it is lifted to top. But setting textColorHint changes the color at every state. So, this worked for me:

   <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
       ...
        <item name="colorControlActivated">@color/colorPrimary</item>
       ...
    </style>

This will change the color when the input is focused.

How should I import data from CSV into a Postgres table using pgAdmin 3?

You may have a table called 'test'

COPY test(gid, "name", the_geom)
FROM '/home/data/sample.csv'
WITH DELIMITER ','
CSV HEADER

Firebase TIMESTAMP to date and Time

I know the firebase give the timestamp in {seconds: '', and nanoseconds: ''} for converting into date u have to only do:

  • take a firebase time in one var ex:- const date

and then date.toDate() => It returns the date.

When is del useful in Python?

Here goes my 2 cents contribution:

I have a optimization problem where I use a Nlopt library for it. I initializing the class and some of its methods, I was using in several other parts of the code.

I was having ramdom results even if applying the same numerical problem.

I just realized that by doing it, some spurius data was contained in the object when it should have no issues at all. After using del, I guess the memory is being properly cleared and it might be an internal issue to that class where some variables might not be liking to be reused without proper constructor.

JSON.Net Self referencing loop detected

Sometimes you have loops becouse your type class have references to other classes and that classes have references to your type class, thus you have to select the parameters that you need exactly in the json string, like this code.

List<ROficina> oficinas = new List<ROficina>();
oficinas = /*list content*/;
var x = JsonConvert.SerializeObject(oficinas.Select(o => new
            {
                o.IdOficina,
                o.Nombre
            }));

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

These are use in ruby on rails :-

<% %> :-

The <% %> tags are used to execute Ruby code that does not return anything, such as conditions, loops or blocks. Eg :-

<h1>Names of all the people</h1>
<% @people.each do |person| %>
  Name: <%= person.name %><br>
<% end %>

<%= %> :-

use to display the content .

Name: <%= person.name %><br>

<% -%>:-

Rails extends ERB, so that you can suppress the newline simply by adding a trailing hyphen to tags in Rails templates

<%# %>:-

comment out the code

<%# WRONG %>
Hi, Mr. <% puts "Frodo" %>

Show two digits after decimal point in c++

This will be possible with setiosflags(ios::showpoint).

HTML/CSS Making a textbox with text that is grayed out, and disappears when I click to enter info, how?

This answer illustrates a pre-HTML5 approach. Please take a look at Psytronic's answer for a modern solution using the placeholder attribute.


HTML:

<input type="text" name="firstname" title="First Name" style="color:#888;" 
    value="First Name" onfocus="inputFocus(this)" onblur="inputBlur(this)" />

JavaScript:

function inputFocus(i) {
    if (i.value == i.defaultValue) { i.value = ""; i.style.color = "#000"; }
}
function inputBlur(i) {
    if (i.value == "") { i.value = i.defaultValue; i.style.color = "#888"; }
}

SQL Server Linked Server Example Query

Usually direct queries should not be used in case of linked server because it heavily use temp database of SQL server. At first step data is retrieved into temp DB then filtering occur. There are many threads about this. It is better to use open OPENQUERY because it passes SQL to the source linked server and then it return filtered results e.g.

SELECT *
FROM OPENQUERY(Linked_Server_Name , 'select * from TableName where ID = 500')

Iterating over and deleting from Hashtable in Java

You need to use an explicit java.util.Iterator to iterate over the Map's entry set rather than being able to use the enhanced For-loop syntax available in Java 6. The following example iterates over a Map of Integer, String pairs, removing any entry whose Integer key is null or equals 0.

Map<Integer, String> map = ...

Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();

while (it.hasNext()) {
  Map.Entry<Integer, String> entry = it.next();

  // Remove entry if key is null or equals 0.
  if (entry.getKey() == null || entry.getKey() == 0) {
    it.remove();
  }
}

Deploying just HTML, CSS webpage to Tomcat

There is no real need to create a war to run it from Tomcat. You can follow these steps

  1. Create a folder in webapps folder e.g. MyApp

  2. Put your html and css in that folder and name the html file, which you want to be the starting page for your application, index.html

  3. Start tomcat and point your browser to url "http://localhost:8080/MyApp". Your index.html page will pop up in the browser

Convert an int to ASCII character

This will only work for int-digits 0-9, but your question seems to suggest that might be enough.

It works by adding the ASCII value of char '0' to the integer digit.

int i=6;
char c = '0'+i;  // now c is '6'

For example:

'0'+0 = '0'
'0'+1 = '1'
'0'+2 = '2'
'0'+3 = '3'

Edit

It is unclear what you mean, "work for alphabets"? If you want the 5th letter of the alphabet:

int i=5;
char c = 'A'-1 + i; // c is now 'E', the 5th letter.

Note that because in C/Ascii, A is considered the 0th letter of the alphabet, I do a minus-1 to compensate for the normally understood meaning of 5th letter.

Adjust as appropriate for your specific situation.
(and test-test-test! any code you write)

How to make ng-repeat filter out duplicate results

Create your own array.

<select name="cmpPro" ng-model="test3.Product" ng-options="q for q in productArray track by q">
    <option value="" >Plans</option>
</select>

 productArray =[];
angular.forEach($scope.leadDetail, function(value,key){
    var index = $scope.productArray.indexOf(value.Product);
    if(index === -1)
    {
        $scope.productArray.push(value.Product);
    }
});

ArrayList or List declaration in Java

Basically it allows Java to store several types of objects in one structure implementation, by generic type declaration (like class MyStructure<T extends TT>), which is one of Javas main features.

Object-oriented approaches are based in modularity and reusability by separation of concerns - the ability to use a structure with any kind of types of object (as long as it obeys a few rules).

You could just instantiate things as followed:

ArrayList list = new ArrayList();

instead of

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

By declaring and using generic types you are informing a structure of the kind of objects it will manage and the compiler will be able to inform you if you're inserting an illegal type into that structure, for instance. Let's say:

// this works
List list1 = new ArrayList();
list1.add(1);
list1.add("one");

// does not work
List<String> list2 = new ArrayList<>();
list2.add(1); // compiler error here
list2.add("one");

If you want to see some examples check the documentation documentation:

/**
 * Generic version of the Box class.
 * @param <T> the type of the value being boxed
 */
public class Box<T> {
    // T stands for "Type"
    private T t;

    public void set(T t) { this.t = t; }
    public T get() { return t; }
}

Then you could instantiate things like:

class Paper  { ... }
class Tissue { ... }

// ...
Box<Paper> boxOfPaper = new Box<>();
boxOfPaper.set(new Paper(...));

Box<Tissue> boxOfTissues = new Box<>();
boxOfTissues.set(new Tissue(...));

The main thing to draw from this is you're specifying which type of object you want to box.

As for using Object l = new ArrayList<>();, you're not accessing the List or ArrayList implementation so you won't be able to do much with the collection.

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

The problem is with percentage sizing. You are not defining the size of the parent div (the new one), so the browser can not report the size to the Google Maps API. Giving the wrapper div a specific size, or a percentage size if the size of its parent can be determined, will work.

See this explanation from Mike Williams' Google Maps API v2 tutorial:

If you try to use style="width:100%;height:100%" on your map div, you get a map div that has zero height. That's because the div tries to be a percentage of the size of the <body>, but by default the <body> has an indeterminate height.

There are ways to determine the height of the screen and use that number of pixels as the height of the map div, but a simple alternative is to change the <body> so that its height is 100% of the page. We can do this by applying style="height:100%" to both the <body> and the <html>. (We have to do it to both, otherwise the <body> tries to be 100% of the height of the document, and the default for that is an indeterminate height.)

Add the 100% size to html and body in your css

    html, body, #map-canvas {
        margin: 0;
        padding: 0;
        height: 100%;
        width: 100%;
    }

Add it inline to any divs that don't have an id:

<body>
  <div style="height:100%; width: 100%;"> 
    <div id="map-canvas"></div>
  </div>
</body>

C++ terminate called without an active exception

How to reproduce that error:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <thread>
using namespace std;
void task1(std::string msg){
  cout << "task1 says: " << msg;
}
int main() { 
  std::thread t1(task1, "hello"); 
  return 0;
}

Compile and run:

el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
terminate called without an active exception
Aborted (core dumped)

You get that error because you didn't join or detach your thread.

One way to fix it, join the thread like this:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <thread>
using namespace std;
void task1(std::string msg){
  cout << "task1 says: " << msg;
}
int main() { 
  std::thread t1(task1, "hello"); 
  t1.join();
  return 0;
}

Then compile and run:

el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
task1 says: hello

The other way to fix it, detach it like this:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <thread>
using namespace std;
void task1(std::string msg){
  cout << "task1 says: " << msg;
}
int main() 
{ 
     {

        std::thread t1(task1, "hello"); 
        t1.detach();

     } //thread handle is destroyed here, as goes out of scope!

     usleep(1000000); //wait so that hello can be printed.
}

Compile and run:

el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
task1 says: hello

Read up on detaching C++ threads and joining C++ threads.

How to get the latest record in each group using GROUP BY?

You need to order them.

SELECT * FROM messages GROUP BY from_id ORDER BY timestamp DESC LIMIT 1

jQuery Select first and second td

$(".location table tbody tr td:first-child").addClass("black");
$(".location table tbody tr td:nth-child(2)").addClass("black");

http://jsfiddle.net/68wbx/1/

SQL to add column and comment in table in single command

No, you can't.

There's no reason why you would need to. This is a one-time operation and so takes only an additional second or two to actually type and execute.

If you're adding columns in your web application this is more indicative of a flaw in your data-model as you shouldn't need to be doing it.


In response to your comment that a comment is a column attribute; it may seem so but behind the scenes Oracle stores this as an attribute of an object.

SQL> desc sys.com$
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 OBJ#                                      NOT NULL NUMBER
 COL#                                               NUMBER
 COMMENT$                                           VARCHAR2(4000)

SQL>

The column is optional and sys.col$ does not contain comment information.

I assume, I have no knowledge, that this was done in order to only have one system of dealing with comments rather than multiple.

read string from .resx file in C#

This works for me. say you have a strings.resx file with string ok in it. to read it

String varOk = My.Resources.strings.ok

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

Use:

string json = "{\r\n \"LOINC_NUM\": \"10362-2\",\r\n}";
var result = JObject.Parse(json.Replace(System.Environment.NewLine, string.Empty));

Best way to check if an PowerShell Object exist?

What all of these answers do not highlight is that when comparing a value to $null, you have to put $null on the left-hand side, otherwise you may get into trouble when comparing with a collection-type value. See: https://github.com/nightroman/PowerShellTraps/blob/master/Basic/Comparison-operators-with-collections/looks-like-object-is-null.ps1

$value = @(1, $null, 2, $null)
if ($value -eq $null) {
    Write-Host "$value is $null"
}

The above block is (unfortunately) executed. What's even more interesting is that in Powershell a $value can be both $null and not $null:

$value = @(1, $null, 2, $null)
if (($value -eq $null) -and ($value -ne $null)) {
    Write-Host "$value is both $null and not $null"
}

So it is important to put $null on the left-hand side to make these comparisons work with collections:

$value = @(1, $null, 2, $null)
if (($null -eq $value) -and ($null -ne $value)) {
    Write-Host "$value is both $null and not $null"
}

I guess this shows yet again the power of Powershell !

How to change string into QString?

std::string s = "Sambuca";
QString q = s.c_str();

Warning: This won't work if the std::string contains \0s.

Javascript use variable as object name

I think Shaz's answer for local variables is hard to understand, though it works for non-recursive functions. Here's another way that I think it's clearer (but it's still his idea, exact same behavior). It's also not accessing the local variables dynamically, just the property of the local variable.

Essentially, it's using a global variable (attached to the function object)

// Here's  a version of it that is more straight forward.
function doIt() {
    doIt.objname = {};
    var someObject = "objname";
    doIt[someObject].value = "value";    
    console.log(doIt.objname);
})();

Which is essentially the same thing as creating a global to store the variable, so you can access it as a property. Creating a global to do this is such a hack.

Here's a cleaner hack that doesn't create global variables, it uses a local variable instead.

function doIt() {
  var scope = {
     MyProp: "Hello"
  };
  var name = "MyProp";
  console.log(scope[name]);
}

See Javascript: interpret string as object reference?

Python convert object to float

  • You can use pandas.Series.astype
  • You can do something like this :

    weather["Temp"] = weather.Temp.astype(float)
    
  • You can also use pd.to_numeric that will convert the column from object to float

  • For details on how to use it checkout this link :http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.to_numeric.html
  • Example :

    s = pd.Series(['apple', '1.0', '2', -3])
    print(pd.to_numeric(s, errors='ignore'))
    print("=========================")
    print(pd.to_numeric(s, errors='coerce'))
    
  • Output:

    0    apple
    1      1.0
    2        2
    3       -3
    =========================
    dtype: object
    0    NaN
    1    1.0
    2    2.0
    3   -3.0
    dtype: float64
    
  • In your case you can do something like this:

    weather["Temp"] = pd.to_numeric(weather.Temp, errors='coerce')
    
  • Other option is to use convert_objects
  • Example is as follows

    >> pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
    
    0     1
    1     2
    2     3
    3     4
    4   NaN
    dtype: float64
    
  • You can use this as follows:

    weather["Temp"] = weather.Temp.convert_objects(convert_numeric=True)
    
  • I have showed you examples because if any of your column won't have a number then it will be converted to NaN... so be careful while using it.

Find length (size) of an array in jquery

If length is undefined you can use:

function count(array){

    var c = 0;
    for(i in array) // in returns key, not object
        if(array[i] != undefined)
            c++;

    return c;
}

var total = count(array);

Creating a file only if it doesn't exist in Node.js

What about using the a option?

According to the docs:

'a+' - Open file for reading and appending. The file is created if it does not exist.

It seems to work perfectly with createWriteStream

For Restful API, can GET method use json data?

To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode). However, considering your reason for doing this is due to the length of the URI, using JSON will be self-defeating (introducing more characters than required).

I suggest you send your parameters in body of a POST request, either in regular CGI style (param1=val1&param2=val2) or JSON (parsed by your API upon receipt)

PYODBC--Data source name not found and no default driver specified

I have had the same error on python3 and this help me:

conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};'
                      'SERVER=YourServerName;'
                      'DATABASE=YourDatabaseName;UID=USER_NAME;PWD=PASS_WORD;')

remember python is case-sensitive so you have to mention DRIVER,SERVER,... in upper case. and you can visit this link for more information:

https://docs.microsoft.com/en-us/sql/connect/python/pyodbc/step-3-proof-of-concept-connecting-to-sql-using-pyodbc?view=sql-server-ver15

Drop shadow on a div container?

You can try using the PNG drop shadows. IE6 doesn't support it, however it will degrade nicely.

http://www.positioniseverything.net/articles/dropshadows.html

Code not running in IE 11, works fine in Chrome

If this is happening in Angular 2+ application, you can just uncomment string polyfills in polyfills.ts:

import 'core-js/es6/string';

Why aren't python nested functions called closures?

People are confusing about what closure is. Closure is not the inner function. the meaning of closure is act of closing. So inner function is closing over a nonlocal variable which is called free variable.

def counter_in(initial_value=0):
    # initial_value is the free variable
    def inc(increment=1):
        nonlocal initial_value
        initial_value += increment
        return print(initial_value)
    return inc

when you call counter_in() this will return inc function which has a free variable initial_value. So we created a CLOSURE. people call inc as closure function and I think this is confusing people, people think "ok inner functions are closures". in reality inc is not a closure, since it is part of the closure, to make life easy, they call it closure function.

  myClosingOverFunc=counter_in(2)

this returns inc function which is closing over the free variable initial_value. when you invoke myClosingOverFunc

 myClosingOverFunc() 

it will print 2.

when python sees that a closure sytem exists, it creates a new obj called CELL. this will store only the name of the free variable which is initial_value in this case. This Cell obj will point to another object which stores the value of the initial_value.

in our example, initial_value in outer function and inner function will point to this cell object, and this cell object will be point to the value of the initial_value.

  variable initial_value =====>> CELL ==========>> value of initial_value

So when you call counter_in its scope is gone, but it does not matter. because variable initial_value is directly referencing the CELL Obj. and it indirectly references the value of initial_value. That is why even though scope of outer function is gone, inner function will still have access to the free variable

let's say I want to write a function, which takes in a function as an arg and returns how many times this function is called.

def counter(fn):
    # since cnt is a free var, python will create a cell and this cell will point to the value of cnt
    # every time cnt changes, cell will be pointing to the new value
    cnt = 0

    def inner(*args, **kwargs):
        # we cannot modidy cnt with out nonlocal
        nonlocal cnt
        cnt += 1
        print(f'{fn.__name__} has been called {cnt} times')
        # we are calling fn indirectly via the closue inner
        return fn(*args, **kwargs)
    return inner
      

in this example cnt is our free variable and inner + cnt create CLOSURE. when python sees this it will create a CELL Obj and cnt will always directly reference this cell obj and CELL will reference the another obj in the memory which stores the value of cnt. initially cnt=0.

 cnt   ======>>>>  CELL  =============>  0

when you invoke the inner function wih passing a parameter counter(myFunc)() this will increase the cnt by 1. so our referencing schema will change as follow:

 cnt   ======>>>>  CELL  =============>  1  #first counter(myFunc)()
 cnt   ======>>>>  CELL  =============>  2  #second counter(myFunc)()
 cnt   ======>>>>  CELL  =============>  3  #third counter(myFunc)()

this is only one instance of closure. You can create multiple instances of closure with passing another function

counter(differentFunc)()

this will create a different CELL obj from the above. We just have created another closure instance.

 cnt  ======>>  difCELL  ========>  1  #first counter(differentFunc)()
 cnt  ======>>  difCELL  ========>  2  #secon counter(differentFunc)()
 cnt  ======>>  difCELL  ========>  3  #third counter(differentFunc)()


  

How to pass the values from one jsp page to another jsp without submit button?

You can try this way also,

Html:

<form action="javascript:next()" method="post">
<input type="submit" value=Submit /></form>

Javascript:

      function next(){
        //Location where you want to forward your values
        window.location.href = "http://localhost:8563/And/try1.jsp?dymanicValue=" + values; 
        }

Merge two rows in SQL

SELECT Q.FK
      ,ISNULL(T1.Field1, T2.Field2) AS Field
FROM (SELECT FK FROM Table1
        UNION
      SELECT FK FROM Table2) AS Q
LEFT JOIN Table1 AS T1 ON T1.FK = Q.FK
LEFT JOIN Table2 AS T2 ON T2.FK = Q.FK

If there is one table, write Table1 instead of Table2

Raise an error manually in T-SQL to jump to BEGIN CATCH block

THROW (Transact-SQL)

Raises an exception and transfers execution to a CATCH block of a TRY…CATCH construct in SQL Server 2017.

Please refer the below link

T-SQL Throw Exception

HTML table needs spacing between columns, not rows

If you can use inline styling, you can set the left and right padding on each td.. Or you use an extra td between columns and set a number of non-breaking spaces as @rene kindly suggested.

http://jsfiddle.net/u5mN4/

http://jsfiddle.net/u5mN4/1/

Both are pretty ugly ;p css ftw

How can you integrate a custom file browser/uploader with CKEditor?

Start by registering your custom browser/uploader when you instantiate CKEditor. You can designate different URLs for an image browser vs. a general file browser.

<script type="text/javascript">
CKEDITOR.replace('content', {
    filebrowserBrowseUrl : '/browser/browse/type/all',
    filebrowserUploadUrl : '/browser/upload/type/all',
    filebrowserImageBrowseUrl : '/browser/browse/type/image',
filebrowserImageUploadUrl : '/browser/upload/type/image',
    filebrowserWindowWidth  : 800,
    filebrowserWindowHeight : 500
});
</script>

Your custom code will receive a GET parameter called CKEditorFuncNum. Save it - that's your callback function. Let's say you put it into $callback.

When someone selects a file, run this JavaScript to inform CKEditor which file was selected:

window.opener.CKEDITOR.tools.callFunction(<?php echo $callback; ?>,url)

Where "url" is the URL of the file they picked. An optional third parameter can be text that you want displayed in a standard alert dialog, such as "illegal file" or something. Set url to an empty string if the third parameter is an error message.

CKEditor's "upload" tab will submit a file in the field "upload" - in PHP, that goes to $_FILES['upload']. What CKEditor wants your server to output is a complete JavaScript block:

$output = '<html><body><script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$callback.', "'.$url.'","'.$msg.'");</script></body></html>';
echo $output;

Again, you need to give it that callback parameter, the URL of the file, and optionally a message. If the message is an empty string, nothing will display; if the message is an error, then url should be an empty string.

The official CKEditor documentation is incomplete on all this, but if you follow the above it'll work like a champ.

What is a callback in java

Callbacks are most easily described in terms of the telephone system. A function call is analogous to calling someone on a telephone, asking her a question, getting an answer, and hanging up; adding a callback changes the analogy so that after asking her a question, you also give her your name and number so she can call you back with the answer.

Paul Jakubik, Callback Implementations in C++.

Mock HttpContext.Current in Test Init Method

HttpContext.Current returns an instance of System.Web.HttpContext, which does not extend System.Web.HttpContextBase. HttpContextBase was added later to address HttpContext being difficult to mock. The two classes are basically unrelated (HttpContextWrapper is used as an adapter between them).

Fortunately, HttpContext itself is fakeable just enough for you do replace the IPrincipal (User) and IIdentity.

The following code runs as expected, even in a console application:

HttpContext.Current = new HttpContext(
    new HttpRequest("", "http://tempuri.org", ""),
    new HttpResponse(new StringWriter())
    );

// User is logged in
HttpContext.Current.User = new GenericPrincipal(
    new GenericIdentity("username"),
    new string[0]
    );

// User is logged out
HttpContext.Current.User = new GenericPrincipal(
    new GenericIdentity(String.Empty),
    new string[0]
    );

Evaluate a string with a switch in C++

You can only use switch-case on types castable to an int.

You could, however, define a std::map<std::string, std::function> dispatcher and use it like dispatcher[str]() to achieve same effect.

working with negative numbers in python

How about something like that? (Uses no abs() nor mulitiplication)
Notes:

  • the abs() function is only used for the optimization trick. This snippet can either be removed or recoded.
  • the logic is less efficient since we're testing the sign of a and b with each iteration (price to pay to avoid both abs() and multiplication operator)

def multiply_by_addition(a, b):
""" School exercise: multiplies integers a and b, by successive additions.
"""
   if abs(a) > abs(b):
      a, b = b, a     # optimize by reducing number of iterations
   total = 0
   while a != 0:
      if a > 0:
         a -= 1
         total += b
      else:
         a += 1
         total -= b
   return total

multiply_by_addition(2,3)
6
multiply_by_addition(4,3)
12
multiply_by_addition(-4,3)
-12
multiply_by_addition(4,-3)
-12
multiply_by_addition(-4,-3)
12

Change Bootstrap tooltip color

This easy method works for me when i want to change the background color of the bootstrap tooltips:

_x000D_
_x000D_
$(function(){
    //$('.tooltips.red-tooltip').tooltip().data('bs.tooltip').tip().addClass('red-tooltip');
    $('.tooltips.red-tooltip').tooltip().data('tooltip').tip().addClass('red-tooltip');
});
_x000D_
.red-tooltip.tooltip.tooltip.bottom .tooltip-arrow, 
.red-tooltip.tooltip.tooltip.bottom-left .tooltip-arrow,
.red-tooltip.tooltip.tooltip.bottom-right .tooltip-arrow{border-bottom-color: red;}
.red-tooltip.tooltip.top .tooltip-arrow {border-top-color: red;}
.red-tooltip.tooltip.left .tooltip-arrow {border-left-color: red;}
.red-tooltip.tooltip.right .tooltip-arrow {border-right-color: red;}
.red-tooltip.tooltip > .tooltip-inner{background-color:red;}
_x000D_
<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://getbootstrap.com/2.3.2/assets/js/bootstrap-tooltip.js"></script>

<a href="#" data-toggle="tooltip" data-placement="bottom"
   title="" data-original-title="Made by @Ram"
   class="tooltips red-tooltip">My link with red tooltip</a>
_x000D_
_x000D_
_x000D_

Note A:

If js code include .data('tooltip') not working for you then please comment its line and uncomment js code include .data('bs-tooltip').

Note B:

If your bootstrap tooltip function add a tooltip to the end of body (not right after the element), my solution works well yet but some other answers in this pages did not works like @Praveen Kumar and @technoTarek in this scenario.

Note C:

This codes support tooltip arrow color in all placements of the tooltip (top,bottom,left,right).

Relationship between hashCode and equals method in Java

According to the doc, the default implementation of hashCode will return some integer that differ for every object

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation
technique is not required by the JavaTM programming language.)

However some time you want the hash code to be the same for different object that have the same meaning. For example

Student s1 = new Student("John", 18);
Student s2 = new Student("John", 18);
s1.hashCode() != s2.hashCode(); // With the default implementation of hashCode

This kind of problem will be occur if you use a hash data structure in the collection framework such as HashTable, HashSet. Especially with collection such as HashSet you will end up having duplicate element and violate the Set contract.

How to convert characters to HTML entities using plain JavaScript

Just reposting @bucababy's answer as a "bookmarklet", as it's sometimes easier than using those lookup pages:

alert(prompt('Enter characters to htmlEncode', '').replace(/[\u00A0-\u2666]/g, function(c) {
   return '&#'+c.charCodeAt(0)+';';
}));

How to change colors of a Drawable in Android?

There are so many solution but nobody suggested if the color resource xml file already have color then we can pick directly from there also as below:

ImageView imageView = (ImageView) findViewById(R.id.imageview);
imageView.setColorFilter(getString(R.color.your_color));

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

For whatever reason $('.panel-collapse').collapse({'toggle': true, 'parent': '#accordion'}); only seems to work the first time and it only works to expand the collapsible. (I tried to start with a expanded collapsible and it wouldn't collapse.)

It could just be something that runs once the first time you initialize collapse with those parameters.

You will have more luck using the show and hide methods.

Here is an example:

$(function() {

  var $active = true;

  $('.panel-title > a').click(function(e) {
    e.preventDefault();
  });

  $('.collapse-init').on('click', function() {
    if(!$active) {
      $active = true;
      $('.panel-title > a').attr('data-toggle', 'collapse');
      $('.panel-collapse').collapse('hide');
      $(this).html('Click to disable accordion behavior');
    } else {
      $active = false;
      $('.panel-collapse').collapse('show');
      $('.panel-title > a').attr('data-toggle','');
      $(this).html('Click to enable accordion behavior');
    }
  });

});

http://bootply.com/98201

Update

Granted KyleMit seems to have a way better handle on this then me. I'm impressed with his answer and understanding.

I don't understand what's going on or why the show seemed to be toggling in some places.

But After messing around for a while.. Finally came with the following solution:

$(function() {
  var transition = false;
  var $active = true;

  $('.panel-title > a').click(function(e) {
    e.preventDefault();
  });

  $('#accordion').on('show.bs.collapse',function(){
    if($active){
        $('#accordion .in').collapse('hide');
    }
  });

  $('#accordion').on('hidden.bs.collapse',function(){
    if(transition){
        transition = false;
        $('.panel-collapse').collapse('show');
    }
  });

  $('.collapse-init').on('click', function() {
    $('.collapse-init').prop('disabled','true');
    if(!$active) {
      $active = true;
      $('.panel-title > a').attr('data-toggle', 'collapse');
      $('.panel-collapse').collapse('hide');
      $(this).html('Click to disable accordion behavior');
    } else {
      $active = false;
      if($('.panel-collapse.in').length){
        transition = true;
        $('.panel-collapse.in').collapse('hide');       
      }
      else{
        $('.panel-collapse').collapse('show');
      }
      $('.panel-title > a').attr('data-toggle','');
      $(this).html('Click to enable accordion behavior');
    }
    setTimeout(function(){
        $('.collapse-init').prop('disabled','');
    },800);
  });
});

http://bootply.com/98239

Redirect all output to file in Bash

All POSIX operating systems have 3 streams: stdin, stdout, and stderr. stdin is the input, which can accept the stdout or stderr. stdout is the primary output, which is redirected with >, >>, or |. stderr is the error output, which is handled separately so that any exceptions do not get passed to a command or written to a file that it might break; normally, this is sent to a log of some kind, or dumped directly, even when the stdout is redirected. To redirect both to the same place, use:

command &> /some/file

EDIT: thanks to Zack for pointing out that the above solution is not portable--use instead:

*command* > file 2>&1 

If you want to silence the error, do:

*command* 2> /dev/null

What should be in my .gitignore for an Android Studio project?

This is created using the reference of http://gitignore.io/ Where you can create the latest updated gitignore file for any project. For Android http://gitignore.io/api/androidstudio. Hope this helps. Currently I am using Android Studio 3.6.3

# Created by https://www.gitignore.io/api/androidstudio
# Edit at https://www.gitignore.io/?templates=androidstudio

### AndroidStudio ###
# Covers files to be ignored for android development using Android Studio.

# Built application files
*.apk
*.ap_

# Files for the ART/Dalvik VM
*.dex

# Java class files
*.class

# Generated files
bin/
gen/
out/

# Gradle files
.gradle
.gradle/
build/

# Signing files
.signing/

# Local configuration file (sdk path, etc)
local.properties

# Proguard folder generated by Eclipse
proguard/

# Log Files
*.log

# Android Studio
/*/build/
/*/local.properties
/*/out
/*/*/build
/*/*/production
captures/
.navigation/
*.ipr
*~
*.swp

# Android Patch
gen-external-apklibs

# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild

# NDK
obj/

# IntelliJ IDEA
*.iml
*.iws
/out/

# User-specific configurations
.idea/caches/
.idea/libraries/
.idea/shelf/
.idea/workspace.xml
.idea/tasks.xml
.idea/.name
.idea/compiler.xml
.idea/copyright/profiles_settings.xml
.idea/encodings.xml
.idea/misc.xml
.idea/modules.xml
.idea/scopes/scope_settings.xml
.idea/dictionaries
.idea/vcs.xml
.idea/jsLibraryMappings.xml
.idea/datasources.xml
.idea/dataSources.ids
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml
.idea/assetWizardSettings.xml

# OS-specific files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db

# Legacy Eclipse project files
.classpath
.project
.cproject
.settings/

# Mobile Tools for Java (J2ME)
.mtj.tmp/

# Package Files #
*.war
*.ear

# virtual machine crash logs (Reference: http://www.java.com/en/download/help/error_hotspot.xml)
hs_err_pid*

## Plugin-specific files:

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Mongo Explorer plugin
.idea/mongoSettings.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

### AndroidStudio Patch ###

!/gradle/wrapper/gradle-wrapper.jar

# End of https://www.gitignore.io/api/androidstudio

remove all special characters in java

use [\\W+] or "[^a-zA-Z0-9]" as regex to match any special characters and also use String.replaceAll(regex, String) to replace the spl charecter with an empty string. remember as the first arg of String.replaceAll is a regex you have to escape it with a backslash to treat em as a literal charcter.

          String c= "hjdg$h&jk8^i0ssh6";
        Pattern pt = Pattern.compile("[^a-zA-Z0-9]");
        Matcher match= pt.matcher(c);
        while(match.find())
        {
            String s= match.group();
        c=c.replaceAll("\\"+s, "");
        }
        System.out.println(c);

Facebook share link without JavaScript

Adding to @rybo111's solution, here's what a LinkedIn share would be:

<a href="http://www.linkedin.com/shareArticle?mini=true&url={articleUrl}&title={articleTitle}&summary={articleSummary}&source={articleSource}" target="_blank" class="share-popup">Share on LinkedIn</a>

and add this to your Javascript:

case "www.linkedin.com":
    window_size = "width=570,height=494";
    break;

As per the LinkedIn documentation: https://developer.linkedin.com/docs/share-on-linkedin (See "Customized Url" section)

For anyone who's interested, I used this in a Rails app with a LinkedIn logo, so here's my code if it might help:

<%= link_to image_tag('linkedin.png', size: "50x50"), "http://www.linkedin.com/shareArticle?mini=true&url=#{job_url(@job)}&title=#{full_title(@job.title).html_safe}&summary=#{strip_tags(@job.description)}&source=SOURCE_URL", class: "share-popup" %>

PHP - check if variable is undefined

An another way is simply :

if($test){
    echo "Yes 1";
}
if(!is_null($test)){
    echo "Yes 2";
}

$test = "hello";

if($test){
    echo "Yes 3";
}

Will return :

"Yes 3"

The best way is to use isset(), otherwise you can have an error like "undefined $test".

You can do it like this :

if( isset($test) && ($test!==null) )

You'll not have any error because the first condition isn't accepted.

OpenSSL and error in reading openssl.conf file

I just had a similar error using the openssl.exe from the Apache for windows bin folder. I had the -config flag specified by had a typo in the path of the openssl.cnf file. I think you'll find that

openssl req -config C:\OpenSSL\bin\openssl.conf -x509 -days 365 -newkey rsa:1024 -keyout hostkey.pem -nodes -out hostcert.pem

should be

openssl req -config "C:\OpenSSL\bin\openssl.cnf" -x509 -days 365 -newkey rsa:1024 -keyout hostkey.pem -nodes -out hostcert.pem

Note: the conf should probably be cnf.

jquery select element by xpath

First create an xpath selector function.

function _x(STR_XPATH) {
    var xresult = document.evaluate(STR_XPATH, document, null, XPathResult.ANY_TYPE, null);
    var xnodes = [];
    var xres;
    while (xres = xresult.iterateNext()) {
        xnodes.push(xres);
    }

    return xnodes;
}

To use the xpath selector with jquery, you can do like this:

$(_x('/html/.//div[@id="text"]')).attr('id', 'modified-text');

Hope this can help.

Installing ADB on macOS

If you've already installed Android Studio --

Add the following lines to the end of ~/.bashrc or ~/.zshrc (if using Oh My ZSH):

export ANDROID_HOME=/Users/$USER/Library/Android/sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

Restart Terminal and you're good to go.

c#: getter/setter

These are called auto properties.

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

Functionally (and in terms of the compiled IL), they are the same as properties with backing fields.

Python Regex - How to Get Positions and Values of Matches

Taken from

Regular Expression HOWTO

span() returns both start and end indexes in a single tuple. Since the match method only checks if the RE matches at the start of a string, start() will always be zero. However, the search method of RegexObject instances scans through the string, so the match may not start at zero in that case.

>>> p = re.compile('[a-z]+')
>>> print p.match('::: message')
None
>>> m = p.search('::: message') ; print m
<re.MatchObject instance at 80c9650>
>>> m.group()
'message'
>>> m.span()
(4, 11)

Combine that with:

In Python 2.2, the finditer() method is also available, returning a sequence of MatchObject instances as an iterator.

>>> p = re.compile( ... )
>>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
>>> iterator
<callable-iterator object at 0x401833ac>
>>> for match in iterator:
...     print match.span()
...
(0, 2)
(22, 24)
(29, 31)

you should be able to do something on the order of

for match in re.finditer(r'[a-z]', 'a1b2c3d4'):
   print match.span()

How to put a symbol above another in LaTeX?

${a \atop \#}$

or

${a \above 0pt \#}$

How to create a custom exception type in Java?

Since you can just create and throw exceptions it could be as easy as

if ( word.contains(" ") )
{
     throw new RuntimeException ( "Word contains one or more spaces" ) ;
}

If you would like to be more formal, you can create an Exception class

class SpaceyWordException extends RuntimeException
{

}

Either way, if you use RuntimeException, your new Exception will be unchecked.

How to get the size of a string in Python?

The most Pythonic way is to use the len(). Keep in mind that the '\' character in escape sequences is not counted and can be dangerous if not used correctly.

>>> len('foo')
3
>>> len('\foo')
3
>>> len('\xoo')
  File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \xXX escape

Access to the path 'c:\inetpub\wwwroot\myapp\App_Data' is denied

I had a similar situation. I am using TFS for source code control. What I found is that when it was checked in, it made the files readonly. This caused the above error in my service where it was opening them read/write. Once I checked them out for edit. Everything worked great. I am considering trying opening them readonly in the service. I think that once they get published to the production server, this is not an issue. Only in the development environment. I have seen similar issues with Services that use Entity Framework. If the .svc file is checked in, you can't do updates to the database through EF.

Send email by using codeigniter library via localhost

I had the same problem and I solved by using the postcast server. You can install it locally and use it.

How can I display a JavaScript object?

You may use my function .
Call this function with an array or string or an object it alerts the contents.

Function

function print_r(printthis, returnoutput) {
    var output = '';

    if($.isArray(printthis) || typeof(printthis) == 'object') {
        for(var i in printthis) {
            output += i + ' : ' + print_r(printthis[i], true) + '\n';
        }
    }else {
        output += printthis;
    }
    if(returnoutput && returnoutput == true) {
        return output;
    }else {
        alert(output);
    }
}

Usage

var data = [1, 2, 3, 4];
print_r(data);

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

Add onClick event to document.createElement("th")

var newTH = document.createElement('th');
newTH.innerHTML = 'Hello, World!';
newTH.onclick = function () {
    this.parentElement.removeChild(this);
};

var table = document.getElementById('content');
table.appendChild(newTH);

Working example: http://jsfiddle.net/23tBM/

You can also just hide with this.style.display = 'none'.

TypeError: cannot perform reduce with flexible type

When your are trying to apply prod on string type of value like:

['-214' '-153' '-58' ..., '36' '191' '-37']

you will get the error.

Solution: Append only integer value like [1,2,3], and you will get your expected output.

If the value is in string format before appending then, in the array you can convert the type into int type and store it in a list.

@viewChild not working - cannot read property nativeElement of undefined

Sometimes, this error occurs when you're trying to target an element that is wrapped in a condition, for example: <div *ngIf="canShow"> <p #target>Targeted Element</p></div>

In this code, if canShow is false on render, Angular won't be able to get that element as it won't be rendered, hence the error that comes up.

One of the solutions is to use a display: hidden on the element instead of the *ngIf so the element gets rendered but is hidden until your condition is fulfilled.

Read More over at Github

Setting Oracle 11g Session Timeout

Does the DB know the connection has dropped, or is the session still listed in v$session? That would indicate, I think, that it's being dropped by the network. Do you know how long it can stay idle before encountering the problem, and if that bears any resemblance to the TCP idle values (net.ipv4.tcp_keepalive_time, tcp_keepalive_probes and tcp_keepalive_interval from sysctl if I recall correctly)? Can't remember whether sysctl changes persist by default, but that might be something that was modified and then reset by the reboot.

Also you might be able to reset your JDBC connections without bouncing the whole server; certainly can in WebLogic, which I realise doesn't help much, but I'm not familiar with the Tomcat equivalents.

Splitting on last delimiter in Python string?

You can use rsplit

string.rsplit('delimeter',1)[1]

To get the string from reverse.

how to download image from any web page in java

(throws IOException)

Image image = null;
try {
    URL url = new URL("http://www.yahoo.com/image_to_read.jpg");
    image = ImageIO.read(url);
} catch (IOException e) {
}

See javax.imageio package for more info. That's using the AWT image. Otherwise you could do:

 URL url = new URL("http://www.yahoo.com/image_to_read.jpg");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
   out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();

And you may then want to save the image so do:

FileOutputStream fos = new FileOutputStream("C://borrowed_image.jpg");
fos.write(response);
fos.close();

Getting Gradle dependencies in IntelliJ IDEA using Gradle build

When importing an existing Gradle project (one with a build.gradle) into IntelliJ IDEA, when presented with the following screen, select Import from external model -> Gradle.

Import project from external model

Optionally, select Auto Import on the next screen to automatically import new dependencies.

How to find the php.ini file used by the command line?

Save CLI phpinfo output into local file:

php -i >> phpinfo-cli.txt

How do I find which rpm package supplies a file I'm looking for?

You can do this alike here but with your package. In my case, it was lsb_release

Run: yum whatprovides lsb_release

Response:

redhat-lsb-core-4.1-24.el7.i686 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release

redhat-lsb-core-4.1-24.el7.x86_64 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release

redhat-lsb-core-4.1-27.el7.i686 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release

redhat-lsb-core-4.1-27.el7.x86_64 : LSB Core module support
Repo        : rhel-7-server-rpms
Matched from:
Filename    : /usr/bin/lsb_release`

Run to install: yum install redhat-lsb-core

The package name SHOULD be without number and system type so yum packager can choose what is best for him.

Visual Studio 2015 installer hangs during install?

This issue is becoming very now, specially for users installing visual studio on windows 10 platform. What Microsoft suggests is disable your anti virus and anti malware programs and always run setup with admin permission.

But in my case I have to do lot more things to get rid of this issue: 1. Disabled AVG realtime protaction 2. Disabled AVG from task manager 3. Remove all the files and folders from system temp folder. (You can open it by typing %temp% and hit enter in run prompt) 4. Run setup again as admin

Here is a complete list of incidents that I faced in this issue (visual studio 2015 installation got stuck)

And how I resolved it

How to grep for contents after pattern?

grep -Po 'potato:\s\K.*' file

-P to use Perl regular expression

-o to output only the match

\s to match the space after potato:

\K to omit the match

.* to match rest of the string(s)

How can I share Jupyter notebooks with non-programmers?

It depends on what you are intending to do with your Notebook: do you want that the user can recompute the results or just playing with them?

Static notebook

NBViewer is a great tool. You can directly use it inside Jupyter. Github has also a render, so you can directly link your file (such as https://github.com/my-name/my-repo/blob/master/mynotebook.ipynb)

Alive notebook

If you want your user to be able to recompute some parts, you can also use MyBinder. It takes some time to start your notebook, but the result is worth it.

As said by @Mapl, Google can host your notebook with Colab. A nice feature is to compute your cells over a GPU.

Datetime BETWEEN statement not working in SQL Server

Do you have times associated with your dates? BETWEEN is inclusive, but when you convert 2013-10-18 to a date it becomes 2013-10-18 00:00:000.00. Anything that is logged after the first second of the 18th will not shown using BETWEEN, unless you include a time value.

Try:

SELECT * FROM LOGS WHERE CHECK_IN BETWEEN CONVERT(datetime,'2013-10-17') AND CONVERT(datetime,'2013-10-18 23:59:59:999')

if you want to search the entire day of the 18th.

SQL DATETIME fields have milliseconds. So I added 999 to the field.

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

Android: Bitmaps loaded from gallery are rotated in ImageView

Got it to work after many attempts thanks to a post I can no longer find :-(

Exif seems to work always, the difficulty was to get the filepath. The code I found makes a different between API older than 4.4 and after 4.4. Basically the picture URI for 4.4+ contains "com.android.providers". For this type of URI, the code uses DocumentsContract to get the picture id and then runs a query using the ContentResolver, while for older SDK, the code goes straight to query the URI with the ContentResolver.

Here is the code (sorry I cannot credit who posted it):

/**
 * Handles pre V19 uri's
 * @param context
 * @param contentUri
 * @return
 */
public static String getPathForPreV19(Context context, Uri contentUri) {
    String res = null;

    String[] proj = { MediaStore.Images.Media.DATA };
    Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
    if(cursor.moveToFirst()){;
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        res = cursor.getString(column_index);
    }
    cursor.close();

    return res;
}

/**
 * Handles V19 and up uri's
 * @param context
 * @param contentUri
 * @return path
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getPathForV19AndUp(Context context, Uri contentUri) {
    String wholeID = DocumentsContract.getDocumentId(contentUri);

    // Split at colon, use second item in the array
    String id = wholeID.split(":")[1];
    String[] column = { MediaStore.Images.Media.DATA };

    // where id is equal to
    String sel = MediaStore.Images.Media._ID + "=?";
    Cursor cursor = context.getContentResolver().
            query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    column, sel, new String[]{ id }, null);

    String filePath = "";
    int columnIndex = cursor.getColumnIndex(column[0]);
    if (cursor.moveToFirst()) {
        filePath = cursor.getString(columnIndex);
    }

    cursor.close();
    return filePath;
}

public static String getRealPathFromURI(Context context,
        Uri contentUri) {
    String uriString = String.valueOf(contentUri);
    boolean goForKitKat= uriString.contains("com.android.providers");

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && goForKitKat) {
            Log.i("KIKAT","YES");
            return getPathForV19AndUp(context, contentUri);
        } else {

            return getPathForPreV19(context, contentUri);
        }
}

Htaccess: add/remove trailing slash from URL

This is what I've used for my latest app.

# redirect the main page to landing
##RedirectMatch 302 ^/$ /landing

# remove php ext from url
# https://stackoverflow.com/questions/4026021/remove-php-extension-with-htaccess
RewriteEngine on 

# File exists but has a trailing slash
# https://stackoverflow.com/questions/21417263/htaccess-add-remove-trailing-slash-from-url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?(.*)/+$ /$1 [R=302,L,QSA]

# ok. It will still find the file but relative assets won't load
# e.g. page: /landing/  -> assets/js/main.js/main
# that's we have the rules above.
RewriteCond %{REQUEST_FILENAME} !\.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^/?(.*?)/?$ $1.php

How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?

For everyone asking for code in C#, below is a simplified version of my implementation.

public static void TakeScreenshot(IWebDriver driver, IWebElement element)
{
    try
    {
        string fileName = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".jpg";
        Byte[] byteArray = ((ITakesScreenshot)driver).GetScreenshot().AsByteArray;
        System.Drawing.Bitmap screenshot = new System.Drawing.Bitmap(new System.IO.MemoryStream(byteArray));
        System.Drawing.Rectangle croppedImage = new System.Drawing.Rectangle(element.Location.X, element.Location.Y, element.Size.Width, element.Size.Height);
        screenshot = screenshot.Clone(croppedImage, screenshot.PixelFormat);
        screenshot.Save(String.Format(@"C:\SeleniumScreenshots\" + fileName, System.Drawing.Imaging.ImageFormat.Jpeg));
    }
    catch (Exception e)
    {
        logger.Error(e.StackTrace + ' ' + e.Message);
    }
}

Setting custom UITableViewCells height

To have the dynamic cell height as the text of Label increases, you first need to calculate height,that the text gonna use in -heightForRowAtIndexPath delegate method and return it with the added heights of other lables,images (max height of text+height of other static componenets) and use same height in cell creation.

#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 300.0f  
#define CELL_CONTENT_MARGIN 10.0f

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{

    if (indexPath.row == 2) {  // the cell you want to be dynamic

        NSString *text = dynamic text for your label;

        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

        CGFloat height = MAX(size.height, 44.0f);

        return height + (CELL_CONTENT_MARGIN * 2);
    }
    else {
        return 44; // return normal cell height
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UILabel *label;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] ;
    }

    label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 280, 34)];

    [label setNumberOfLines:2];

    label.backgroundColor = [UIColor clearColor];

    [label setFont:[UIFont systemFontOfSize:FONT_SIZE]];

    label.adjustsFontSizeToFitWidth = NO;

    [[cell contentView] addSubview:label];


    NSString *text = dynamic text fro your label;

    [label setText:text];

    if (indexPath.row == 2) {// the cell which needs to be dynamic 

        [label setNumberOfLines:0];

        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);

        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

        [label setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];

    }
    return  cell;
}

Extracting text from a PDF file using PDFMiner in python?

This works in May 2020 using PDFminer six in Python3.

Installing the package

$ pip install pdfminer.six

Importing the package

from pdfminer.high_level import extract_text

Using a PDF saved on disk

text = extract_text('report.pdf')

Or alternatively:

with open('report.pdf','rb') as f:
    text = extract_text(f)

Using PDF already in memory

If the PDF is already in memory, for example if retrieved from the web with the requests library, it can be converted to a stream using the io library:

import io

response = requests.get(url)
text = extract_text(io.BytesIO(response.content))

Performance and Reliability compared with PyPDF2

PDFminer.six works more reliably than PyPDF2 (which fails with certain types of PDFs), in particular PDF version 1.7

However, text extraction with PDFminer.six is significantly slower than PyPDF2 by a factor of 6.

I timed text extraction with timeit on a 15" MBP (2018), timing only the extraction function (no file opening etc.) with a 10 page PDF and got the following results:

PDFminer.six: 2.88 sec
PyPDF2:       0.45 sec

pdfminer.six also has a huge footprint, requiring pycryptodome which needs GCC and other things installed pushing a minimal install docker image on Alpine Linux from 80 MB to 350 MB. PyPDF2 has no noticeable storage impact.