Programs & Examples On #Facebook android sdk

The Facebook SDK for Android helps Android app developer implement Facebook functionality into their Android apps. Features include Facebook Login, Friend and Place pickers, session management, native object responses from the Graph API and Feed and Requests dialogs.

How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

Since Facebook's Android SDK v4.0 you need to execute the following:

LoginManager.getInstance().logOut();

This is not sufficient. This will simply clear cached access token and profile so that AccessToken.getCurrentAccessToken() and Profile.getCurrentProfile() will now become null.

To completely logout you need to revoke permissions and then call LoginManager.getInstance().logOut();. To revoke permission execute following graph API -

    GraphRequest delPermRequest = new GraphRequest(AccessToken.getCurrentAccessToken(), "/{user-id}/permissions/", null, HttpMethod.DELETE, new GraphRequest.Callback() {
        @Override
        public void onCompleted(GraphResponse graphResponse) {
            if(graphResponse!=null){
                FacebookRequestError error =graphResponse.getError();
                if(error!=null){
                    Log.e(TAG, error.toString());
                }else {
                    finish();
                }
            }
        }
    });
    Log.d(TAG,"Executing revoke permissions with graph path" + delPermRequest.getGraphPath());
    delPermRequest.executeAsync();

Openssl is not recognized as an internal or external command

Use the entire path, like this:

exportcert -alias androiddebugkey -keystore ~/.android
/debug.keystore | "C:\openssl\bin\openssl.exe" sha1 -binary | "C:\openssl\bin\op
enssl.exe" base64

It worked for me.

Facebook key hash does not match any stored key hashes

Just run command adb logcat | grep hash and look for something like Key hash ABCDEFGH1234= does not match any stored key. Now save this hash on your fb developer console.

using facebook sdk in Android studio

I have used facebook sdk 4.10.0 to integrate login in my android app. Tutorial I followed is :

facebook login android studio

You will be able to get first name, last name, email, gender , facebook id and birth date from facebbok.

Above tutorial also explains how to create app in facebook developer console through video.

add below in build.gradle(Module:app) file:

repositories {
        mavenCentral()
    }

and

 compile 'com.facebook.android:facebook-android-sdk:4.10.0'

now add below in AndroidManifest.xml file :

 <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="your app id from facebook developer console"/>

     <activity android:name="com.facebook.FacebookActivity"
               android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
               android:theme="@android:style/Theme.Translucent.NoTitleBar"
               android:label="@string/app_name" />

add following in activity_main.xml file :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.demonuts.fblogin.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000"
        android:layout_marginLeft="10dp"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/text"/>

    <com.facebook.login.widget.LoginButton
        android:id="@+id/btnfb"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

And in last add below in MainActivity.java file :

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;

import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;


public class MainActivity extends AppCompatActivity {

    private TextView tvdetails;
    private CallbackManager callbackManager;
    private AccessTokenTracker accessTokenTracker;
    private ProfileTracker profileTracker;
    private LoginButton loginButton;
    private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {
                            Log.v("LoginActivity", response.toString());

                            // Application code
                            try {
                                Log.d("tttttt",object.getString("id"));
                                String birthday="";
                                if(object.has("birthday")){
                                    birthday = object.getString("birthday"); // 01/31/1980 format
                                }

                                String fnm = object.getString("first_name");
                                String lnm = object.getString("last_name");
                                String mail = object.getString("email");
                                String gender = object.getString("gender");
                                String fid = object.getString("id");
                                tvdetails.setText(fnm+" "+lnm+" \n"+mail+" \n"+gender+" \n"+fid+" \n"+birthday);

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

                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id, first_name, last_name, email, gender, birthday, location");
            request.setParameters(parameters);
            request.executeAsync();

        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FacebookSdk.sdkInitialize(this);
        setContentView(R.layout.activity_main);

        tvdetails = (TextView) findViewById(R.id.text);

        loginButton = (LoginButton) findViewById(R.id.btnfb);

        callbackManager = CallbackManager.Factory.create();

        accessTokenTracker= new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {

            }
        };

        profileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {

            }
        };

        accessTokenTracker.startTracking();
        profileTracker.startTracking();
        loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday", "user_friends"));
        loginButton.registerCallback(callbackManager, callback);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public void onStop() {
        super.onStop();
        accessTokenTracker.stopTracking();
        profileTracker.stopTracking();
    }

    @Override
    public void onResume() {
        super.onResume();
        Profile profile = Profile.getCurrentProfile();

    }

}

Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User

That's not the right way to set the permissions as you are overwriting them with each method call.

Replace this:

mButtonLogin.setReadPermissions("user_friends");
mButtonLogin.setReadPermissions("public_profile");
mButtonLogin.setReadPermissions("email");
mButtonLogin.setReadPermissions("user_birthday");

With the following, as the method setReadPermissions() accepts an ArrayList:

loginButton.setReadPermissions(Arrays.asList(
        "public_profile", "email", "user_birthday", "user_friends"));

Also here is how to query extra data GraphRequest:

private LoginButton loginButton;
private CallbackManager callbackManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    loginButton = (LoginButton) findViewById(R.id.login_button);

    loginButton.setReadPermissions(Arrays.asList(
            "public_profile", "email", "user_birthday", "user_friends"));

    callbackManager = CallbackManager.Factory.create();

    // Callback registration
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            // App code
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {
                            Log.v("LoginActivity", response.toString());

                            // Application code
                            String email = object.getString("email");
                            String birthday = object.getString("birthday"); // 01/31/1980 format
                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name,email,gender,birthday");
            request.setParameters(parameters);
            request.executeAsync();


        }

        @Override
        public void onCancel() {
            // App code
            Log.v("LoginActivity", "cancel");
        }

        @Override
        public void onError(FacebookException exception) {
            // App code
            Log.v("LoginActivity", exception.getCause().toString());
        }
    });
}

EDIT:

One possible problem is that Facebook assumes that your email is invalid. To test it, use the Graph API Explorer and try to get it. If even there you can't get your email, change it in your profile settings and try again. This approach resolved this issue for some developers commenting my answer.

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

I include definitions for computed columns

    select 'CREATE TABLE [' + so.name + '] (' + o.list + ')' + CASE WHEN tc.Constraint_Name IS NULL THEN '' ELSE 'ALTER TABLE ' + so.Name + ' ADD CONSTRAINT ' + tc.Constraint_Name  + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' END, name
from    sysobjects so
cross apply
    (SELECT

case when comps.definition is not null then '  ['+column_name+'] AS ' + comps.definition 
else
        '  ['+column_name+'] ' + data_type + 
        case
        when data_type like '%text' or data_type in ('image', 'sql_variant' ,'xml')
            then ''
        when data_type in ('float')
            then '(' + cast(coalesce(numeric_precision, 18) as varchar(11)) + ')'
        when data_type in ('datetime2', 'datetimeoffset', 'time')
            then '(' + cast(coalesce(datetime_precision, 7) as varchar(11)) + ')'
        when data_type in ('decimal', 'numeric')
            then '(' + cast(coalesce(numeric_precision, 18) as varchar(11)) + ',' + cast(coalesce(numeric_scale, 0) as varchar(11)) + ')'
        when (data_type like '%binary' or data_type like '%char') and character_maximum_length = -1
            then '(max)'
        when character_maximum_length is not null
            then '(' + cast(character_maximum_length as varchar(11)) + ')'
        else ''
        end + ' ' +
        case when exists ( 
        select id from syscolumns
        where object_name(id)=so.name
        and name=column_name
        and columnproperty(id,name,'IsIdentity') = 1 
        ) then
        'IDENTITY(' + 
        cast(ident_seed(so.name) as varchar) + ',' + 
        cast(ident_incr(so.name) as varchar) + ')'
        else ''
        end + ' ' +
         (case when information_schema.columns.IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' + 
          case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT ELSE '' END 
end + ', ' 

     from information_schema.columns 
     left join sys.computed_columns comps 
     on OBJECT_ID(information_schema.columns.TABLE_NAME)=comps.object_id and information_schema.columns.COLUMN_NAME=comps.name

     where table_name = so.name
     order by ordinal_position
    FOR XML PATH('')) o (list)
left join
    information_schema.table_constraints tc
on  tc.Table_name       = so.Name
AND tc.Constraint_Type  = 'PRIMARY KEY'
cross apply
    (select '[' + Column_Name + '], '
     FROM   information_schema.key_column_usage kcu
     WHERE  kcu.Constraint_Name = tc.Constraint_Name
     ORDER BY
        ORDINAL_POSITION
     FOR XML PATH('')) j (list)
where   xtype = 'U'
AND name    NOT IN ('dtproperties')

How to access shared folder without giving username and password

I found one way to access the shared folder without giving the username and password.

We need to change the share folder protect settings in the machine where the folder has been shared.

Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.

By doing the above settings we can access the shared folder without any username/password.

Access props inside quotes in React JSX

you can use

<img className="image" src=`images/${this.props.image}`>

or

<img className="image" src={'images/'+this.props.image}>

or

  render() {
         let imageUrl = this.props.image ? "images/"+this.props.image : 'some placeholder url image';
    return (
       <div>
          <img className="image" src={imageUrl} />
       </div>
    )
  }

this is error ORA-12154: TNS:could not resolve the connect identifier specified?

run the below command in command prompt

tnsping Datasource

This should give a response like below

C:>tnsping *******

TNS Ping Utility for *** Windows: Version *** - Production on *****

Copyright (c) 1997, 2014, Oracle. All rights reserved.

Used parameter files: c:\oracle*****

Used **** to resolve the alias Attempting to contact (description=(address_list=(address=(protocol=tcp)(host=)(port=)))(connect_data=(server=)(service_name=)(failover_mode=(type=)(method=)(retries=)(delay=))))** OK (**** msec)

Add the text 'Datasource=' in beginning and credentials at the end. the final string should be

Data Source=(description=(address_list=(address=(protocol=tcp)(host=)(port=)))(connect_data=(server=)(service_name=)(failover_mode=(type=)(method=)(retries=)(delay=))));User Id=;Password=;**

Use this as the connection string to connect to oracle db.

What's the difference between Apache's Mesos and Google's Kubernetes

Kubernetes is an open source project that brings 'Google style' cluster management capabilities to the world of virtual machines, or 'on the metal' scenarios. It works very well with modern operating system environments (like CoreOS or Red Hat Atomic) that offer up lightweight computing 'nodes' that are managed for you. It is written in Golang and is lightweight, modular, portable and extensible. We (the Kubernetes team) are working with a number of different technology companies (including Mesosphere who curate the Mesos open source project) to establish Kubernetes as the standard way to interact with computing clusters. The idea is to reproduce the patterns that we see people needing to build cluster applications based on our experience at Google. Some of these concepts include:

  • pods — a way to group containers together
  • replication controllers — a way to handle the lifecycle of containers
  • labels — a way to find and query containers, and
  • services — a set of containers performing a common function.

So with Kubernetes alone you will have something that is simple, easy to get up-and-running, portable and extensible that adds 'cluster' as a noun to the things that you manage in the lightest weight manner possible. Run an application on a cluster, and stop worrying about an individual machine. In this case, cluster is a flexible resource just like a VM. It is a logical computing unit. Turn it up, use it, resize it, turn it down quickly and easily.

With Mesos, there is a fair amount of overlap in terms of the basic vision, but the products are at quite different points in their lifecycle and have different sweet spots. Mesos is a distributed systems kernel that stitches together a lot of different machines into a logical computer. It was born for a world where you own a lot of physical resources to create a big static computing cluster. The great thing about it is that lots of modern scalable data processing application run well on Mesos (Hadoop, Kafka, Spark) and it is nice because you can run them all on the same basic resource pool, along with your new age container packaged apps. It is somewhat more heavy weight than the Kubernetes project, but is getting easier and easier to manage thanks to the work of folks like Mesosphere.

Now what gets really interesting is that Mesos is currently being adapted to add a lot of the Kubernetes concepts and to support the Kubernetes API. So it will be a gateway to getting more capabilities for your Kubernetes app (high availability master, more advanced scheduling semantics, ability to scale to a very large number of nodes) if you need them, and is well suited to run production workloads (Kubernetes is still in an alpha state).

When asked, I tend to say:

  1. Kubernetes is a great place to start if you are new to the clustering world; it is the quickest, easiest and lightest way to kick the tires and start experimenting with cluster oriented development. It offers a very high level of portability since it is being supported by a lot of different providers (Microsoft, IBM, Red Hat, CoreOs, MesoSphere, VMWare, etc).

  2. If you have existing workloads (Hadoop, Spark, Kafka, etc), Mesos gives you a framework that let's you interleave those workloads with each other, and mix in a some of the new stuff including Kubernetes apps.

  3. Mesos gives you an escape valve if you need capabilities that are not yet implemented by the community in the Kubernetes framework.

How to find longest string in the table column data

To answer your question, and get the Prefix too, for MySQL you can do:

select Prefix, CR, length(CR) from table1 order by length(CR) DESC limit 1;

and it will return


+-------+----------------------------+--------------------+
| Prefix| CR                         |         length(CR) |
+-------+----------------------------+--------------------+
| g     | ;#WR_1;#WR_2;#WR_3;#WR_4;# |                 26 |
+-------+----------------------------+--------------------+
1 row in set (0.01 sec)

How can I use custom fonts on a website?

CSS lets you use custom fonts, downloadable fonts on your website. You can download the font of your preference, let’s say myfont.ttf, and upload it to your remote server where your blog or website is hosted.

@font-face {
    font-family: myfont;
    src: url('myfont.ttf');
}

Iterating Through a Dictionary in Swift

Dictionaries in Swift (and other languages) are not ordered. When you iterate through the dictionary, there's no guarentee that the order will match the initialization order. In this example, Swift processes the "Square" key before the others. You can see this by adding a print statement to the loop. 25 is the 5th element of Square so largest would be set 5 times for the 5 elements in Square and then would stay at 25.

let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25]
]
var largest = 0
for (kind, numbers) in interestingNumbers {
    println("kind: \(kind)")
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}
largest

This prints:

kind: Square
kind: Prime
kind: Fibonacci

How to sort an object array by date property?

I have just taken the Schwartzian transform depicted above and made as function. It takes an array, the sorting function and a boolean as input:

function schwartzianSort(array,f,asc){
    for (var i=array.length;i;){
      var o = array[--i];
      array[i] = [].concat(f.call(o,o,i),o);
    }
    array.sort(function(a,b){
      for (var i=0,len=a.length;i<len;++i){
        if (a[i]!=b[i]) return a[i]<b[i]?asc?-1:1:1;
      }
      return 0;
    });
    for (var i=array.length;i;){
      array[--i]=array[i][array[i].length-1];
    }
    return array;
  }

_x000D_
_x000D_
function schwartzianSort(array, f, asc) {_x000D_
  for (var i = array.length; i;) {_x000D_
    var o = array[--i];_x000D_
    array[i] = [].concat(f.call(o, o, i), o);_x000D_
  }_x000D_
  array.sort(function(a, b) {_x000D_
    for (var i = 0, len = a.length; i < len; ++i) {_x000D_
      if (a[i] != b[i]) return a[i] < b[i] ? asc ? -1 : 1 : 1;_x000D_
    }_x000D_
    return 0;_x000D_
  });_x000D_
  for (var i = array.length; i;) {_x000D_
    array[--i] = array[i][array[i].length - 1];_x000D_
  }_x000D_
  return array;_x000D_
}_x000D_
_x000D_
arr = []_x000D_
arr.push({_x000D_
  date: new Date(1494434112806)_x000D_
})_x000D_
arr.push({_x000D_
  date: new Date(1494434118181)_x000D_
})_x000D_
arr.push({_x000D_
  date: new Date(1494434127341)_x000D_
})_x000D_
_x000D_
console.log(JSON.stringify(arr));_x000D_
_x000D_
arr = schwartzianSort(arr, function(o) {_x000D_
  return o.date_x000D_
}, false)_x000D_
console.log("DESC", JSON.stringify(arr));_x000D_
_x000D_
arr = schwartzianSort(arr, function(o) {_x000D_
  return o.date_x000D_
}, true)_x000D_
console.log("ASC", JSON.stringify(arr));
_x000D_
_x000D_
_x000D_

Convert string to date then format the date

tl;dr

LocalDate.parse( "2011-01-01" )
         .format( DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) ) 

java.time

The other Answers are now outdated. The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes.

ISO 8601

The input string 2011-01-01 happens to comply with the ISO 8601 standard formats for date-time text. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate ld = LocalDate.parse( "2011-01-01" ) ;

Generate a String in the same format by calling toString.

String output = ld.toString() ;

2011-01-01

DateTimeFormatter

To parse/generate other formats, use a DateTimeFormatter.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) ;
String output = ld.format( f ) ;

01-01-2011


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to concatenate strings in django templates?

Use with:

{% with "shop/"|add:shop_name|add:"/base.html" as template %}
{% include template %}
{% endwith %}

CSS fill remaining width

Include your image in the searchBar div, it will do the task for you

<div id="searchBar">
    <img src="img/logo.png" />                
    <input type="text" />
</div>

Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required)

I'm quite sure you won't get this 32Bit DLL working in Office 64Bit. The DLL needs to be updated by the author to be compatible with 64Bit versions of Office.

The code changes you have found and supplied in the question are used to convert calls to APIs that have already been rewritten for Office 64Bit. (Most Windows APIs have been updated.)

From: http://technet.microsoft.com/en-us/library/ee681792.aspx:

"ActiveX controls and add-in (COM) DLLs (dynamic link libraries) that were written for 32-bit Office will not work in a 64-bit process."

Edit: Further to your comment, I've tried the 64Bit DLL version on Win 8 64Bit with Office 2010 64Bit. Since you are using User Defined Functions called from the Excel worksheet you are not able to see the error thrown by Excel and just end up with the #VALUE returned.

If we create a custom procedure within VBA and try one of the DLL functions we see the exact error thrown. I tried a simple function of swe_day_of_week which just has a time as an input and I get the error Run-time error '48' File not found: swedll32.dll.

Now I have the 64Bit DLL you supplied in the correct locations so it should be found which suggests it has dependencies which cannot be located as per https://stackoverflow.com/a/8607250/1733206

I've got all the .NET frameworks installed which would be my first guess, so without further information from the author it might be difficult to find the problem.

Edit2: And after a bit more investigating it appears the 64Bit version you have supplied is actually a 32Bit version. Hence the error message on the 64Bit Office. You can check this by trying to access the '64Bit' version in Office 32Bit.

Move a view up only when the keyboard covers an input field

for swift 4.2.

This will apply to any form. No need of scrollview. do not forget to set delegate.

Make a var of uitextfield

var clickedTextField = UITextField()

In your viewdid load

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:NSNotification.Name.UIKeyboardWillShow, object: nil);
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name:NSNotification.Name.UIKeyboardWillHide, object: nil);

Know the clicked text field. probably you are having textfields on the entire screen.

func textFieldDidBeginEditing(_ textField: UITextField) {
    clickedTextField = textField
}

Check if the keyboard is covering textfield or not.

@objc func keyboardWillShow(sender: NSNotification,_ textField : UITextField) {
    if let keyboardSize = (sender.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {

        if clickedTextField.frame.origin.y > keyboardSize.origin.y {
            self.view.frame.origin.y = keyboardSize.origin.y - clickedTextField.center.y - 20
        }
    }
}

@objc func keyboardWillHide(sender: NSNotification) {
    self.view.frame.origin.y = 0
}

Return to close keyboard

func textFieldShouldReturn(_ textField: UITextField) -> Bool {   //delegate method
    textField.resignFirstResponder()
    return true
}

UPDATE : NSNotification.Name.UIKeyboardWillShow & NSNotification.Name.UIKeyboardWillHide are renamed to UIResponder.keyboardWillShowNotification & UIResponder.keyboardWillHideNotification respectively.

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

You have 3 options:

1) Get default value

dt = datetime??DateTime.Now;

it will assign DateTime.Now (or any other value which you want) if datetime is null

2) Check if datetime contains value and if not return empty string

if(!datetime.HasValue) return "";
dt = datetime.Value;

3) Change signature of method to

public string ConvertToPersianToShow(DateTime  datetime)

It's all because DateTime? means it's nullable DateTime so before assigning it to DateTime you need to check if it contains value and only then assign.

How do I initialise all entries of a matrix with a specific value?

As mentioned in other answers you can use:

>> tic; x=5*ones(10,1); toc
Elapsed time is 0.000415 seconds.

An even faster method is:

>> tic;  x=5; x=x(ones(10,1)); toc
Elapsed time is 0.000257 seconds.

Encode/Decode URLs in C++

cpp-netlib has functions

namespace boost {
  namespace network {
    namespace uri {    
      inline std::string decoded(const std::string &input);
      inline std::string encoded(const std::string &input);
    }
  }
}

they allow to encode and decode URL strings very easy.

How to Set a Custom Font in the ActionBar Title?

The Calligraphy library let's you set a custom font through the app theme, which would also apply to the action bar.

<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:textViewStyle">@style/AppTheme.Widget.TextView</item>
</style>

<style name="AppTheme.Widget"/>

<style name="AppTheme.Widget.TextView" parent="android:Widget.Holo.Light.TextView">
   <item name="fontPath">fonts/Roboto-ThinItalic.ttf</item>
</style>

All it takes to activate Calligraphy is attaching it to your Activity context:

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(new CalligraphyContextWrapper(newBase));
}

The default custom attribute is fontPath, but you may provide your own custom attribute for the path by initializing it in your Application class with CalligraphyConfig.Builder. Usage of android:fontFamily has been discouraged.

How can I kill a process by name instead of PID?

Using #killall command:

#killall -9 <processname>

How to move Jenkins from one PC to another

Jenkins Server Automation:

Step 1:

Set up a repository to store the Jenkins home (jobs, configurations, plugins, etc.) in a GitLab local or on GitHub private repository and keep it updated regularly by pushing any new changes to Jenkins jobs, plugins, etc.

Step 2:

Configure a Puppet host-group/role for Jenkins that can be used to spin up new Jenkins servers. Do all the basic configuration in a Puppet recipe and make sure it installs the latest version of Jenkins and sets up a separate directory/mount for JENKINS_HOME.

Step 3:

Spin up a new machine using the Jenkins-puppet configuration above. When everything is installed, grab/clone the Jenkins configuration from the Git repository to the Jenkins home direcotry and restart Jenkins.

Step 4:

Go to the Jenkins URL, Manage Jenkins ? Manage Plugins and update all the plugins that require an update.

Done

You can use Docker Swarm or Kubernetes to auto-scale the slave nodes.

How do I use Assert to verify that an exception has been thrown?

You can achieve this with a simple one-line.

If your operation foo.bar() is async:

await Assert.ThrowsExceptionAsync<Exception>(() => foo.bar());

If foo.bar() is not async

Assert.ThrowsException<Exception>(() => foo.bar());

mysql-python install error: Cannot open include file 'config-win.h'

For me, it worked when I selected the correct bit of my Python version, NOT the one of my computer version.

Mine is 32bit, and my computer is 64bit. That was the problem and the 32bit version of fixed it.

to be exact, here is the one that worked for me: mysqlclient-1.3.13-cp37-cp37m-win32.whl

How to use activity indicator view on iPhone?

Activity indicator 2 sec show and go to next page

@property(strong,nonatomic)IBOutlet UIActivityIndicator *activityindctr;

-(void)viewDidload { [super viewDidload];[activityindctr startanimating]; [self performSelector:@selector(nextpage) withObject:nil afterDelay:2];}

-(void)nextpage{ [activityindctr stopAnimating]; [self performSegueWithIdentifier:@"nextviewcintroller" sender:self];}

Updating and committing only a file's permissions using git version control

By default, git will update execute file permissions if you change them. It will not change or track any other permissions.

If you don't see any changes when modifying execute permission, you probably have a configuration in git which ignore file mode.

Look into your project, in the .git folder for the config file and you should see something like this:

[core]
    filemode = false

You can either change it to true in your favorite text editor, or run:

git config core.filemode true

Then, you should be able to commit normally your files. It will only commit the permission changes.

preferredStatusBarStyle isn't called

@serenn's answer above is still a great one for the case of UINavigationControllers. However, for swift 3 the childViewController functions have been changed to vars. So the UINavigationController extension code should be:

override open var childViewControllerForStatusBarStyle: UIViewController? {
  return topViewController
}

override open var childViewControllerForStatusBarHidden: UIViewController? {
  return topViewController
}

And then in the view controller that should dictate the status bar style:

override var preferredStatusBarStyle: UIStatusBarStyle {
   return .lightContent
}

SVN "Already Locked Error"

Sometimes cleaning the repository with the "break locks"-option still doesn't work if the lock was created by another process. Possible Solution: 1) Acquire a new lock on the folder/file and choose the option "Steal the locks" 2) Release your new lock.

What is the 'open' keyword in Swift?

Open is an access level, was introduced to impose limitations on class inheritance on Swift.

This means that the open access level can only be applied to classes and class members.

In Classes

An open class can be subclassed in the module it is defined in and in modules that import the module in which the class is defined.

In Class members

The same applies to class members. An open method can be overridden by subclasses in the module it is defined in and in modules that import the module in which the method is defined.

THE NEED FOR THIS UPDATE

Some classes of libraries and frameworks are not designed to be subclassed and doing so may result in unexpected behavior. Native Apple library also won't allow overriding the same methods and classes,

So after this addition they will apply public and private access levels accordingly.

For more details have look at Apple Documentation on Access Control

How does true/false work in PHP?

PHP uses weak typing (which it calls 'type juggling'), which is a bad idea (though that's a conversation for another time). When you try to use a variable in a context that requires a boolean, it will convert whatever your variable is into a boolean, according to some mostly arbitrary rules available here: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

When should I use GC.SuppressFinalize()?

SuppressFinalize should only be called by a class that has a finalizer. It's informing the Garbage Collector (GC) that this object was cleaned up fully.

The recommended IDisposable pattern when you have a finalizer is:

public class MyClass : IDisposable
{
    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                // called via myClass.Dispose(). 
                // OK to use any private object references
            }
            // Release unmanaged resources.
            // Set large fields to null.                
            disposed = true;
        }
    }

    public void Dispose() // Implement IDisposable
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~MyClass() // the finalizer
    {
        Dispose(false);
    }
}

Normally, the CLR keeps tabs on objects with a finalizer when they are created (making them more expensive to create). SuppressFinalize tells the GC that the object was cleaned up properly and doesn't need to go onto the finalizer queue. It looks like a C++ destructor, but doesn't act anything like one.

The SuppressFinalize optimization is not trivial, as your objects can live a long time waiting on the finalizer queue. Don't be tempted to call SuppressFinalize on other objects mind you. That's a serious defect waiting to happen.

Design guidelines inform us that a finalizer isn't necessary if your object implements IDisposable, but if you have a finalizer you should implement IDisposable to allow deterministic cleanup of your class.

Most of the time you should be able to get away with IDisposable to clean up resources. You should only need a finalizer when your object holds onto unmanaged resources and you need to guarantee those resources are cleaned up.

Note: Sometimes coders will add a finalizer to debug builds of their own IDisposable classes in order to test that code has disposed their IDisposable object properly.

public void Dispose() // Implement IDisposable
{
    Dispose(true);
#if DEBUG
    GC.SuppressFinalize(this);
#endif
}

#if DEBUG
~MyClass() // the finalizer
{
    Dispose(false);
}
#endif

Plotting two variables as lines using ggplot2 on the same graph

For a small number of variables, you can build the plot manually yourself:

ggplot(test_data, aes(date)) + 
  geom_line(aes(y = var0, colour = "var0")) + 
  geom_line(aes(y = var1, colour = "var1"))

How to check visibility of software keyboard in Android?

This code works great nice

use this class for root view:

public class KeyboardConstraintLayout extends ConstraintLayout {

private KeyboardListener keyboardListener;
private EditText targetEditText;
private int minKeyboardHeight;
private boolean isShow;

public KeyboardConstraintLayout(Context context) {
    super(context);
    minKeyboardHeight = getResources().getDimensionPixelSize(R.dimen.keyboard_min_height);
}

public KeyboardConstraintLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    minKeyboardHeight = getResources().getDimensionPixelSize(R.dimen.keyboard_min_height);
}

public KeyboardConstraintLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    minKeyboardHeight = getResources().getDimensionPixelSize(R.dimen.keyboard_min_height);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (!isInEditMode()) {
        Activity activity = (Activity) getContext();
        @SuppressLint("DrawAllocation")
        Rect rect = new Rect();
        getWindowVisibleDisplayFrame(rect);

        int statusBarHeight = rect.top;
        int keyboardHeight = activity.getWindowManager().getDefaultDisplay().getHeight() - (rect.bottom - rect.top) - statusBarHeight;

        if (keyboardListener != null && targetEditText != null && targetEditText.isFocused()) {
            if (keyboardHeight > minKeyboardHeight) {
                if (!isShow) {
                    isShow = true;
                    keyboardListener.onKeyboardVisibility(true);
                }
            }else {
                if (isShow) {
                    isShow = false;
                    keyboardListener.onKeyboardVisibility(false);
                }
            }
        }
    }
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

public boolean isShowKeyboard() {
    return isShow;
}

public void setKeyboardListener(EditText targetEditText, KeyboardListener keyboardListener) {
    this.targetEditText = targetEditText;
    this.keyboardListener = keyboardListener;
}

public interface KeyboardListener {
    void onKeyboardVisibility (boolean isVisible);
}

}

and set keyboard listener in activity or fragment:

    rootLayout.setKeyboardListener(targetEditText, new KeyboardConstraintLayout.KeyboardListener() {
    @Override
    public void onKeyboardVisibility(boolean isVisible) {

    }
});

SQL Server : SUM() of multiple rows including where clauses

you mean getiing sum(Amount of all types) for each property where EndDate is null:

SELECT propertyId, SUM(Amount) as TOTAL_COSTS
  FROM MyTable
 WHERE EndDate IS NULL
GROUP BY propertyId

How do I access Configuration in any class in ASP.NET Core?

The right way to do it:

In .NET Core you can inject the IConfiguration as a parameter into your Class constructor, and it will be available.

public class MyClass 
{
    private IConfiguration configuration;
    public MyClass(IConfiguration configuration)
    {
        ConnectionString = new configuration.GetValue<string>("ConnectionString");
    }

Now, when you want to create an instance of your class, since your class gets injected the IConfiguration, you won't be able to just do new MyClass(), because it needs a IConfiguration parameter injected into the constructor, so, you will need to inject your class as well to the injecting chain, which means two simple steps:

1) Add your Class/es - where you want to use the IConfiguration, to the IServiceCollection at the ConfigureServices() method in Startup.cs

services.AddTransient<MyClass>();

2) Define an instance - let's say in the Controller, and inject it using the constructor:

public class MyController : ControllerBase
{
    private MyClass _myClass;
    public MyController(MyClass myClass)
    {
        _myClass = myClass;
    }

Now you should be able to enjoy your _myClass.configuration freely...

Another option:

If you are still looking for a way to have it available without having to inject the classes into the controller, then you can store it in a static class, which you will configure in the Startup.cs, something like:

public static class MyAppData
{
    public static IConfiguration Configuration;
}

And your Startup constructor should look like this:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
    MyAppData.Configuration = configuration;
}

Then use MyAppData.Configuration anywhere in your program.

Don't confront me why the first option is the right way, I can just see experienced developers always avoid garbage data along their way, and it's well understood that it's not the best practice to have loads of data available in memory all the time, neither is it good for performance and nor for development, and perhaps it's also more secure to only have with you what you need.

React - clearing an input value after form submit

This is the value that i want to clear and create it in state 1st STEP

state={
TemplateCode:"",
}

craete submitHandler function for Button or what you want 3rd STEP

submitHandler=()=>{
this.clear();//this is function i made
}

This is clear function Final STEP

clear = () =>{
  this.setState({
    TemplateCode: ""//simply you can clear Templatecode
  });
}

when click button Templatecode is clear 2nd STEP

<div class="col-md-12" align="right">
  <button id="" type="submit" class="btn btnprimary" onClick{this.submitHandler}> Save 
  </button>
</div>

throw checked Exceptions from mocks with Mockito

A workaround is to use a willAnswer() method.

For example the following works (and doesn't throw a MockitoException but actually throws a checked Exception as required here) using BDDMockito:

given(someObj.someMethod(stringArg1)).willAnswer( invocation -> { throw new Exception("abc msg"); });

The equivalent for plain Mockito would to use the doAnswer method

Gradle: How to Display Test Results in the Console in Real Time?

Here is my fancy version:

fancy test result

import org.gradle.api.tasks.testing.logging.TestExceptionFormat
import org.gradle.api.tasks.testing.logging.TestLogEvent

tasks.withType(Test) {
    testLogging {
        // set options for log level LIFECYCLE
        events TestLogEvent.FAILED,
               TestLogEvent.PASSED,
               TestLogEvent.SKIPPED,
               TestLogEvent.STANDARD_OUT
        exceptionFormat TestExceptionFormat.FULL
        showExceptions true
        showCauses true
        showStackTraces true

        // set options for log level DEBUG and INFO
        debug {
            events TestLogEvent.STARTED,
                   TestLogEvent.FAILED,
                   TestLogEvent.PASSED,
                   TestLogEvent.SKIPPED,
                   TestLogEvent.STANDARD_ERROR,
                   TestLogEvent.STANDARD_OUT
            exceptionFormat TestExceptionFormat.FULL
        }
        info.events = debug.events
        info.exceptionFormat = debug.exceptionFormat

        afterSuite { desc, result ->
            if (!desc.parent) { // will match the outermost suite
                def output = "Results: ${result.resultType} (${result.testCount} tests, ${result.successfulTestCount} passed, ${result.failedTestCount} failed, ${result.skippedTestCount} skipped)"
                def startItem = '|  ', endItem = '  |'
                def repeatLength = startItem.length() + output.length() + endItem.length()
                println('\n' + ('-' * repeatLength) + '\n' + startItem + output + endItem + '\n' + ('-' * repeatLength))
            }
        }
    }
}

read word by word from file in C++

As others have said, you are likely reading past the end of the file as you're only checking for x != ' '. Instead you also have to check for EOF in the inner loop (but in this case don't use a char, but a sufficiently large type):

while ( ! file.eof() )
{
    std::ifstream::int_type x = file.get();

    while ( x != ' ' && x != std::ifstream::traits_type::eof() )
    {
        word += static_cast<char>(x);
        x = file.get();
    }
    std::cout << word << '\n';
    word.clear();
}

But then again, you can just employ the stream's streaming operators, which already separate at whitespace (and better account for multiple spaces and other kinds of whitepsace):

void readFile(  )
{
    std::ifstream file("program.txt");
    for(std::string word; file >> word; )
        std::cout << word << '\n';
}

And even further, you can employ a standard algorithm to get rid of the manual loop altogether:

#include <algorithm>
#include <iterator>

void readFile(  )
{
    std::ifstream file("program.txt");
    std::copy(std::istream_iterator<std::string>(file), 
              std::istream_itetator<std::string>(), 
              std::ostream_iterator<std::string>(std::cout, "\n"));
}

How do I extract the contents of an rpm?

7-zip understands most kinds of archives, including rpm and the included cpio.

How do I use spaces in the Command Prompt?

Single quotation marks won't do in that case. You have to add quotation marks around each path and also enclose the whole command in quotation marks:

cmd /C ""C:\Program Files (x86)\WinRar\Rar.exe" a "D:\Hello 2\File.rar" "D:\Hello 2\*.*""

I want to get the type of a variable at runtime

i have tested that and it worked

val x = 9
def printType[T](x:T) :Unit = {println(x.getClass.toString())}

How to find out the number of CPUs using python

Another option is to use the psutil library, which always turn out useful in these situations:

>>> import psutil
>>> psutil.cpu_count()
2

This should work on any platform supported by psutil(Unix and Windows).

Note that in some occasions multiprocessing.cpu_count may raise a NotImplementedError while psutil will be able to obtain the number of CPUs. This is simply because psutil first tries to use the same techniques used by multiprocessing and, if those fail, it also uses other techniques.

How do I clone a specific Git branch?

Here is a really simple way to do it :)

Clone the repository

git clone <repository_url>

List all branches

git branch -a 

Checkout the branch that you want

git checkout <name_of_branch>

Collections.sort with multiple fields

I had the same issue and I needed an algorithm using a config file. In This way you can use multiple fields define by a configuration file (simulate just by a List<String) config)

  public static void test() {  
    // Associate your configName with your Comparator 
    Map<String, Comparator<DocumentDto>> map = new HashMap<>();
    map.put("id", new IdSort());
    map.put("createUser", new DocumentUserSort());
    map.put("documentType", new DocumentTypeSort());
    /**
      In your config.yml file, you'll have something like
      sortlist: 
        - documentType
        - createUser
        - id
    */
    List<String> config = new ArrayList<>();
    config.add("documentType");
    config.add("createUser");
    config.add("id");
    

    List<Comparator<DocumentDto>> sorts = new ArrayList<>();

    for (String comparator : config) {
        sorts.add(map.get(comparator));
    }

    // Begin creation of the list 
    DocumentDto d1 = new DocumentDto();
    d1.setDocumentType(new DocumentTypeDto());
    d1.getDocumentType().setCode("A");
    d1.setId(1);
    d1.setCreateUser("Djory");

    DocumentDto d2 = new DocumentDto();
    d2.setDocumentType(new DocumentTypeDto());
    d2.getDocumentType().setCode("A");
    d2.setId(2);
    d2.setCreateUser("Alex");

    DocumentDto d3 = new DocumentDto();
    d3.setDocumentType(new DocumentTypeDto());
    d3.getDocumentType().setCode("A");
    d3.setId(3);
    d3.setCreateUser("Djory");

    DocumentDto d4 = new DocumentDto();
    d4.setDocumentType(new DocumentTypeDto());
    d4.getDocumentType().setCode("A");
    d4.setId(4);
    d4.setCreateUser("Alex");

    DocumentDto d5 = new DocumentDto();
    d5.setDocumentType(new DocumentTypeDto());
    d5.getDocumentType().setCode("D");
    d5.setId(5);
    d5.setCreateUser("Djory");

    DocumentDto d6 = new DocumentDto();
    d6.setDocumentType(new DocumentTypeDto());
    d6.getDocumentType().setCode("B");
    d6.setId(6);
    d6.setCreateUser("Alex");

    DocumentDto d7 = new DocumentDto();
    d7.setDocumentType(new DocumentTypeDto());
    d7.getDocumentType().setCode("B");
    d7.setId(7);
    d7.setCreateUser("Alex");

    List<DocumentDto> documents = new ArrayList<>();

    documents.add(d1);
    documents.add(d2);
    documents.add(d3);
    documents.add(d4);
    documents.add(d5);
    documents.add(d6);
    documents.add(d7);
    // End creation of the list


    // The Sort 
    Stream<DocumentDto> docStream = documents.stream();

    // we need to reverse this list in order to sort by documentType first because stream are pull-based, last sorted() will have the priority
    Collections.reverse(sorts);

    for(Comparator<DocumentDto> entitySort : sorts){
        docStream = docStream.sorted(entitySort);
    }
    documents = docStream.collect(Collectors.toList());
    // documents has been sorted has you configured
    // in case of equality second sort will be used.

    System.out.println(documents);

  }

Comparator objects are really simple.

public class IdSort implements Comparator<DocumentDto> {

    @Override
    public int compare(DocumentDto o1, DocumentDto o2) {
        return o1.getId().compareTo(o2.getId());
    }
}
public class DocumentUserSort implements Comparator<DocumentDto> {

    @Override
    public int compare(DocumentDto o1, DocumentDto o2) {
        return o1.getCreateUser().compareTo(o2.getCreateUser());
    }
}
public class DocumentTypeSort implements Comparator<DocumentDto> {

    @Override
    public int compare(DocumentDto o1, DocumentDto o2) {
        return o1.getDocumentType().getCode().compareTo(o2.getDocumentType().getCode());
    }
}

Conclusion : this method isn't has efficient but you can create generic sort using a file configuration in this way.

How do I get the max ID with Linq to Entity?

Do that like this

db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();

INSERT INTO a temp table, and have an IDENTITY field created, without first declaring the temp table?

IIRC, the INSERT INTO command uses the schema of the source table to create the temp table. That's part of the reason you can't just try to create a table with an additional column. Identity columns are internally tied to a SQL Server construct called a generator.

How to create range in Swift?

I want to do this:

print("Hello"[1...3])
// out: Error

But unfortunately, I can't write a subscript of my own because the loathed one takes up the name space.

We can do this however:

print("Hello"[range: 1...3])
// out: ell 

Just add this to your project:

extension String {
    subscript(range: ClosedRange<Int>) -> String {
        get {
            let start = String.Index(utf16Offset: range.lowerBound, in: self)
            let end = String.Index(utf16Offset: range.upperBound, in: self)
            return String(self[start...end])
        }
    }
}

Use CSS to remove the space between images

The best solution I've found for this is to contain them in a parent div, and give that div a font-size of 0.

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

I found success using this configuration:

classpath 'com.android.tools.build:gradle:1.5.0'
classpath 'com.google.gms:google-services:2.0.0-alpha3'
//or use
//classpath 'com.android.tools.build:gradle:2.0.0-alpha6'

and

distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip

using 8.40 Google Play services. Alpha5 & Alpha6 gave the same 2.8 error you had, regardless of the distributionUrl being 2.10

Difference between __getattr__ vs __getattribute__

In reading through Beazley & Jones PCB, I have stumbled on an explicit and practical use-case for __getattr__ that helps answer the "when" part of the OP's question. From the book:

"The __getattr__() method is kind of like a catch-all for attribute lookup. It's a method that gets called if code tries to access an attribute that doesn't exist." We know this from the above answers, but in PCB recipe 8.15, this functionality is used to implement the delegation design pattern. If Object A has an attribute Object B that implements many methods that Object A wants to delegate to, rather than redefining all of Object B's methods in Object A just to call Object B's methods, define a __getattr__() method as follows:

def __getattr__(self, name):
    return getattr(self._b, name)

where _b is the name of Object A's attribute that is an Object B. When a method defined on Object B is called on Object A, the __getattr__ method will be invoked at the end of the lookup chain. This would make code cleaner as well, since you do not have a list of methods defined just for delegating to another object.

Full Page <iframe>

This is cross-browser and fully responsive:

<iframe
  src="https://drive.google.com/file/d/0BxrMaW3xINrsR3h2cWx0OUlwRms/preview"
  style="
    position: fixed;
    top: 0px;
    bottom: 0px;
    right: 0px;
    width: 100%;
    border: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    z-index: 999999;
    height: 100%;
  ">
</iframe>

Android Studio error: "Environment variable does not point to a valid JVM installation"

It started happening to me when I changed variables for Android Studio. Go to your studio64.exe.vmoptions file (located in c:\users\userName\.AndroidStudio{version}\ and comments the arguments.

Convert java.time.LocalDate into java.util.Date type

Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

That assumes your date chooser uses the system default timezone to transform dates into strings.

Difference between string object and string literal

In the first case, there are two objects created.

In the second case, it's just one.

Although both ways str is referring to "abc".

Enabling/installing GD extension? --without-gd

if you are on a Debian based server (such as Ubuntu) you can run the following command:

apt-get install php-gd

Then once it is complete run:

/etc/init.d/apache2 restart

This will restart your server and enable GD in PHP.

If you are on another type of system you will need to use something else (like yum install) or compile directly into PHP.

How do you add an action to a button programmatically in xcode

CGRect buttonFrame = CGRectMake( 10, 80, 100, 30 );
        UIButton *button = [[UIButton alloc] initWithFrame: buttonFrame];
        [button setTitle: @"My Button" forState: UIControlStateNormal];
        [button addTarget:self action:@selector(btnSelected:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor: [UIColor redColor] forState: UIControlStateNormal];
[view addSubview:button];

@Html.DropDownListFor how to set default value

I hope this is helpful to you.

Please try this code,

 @Html.DropDownListFor(model => model.Items, new List<SelectListItem>
   { new SelectListItem{Text="Deactive", Value="False"},
     new SelectListItem{Text="Active", Value="True",  Selected = true},
     })

Linq filter List<string> where it contains a string value from another List<string>

you can do that

var filteredFileList = fileList.Where(fl => filterList.Contains(fl.ToString()));

Parse an URL in JavaScript

One liner:

location.search.replace('?','').split('&').reduce(function(s,c){var t=c.split('=');s[t[0]]=t[1];return s;},{})

Show special characters in Unix while using 'less' Command

less will look in its environment to see if there is a variable named LESS

You can set LESS in one of your ~/.profile (.bash_rc, etc, etc) and then anytime you run less from the comand line, it will find the LESS.

Try adding this

export LESS="-CQaix4"

This is the setup I use, there are some behaviors embedded in that may confuse you, so you can find out about what all of these mean from the help function in less, just tap the 'h' key and nose around, or run less --help.

Edit:

I looked at the help, and noticed there is also an -r option

-r  -R  ....  --raw-control-chars  --RAW-CONTROL-CHARS
                Output "raw" control characters.

I agree that cat may be the most exact match to your stated needs.

cat -vet file | less

Will add '$' at end of each line and convert tab char to visual '^I'.

cat --help
   (edited)
    -e                       equivalent to -vE
    -E, --show-ends          display $ at end of each line
    -t                       equivalent to -vT
    -T, --show-tabs          display TAB characters as ^I
    -v, --show-nonprinting   use ^ and M- notation, except for LFD and TAB

I hope this helps.

Connect to SQL Server database from Node.js

//start the program
var express = require('express');
var app = express();

app.get('/', function (req, res) {

    var sql = require("mssql");

    // config for your database
    var config = {
        user: 'datapullman',
        password: 'system',
        server: 'localhost', 
        database: 'chat6' 
    };

    // connect to your database
    sql.connect(config, function (err) {

        if (err) console.log(err);

        // create Request object
        var request = new sql.Request();

        // query to the database and get the records

        request.query("select * From emp", function (err, recordset) {            
            if  (err) console.log(err)

            // send records as a response
            res.send(recordset);

        });
    });
});

var server = app.listen(5000, function () {
    console.log('Server is running..');
});

//create a table as emp in a database (i have created as chat6)

// programs ends here

//save it as app.js and run as node app.js //open in you browser as localhost:5000

How to install python3 version of package via pip on Ubuntu?

The easiest way to install latest pip2/pip3 and corresponding packages:

curl https://bootstrap.pypa.io/get-pip.py | python2
pip2 install package-name    

curl https://bootstrap.pypa.io/get-pip.py | python3
pip3 install package-name

Note: please run these commands as root

Convert a date format in epoch

Create Common Method to Convert String to Date format

public static void main(String[] args) throws Exception {
    long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
    long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
    long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");
}

private static long ConvertStringToDate(String dateString, String format) {
    try {
        return new SimpleDateFormat(format).parse(dateString).getTime();
    } catch (ParseException e) {}
    return 0;
}

SQL - How to find the highest number in a column?

You can do

SELECT MAX(ID) FROM Customers;

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

As Homebrew is my favorite for macOS although it is possible to have apt-get on macOS using Fink.

How to create multidimensional array

you can create array follow the code below:

var arraymultidimensional = []
    arraymultidimensional = [[value1,value2],[value3,value4],[value5,value6]];

Result:
[v1][v2] position 0
[v3][v4] position 1
[v5][v6] position 2

For add to array dinamically, use the method below:

//vectorvalue format = "[value,value,...]"
function addToArray(vectorvalue){
  arraymultidimensional[arraymultidimensional.length] = vectorvalue;
}

Hope this helps. :)

How to list only files and not directories of a directory Bash?

ls -p | grep -v /

ls -p lets you show / after the folder name, which acts as a tag for you to remove.

Show DataFrame as table in iPython Notebook

You'll need to use the HTML() or display() functions from IPython's display module:

from IPython.display import display, HTML

# Assuming that dataframes df1 and df2 are already defined:
print "Dataframe 1:"
display(df1)
print "Dataframe 2:"
display(HTML(df2.to_html()))

Note that if you just print df1.to_html() you'll get the raw, unrendered HTML.

You can also import from IPython.core.display with the same effect

How to display list of repositories from subversion server

Sometimes you may wish to check on the timestamp for when the repo was updated, for getting this handy info you can use the svn -v (verbose) option as in

svn list -v svn://123.123.123.123/svn/repo/path

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

This esc behavior is IE only by the way. Instead of using jQuery use good old javascript for creating the element and it works.

var element = document.createElement('input');
element.type = 'text';
element.value = 100;
document.getElementsByTagName('body')[0].appendChild(element);

http://jsfiddle.net/gGrf9/

If you want to extend this functionality to other browsers then I would use jQuery's data object to store the default. Then set it when user presses escape.

//store default value for all elements on page. set new default on blur
$('input').each( function() {
    $(this).data('default', $(this).val());
    $(this).blur( function() { $(this).data('default', $(this).val()); });
});

$('input').keyup( function(e) {
    if (e.keyCode == 27) { $(this).val($(this).data('default')); }
});

How to make a back-to-top button using CSS and HTML only?

<a href="#">Start of page</a>

"The link has the href value of "#", which by definition means the start of the current document. Thus there is no need to worry about the correct way of setting up the destination anchor..."

Source

How to check type of variable in Java?

You can check it easily using Java.lang.Class.getSimpleName() Method Only if variable has non-primitive type. It doesnt work with primitive types int ,long etc.

reference - Here is the Oracle docs link

How to copy a directory structure but only include certain files (using windows batch files)

Thanks To Previous Answers. :)

This script named "r4k4copy.cmd":

@echo off
for %%p in (SOURCE_DIR DEST_DIR FILENAMES_TO_COPY) do set %%p=
cls
echo :: Copy Files Including Folder Tree
echo :: http://stackoverflow.com
rem     /questions/472692/how-to-copy
rem     -a-directory-structure-but-only
rem     -include-certain-files-using-windows
echo :: ReScripted by r4k4
echo.
if "%1"=="" goto :NoParam
if "%2"=="" goto :NoParam
if "%3"=="" goto :NoParam
setlocal enabledelayedexpansion
set SOURCE_DIR=%1
set DEST_DIR=%2
set FILENAMES_TO_COPY=%3
for /R "%SOURCE_DIR%" %%F IN (%FILENAMES_TO_COPY%) do (
if exist "%%F" (
set FILE_DIR=%%~dpF
set FILE_INTERMEDIATE_DIR=!FILE_DIR:%SOURCE_DIR%=!
xcopy /E /I /Y "%%F" "%DEST_DIR%!FILE_INTERMEDIATE_DIR!"
)
)
goto :eof
:NoParam
echo.
echo Syntax: %0 [Source_DIR] [Dest_DIR] [FileName]
echo Eg.   : %0 D:\Root E:\Root\Lev1\Lev2\Lev3 *.JPG
echo Means : Copy *.JPG from D:\Root to E:\Root\Lev1\Lev2\Lev3

It accepts variable of "Source", "Destination", and "FileName". It also can only copying specified type of files or selective filenames.

Any improvement are welcome. :)

GZIPInputStream reading line by line

GZIPInputStream gzip = new GZIPInputStream(new FileInputStream("F:/gawiki-20090614-stub-meta-history.xml.gz"));
BufferedReader br = new BufferedReader(new InputStreamReader(gzip));
br.readLine();

Adding values to an array in java

put x=0 outside the for loop that is the problem

Loop inside React JSX

Using map in React are best practices for iterating over an array.

To prevent some errors with ES6, the syntax map is used like this in React:

<tbody>
    {items.map((item, index) => <ObjectRow key={index} name={item.name} />)}
</tbody>

Here you call a Component, <ObjectRow/>, so you don't need to put parenthesis after the arrow.

But you can be make this too:

{items.map((item, index) => (
    <ObjectRow key={index} name={item.name} />
))}

Or:

{items.map((item, index) => {
    // Here you can log 'item'
    return (
        <ObjectRow key={index} name={item.name} />
    )
})}

I say that because if you put a bracket "{}" after the arrow React will not throw an error and will display a whitelist.

Change variable name in for loop using R

Another option is using eval and parse, as in

d = 5
for (i in 1:10){
     eval(parse(text = paste('a', 1:10, ' = d + rnorm(3)', sep='')[i]))
}

How can I list the scheduled jobs running in my database?

I think you need the SCHEDULER_ADMIN role to see the dba_scheduler tables (however this may grant you too may rights)

see: http://download.oracle.com/docs/cd/B28359_01/server.111/b28310/schedadmin001.htm

Elasticsearch query to return all records

If it's a small dataset (e.g. 1K records), you can simply specify size:

curl localhost:9200/foo_index/_search?size=1000

The match all query isn't needed, as it's implicit.

If you have a medium-sized dataset, like 1M records, you may not have enough memory to load it, so you need a scroll.

A scroll is like a cursor in a DB. In Elasticsearch, it remembers where you left off and keeps the same view of the index (i.e. prevents the searcher from going away with a refresh, prevents segments from merging).

API-wise, you have to add a scroll parameter to the first request:

curl 'localhost:9200/foo_index/_search?size=100&scroll=1m&pretty'

You get back the first page and a scroll ID:

{
  "_scroll_id" : "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAADEWbmJlSmxjb2hSU0tMZk12aEx2c0EzUQ==",
  "took" : 0,
...

Remember that both the scroll ID you get back and the timeout are valid for the next page. A common mistake here is to specify a very large timeout (value of scroll), that would cover for processing the whole dataset (e.g. 1M records) instead of one page (e.g. 100 records).

To get the next page, fill in the last scroll ID and a timeout that should last until fetching the following page:

curl -XPOST -H 'Content-Type: application/json' 'localhost:9200/_search/scroll' -d '{
  "scroll": "1m",
  "scroll_id": "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAADAWbmJlSmxjb2hSU0tMZk12aEx2c0EzUQ=="
}'

If you have a lot to export (e.g. 1B documents), you'll want to parallelise. This can be done via sliced scroll. Say you want to export on 10 threads. The first thread would issue a request like this:

curl -XPOST -H 'Content-Type: application/json' 'localhost:9200/test/_search?scroll=1m&size=100' -d '{
  "slice": {
    "id": 0, 
    "max": 10 
  }
}'

You get back the first page and a scroll ID, exactly like a normal scroll request. You'd consume it exactly like a regular scroll, except that you get 1/10th of the data.

Other threads would do the same, except that id would be 1, 2, 3...

SMTP error 554

SMTP error 554 is one of the more vague error codes, but is typically caused by the receiving server seeing something in the From or To headers that it doesn't like. This can be caused by a spam trap identifying your machine as a relay, or as a machine not trusted to send mail from your domain.

We ran into this problem recently when adding a new server to our array, and we fixed it by making sure that we had the correct reverse DNS lookup set up.

What's the name for hyphen-separated case?

It's also sometimes known as caterpillar-case

Clear variable in python

What's wrong with self.left = None?

How can I jump to class/method definition in Atom text editor?

As of November 2018 the package autocomplete-python offers this functionality with this key combo:

Ctrl+Alt+G

with mouse cursor on the function call.

jQuery - Illegal invocation

If you want to submit a form using Javascript FormData API with uploading files you need to set below two options:

processData: false,
contentType: false

You can try as follows:

//Ajax Form Submission
$(document).on("click", ".afs", function (e) {
    e.preventDefault();
    e.stopPropagation();
    var thisBtn = $(this);
    var thisForm = thisBtn.closest("form");
    var formData = new FormData(thisForm[0]);
    //var formData = thisForm.serializeArray();

    $.ajax({
        type: "POST",
        url: "<?=base_url();?>assignment/createAssignment",
        data: formData,
        processData: false,
        contentType: false,
        success:function(data){
            if(data=='yes')
            {
                alert('Success! Record inserted successfully');
            }
            else if(data=='no')
            {
                alert('Error! Record not inserted successfully')
            }
            else
            {
                alert('Error! Try again');
            }
        }
    });
});

How to bring a window to the front?

There are numerous caveats in the javadoc for the toFront() method which may be causing your problem.

But I'll take a guess anyway, when "only the tab in the taskbar flashes", has the application been minimized? If so the following line from the javadoc may apply:

"If this Window is visible, brings this Window to the front and may make it the focused Window."

Adding multiple class using ng-class

An incredibly powerful alternative to other answers here:

ng-class="[  { key: resulting-class-expression }[ key-matching-expression ], ..  ]"

Some examples:

1. Simply adds 'class1 class2 class3' to the div:

<div ng-class="[{true: 'class1'}[true], {true: 'class2 class3'}[true]]"></div>

2. Adds 'odd' or 'even' classes to div, depending on the $index:

<div ng-class="[{0:'even', 1:'odd'}[ $index % 2]]"></div>

3. Dynamically creates a class for each div based on $index

<div ng-class="[{true:'index'+$index}[true]]"></div>

If $index=5 this will result in:

<div class="index5"></div>

Here's a code sample you can run:

_x000D_
_x000D_
var app = angular.module('app', []); _x000D_
app.controller('MyCtrl', function($scope){_x000D_
  $scope.items = 'abcdefg'.split('');_x000D_
}); 
_x000D_
.odd  { background-color: #eee; }_x000D_
.even { background-color: #fff; }_x000D_
.index5 {background-color: #0095ff; color: white; font-weight: bold; }_x000D_
* { font-family: "Courier New", Courier, monospace; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="app" ng-controller="MyCtrl">_x000D_
  <div ng-repeat="item in items"_x000D_
    ng-class="[{true:'index'+$index}[true], {0:'even', 1:'odd'}[ $index % 2 ]]">_x000D_
    index {{$index}} = "{{item}}" ng-class="{{[{true:'index'+$index}[true], {0:'even', 1:'odd'}[ $index % 2 ]].join(' ')}}"_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I install Python 3 on an AWS EC2 instance?

Here are the steps I used to manually install python3 for anyone else who wants to do it as it's not super straight forward. EDIT: It's almost certainly easier to use the yum package manager (see other answers).

Note, you'll probably want to do sudo yum groupinstall 'Development Tools' before doing this otherwise pip won't install.

wget https://www.python.org/ftp/python/3.4.2/Python-3.4.2.tgz
tar zxvf Python-3.4.2.tgz
cd Python-3.4.2
sudo yum install gcc
./configure --prefix=/opt/python3
make
sudo yum install openssl-devel
sudo make install
sudo ln -s /opt/python3/bin/python3 /usr/bin/python3
python3 (should start the interpreter if it's worked (quit() to exit)

Pass a simple string from controller to a view MVC3

Just define your action method like this

public string ThemePath()

and simply return the string itself.

How do I store data in local storage using Angularjs?

Follow the steps to store data in Angular - local storage:

  1. Add 'ngStorage.js' in your folder.
  2. Inject 'ngStorage' in your angular.module

        eg: angular.module("app", [ 'ngStorage']);
    
  3. Add $localStorage in your app.controller function

4.You can use $localStorage inside your controller

Eg: $localstorage.login= true;

The above will store the localstorage in your browser application

SecurityException: Permission denied (missing INTERNET permission?)

Write your permission before the application tag as given below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.someapp.sample">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

Mongoose, Select a specific field with find

The _id field is always present unless you explicitly exclude it. Do so using the - syntax:

exports.someValue = function(req, res, next) {
    //query with mongoose
    var query = dbSchemas.SomeValue.find({}).select('name -_id');

    query.exec(function (err, someValue) {
        if (err) return next(err);
        res.send(someValue);
    });
};

Or explicitly via an object:

exports.someValue = function(req, res, next) {
    //query with mongoose
    var query = dbSchemas.SomeValue.find({}).select({ "name": 1, "_id": 0});

    query.exec(function (err, someValue) {
        if (err) return next(err);
        res.send(someValue);
    });
};

How to iterate over columns of pandas dataframe to run regression

You can use iteritems():

for name, values in df.iteritems():
    print('{name}: {value}'.format(name=name, value=values[0]))

Copy data from one existing row to another existing row in SQL?

Copy a value from one row to any other qualified rows within the same table (or different tables):

UPDATE `your_table` t1, `your_table` t2
SET t1.your_field = t2.your_field
WHERE t1.other_field = some_condition
AND t1.another_field = another_condition
AND t2.source_id = 'explicit_value'

Start off by aliasing the table into 2 unique references so the SQL server can tell them apart

Next, specify the field(s) to copy.

Last, specify the conditions governing the selection of the rows

Depending on the conditions you may copy from a single row to a series, or you may copy a series to a series. You may also specify different tables, and you can even use sub-selects or joins to allow using other tables to control the relationships.

How to use LocalBroadcastManager?

In Eclipse, eventually I had to add Compatibility/Support Library by right-clicking on my project and selecting:

Android Tools -> Add Support Library

Once it was added, then I was able to use LocalBroadcastManager class in my code.


Android Compatibility Library

How to implement debounce in Vue2?

If you are using Vue you can also use v.model.lazy instead of debounce but remember v.model.lazy will not always work as Vue limits it for custom components.

For custom components you should use :value along with @change.native

<b-input :value="data" @change.native="data = $event.target.value" ></b-input>

What is makeinfo, and how do I get it?

If it doesn't show up in your package manager (i.e. apt-cache search texinfo) and even apt-file search bin/makeinfo is no help, you may have to enable non-free/restricted packages for your package manager.

For ubuntu, sudo $EDITOR /etc/apt/sources.list and add restricted.

deb http://archive.ubuntu.com/ubuntu bionic main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu bionic-security main
deb http://archive.ubuntu.com/ubuntu bionic-updates main

For debian, sudo $EDITOR /etc/apt/sources.list and add non-free. You can even have preferences on package level if you don't want to clutter the package db with non-free stuff.

After a sudo apt-get udpate you should find the required package.

Undo scaffolding in Rails

rails [option] scaffold scaffold_name

Option

g    generate
d    destroy

If you do

rails g  scaffold myFoo

Then reverse it back using

rails d scaffold MyFoo

Convert line endings

Some options:

Using tr

tr -d '\15\32' < windows.txt > unix.txt

OR

tr -d '\r' < windows.txt > unix.txt 

Using perl

perl -p -e 's/\r$//' < windows.txt > unix.txt

Using sed

sed 's/^M$//' windows.txt > unix.txt

OR

sed 's/\r$//' windows.txt > unix.txt

To obtain ^M, you have to type CTRL-V and then CTRL-M.

PHP - Get bool to echo false when false

The %b option of sprintf() will convert a boolean to an integer:

echo sprintf("False will print as %b", false); //False will print as 0
echo sprintf("True will print as %b", true); //True will print as 1

If you're not familiar with it: You can give this function an arbitrary amount of parameters while the first one should be your ouput string spiced with replacement strings like %b or %s for general string replacement.

Each pattern will be replaced by the argument in order:

echo sprintf("<h1>%s</h1><p>%s<br/>%s</p>", "Neat Headline", "First Line in the paragraph", "My last words before this demo is over");

how to draw a rectangle in HTML or CSS?

You need to identify your sections and then style them with CSS. In this case, this might work:

HTML

<div id="blueRectangle"></div>

CSS

#blueRectangle {
    background: #4679BD;
    min-height: 50px;
    //width: 100%;
}

http://jsfiddle.net/7PJ5q/

Why use double indirection? or Why use pointers to pointers?

I saw a very good example today, from this blog post, as I summarize below.

Imagine you have a structure for nodes in a linked list, which probably is

typedef struct node
{
    struct node * next;
    ....
} node;

Now you want to implement a remove_if function, which accepts a removal criterion rm as one of the arguments and traverses the linked list: if an entry satisfies the criterion (something like rm(entry)==true), its node will be removed from the list. In the end, remove_if returns the head (which may be different from the original head) of the linked list.

You may write

for (node * prev = NULL, * curr = head; curr != NULL; )
{
    node * const next = curr->next;
    if (rm(curr))
    {
        if (prev)  // the node to be removed is not the head
            prev->next = next;
        else       // remove the head
            head = next;
        free(curr);
    }
    else
        prev = curr;
    curr = next;
}

as your for loop. The message is, without double pointers, you have to maintain a prev variable to re-organize the pointers, and handle the two different cases.

But with double pointers, you can actually write

// now head is a double pointer
for (node** curr = head; *curr; )
{
    node * entry = *curr;
    if (rm(entry))
    {
        *curr = entry->next;
        free(entry);
    }
    else
        curr = &entry->next;
}

You don't need a prev now because you can directly modify what prev->next pointed to.

To make things clearer, let's follow the code a little bit. During the removal:

  1. if entry == *head: it will be *head (==*curr) = *head->next -- head now points to the pointer of the new heading node. You do this by directly changing head's content to a new pointer.
  2. if entry != *head: similarly, *curr is what prev->next pointed to, and now points to entry->next.

No matter in which case, you can re-organize the pointers in a unified way with double pointers.

Spring Boot Java Config Set Session Timeout

  • Spring Boot version 1.0: server.session.timeout=1200
  • Spring Boot version 2.0: server.servlet.session.timeout=10m
    NOTE: If a duration suffix is not specified, seconds will be used.

Display a RecyclerView in Fragment

Make sure that you have the correct layout, and that the RecyclerView id is inside the layout. Otherwise, you will be getting this error. I had the same problem, then I noticed the layout was wrong.

    public class ColorsFragment extends Fragment {

         public ColorsFragment() {}

         @Override
         public View onCreateView(LayoutInflater inflater, ViewGroup container,
             Bundle savedInstanceState) {

==> make sure you are getting the correct layout here. R.layout...

             View rootView = inflater.inflate(R.layout.fragment_colors, container, false); 

PowerShell equivalent to grep -f

So I found a pretty good answer at this link: https://www.thomasmaurer.ch/2011/03/powershell-search-for-string-or-grep-for-powershell/

But essentially it is:

Select-String -Path "C:\file\Path\*.txt" -Pattern "^Enter REGEX Here$"

This gives a directory file search (*or you can just specify a file) and a file-content search all in one line of PowerShell, very similar to grep. The output will be similar to:

doc.txt:31: Enter REGEX Here
HelloWorld.txt:13: Enter REGEX Here

HTTP POST using JSON in Java

You can use the following code with Apache HTTP:

String payload = "{\"name\": \"myname\", \"age\": \"20\"}";
post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));

response = client.execute(request);

Additionally you can create a json object and put in fields into the object like this

HttpPost post = new HttpPost(URL);
JSONObject payload = new JSONObject();
payload.put("name", "myName");
payload.put("age", "20");
post.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON));

Why is Event.target not Element in Typescript?

With typescript we can leverage type aliases, like so:

type KeyboardEvent = {
  target: HTMLInputElement,
  key: string,
};
const onKeyPress = (e: KeyboardEvent) => {
  if ('Enter' === e.key) { // Enter keyboard was pressed!
    submit(e.target.value);
    e.target.value = '';
    return;
  }
  // continue handle onKeyPress input events...
};

Private vs Protected - Visibility Good-Practice Concern

Let me preface this by saying I'm talking primarily about method access here, and to a slightly lesser extent, marking classes final, not member access.

The old wisdom

"mark it private unless you have a good reason not to"

made sense in days when it was written, before open source dominated the developer library space and VCS/dependency mgmt. became hyper collaborative thanks to Github, Maven, etc. Back then there was also money to be made by constraining the way(s) in which a library could be utilized. I spent probably the first 8 or 9 years of my career strictly adhering to this "best practice".

Today, I believe it to be bad advice. Sometimes there's a reasonable argument to mark a method private, or a class final but it's exceedingly rare, and even then it's probably not improving anything.

Have you ever:

  • Been disappointed, surprised or hurt by a library etc. that had a bug that could have been fixed with inheritance and few lines of code, but due to private / final methods and classes were forced to wait for an official patch that might never come? I have.
  • Wanted to use a library for a slightly different use case than was imagined by the authors but were unable to do so because of private / final methods and classes? I have.
  • Been disappointed, surprised or hurt by a library etc. that was overly permissive in it's extensibility? I have not.

These are the three biggest rationalizations I've heard for marking methods private by default:

Rationalization #1: It's unsafe and there's no reason to override a specific method

I can't count the number of times I've been wrong about whether or not there will ever be a need to override a specific method I've written. Having worked on several popular open source libs, I learned the hard way the true cost of marking things private. It often eliminates the only practical solution to unforseen problems or use cases. Conversely, I've never in 16+ years of professional development regretted marking a method protected instead of private for reasons related to API safety. When a developer chooses to extend a class and override a method, they are consciously saying "I know what I'm doing." and for the sake of productivity that should be enough. period. If it's dangerous, note it in the class/method Javadocs, don't just blindly slam the door shut.

Marking methods protected by default is a mitigation for one of the major issues in modern SW development: failure of imagination.

Rationalization #2: It keeps the public API / Javadocs clean

This one is more reasonable, and depending on the target audience it might even be the right thing to do, but it's worth considering what the cost of keeping the API "clean" actually is: extensibility. For the reasons mentioned above, it probably makes more sense to mark things protected by default just in case.

Rationalization #3: My software is commercial and I need to restrict it's use.

This is reasonable too, but as a consumer I'd go with the less restrictive competitor (assuming no significant quality differences exist) every time.

Never say never

I'm not saying never mark methods private. I'm saying the better rule of thumb is to "make methods protected unless there's a good reason not to".

This advice is best suited for those working on libraries or larger scale projects that have been broken into modules. For smaller or more monolithic projects it doesn't tend to matter as much since you control all the code anyway and it's easy to change the access level of your code if/when you need it. Even then though, I'd still give the same advice :-)

Add border-bottom to table row <tr>

Display the row as a block.

tr {
    display: block;
    border-bottom: 1px solid #000;
}

and to display alternate colors simply:

tr.oddrow {
    display: block;
    border-bottom: 1px solid #F00;
}

Difference between opening a file in binary vs text

The most important difference to be aware of is that with a stream opened in text mode you get newline translation on non-*nix systems (it's also used for network communications, but this isn't supported by the standard library). In *nix newline is just ASCII linefeed, \n, both for internal and external representation of text. In Windows the external representation often uses a carriage return + linefeed pair, "CRLF" (ASCII codes 13 and 10), which is converted to a single \n on input, and conversely on output.


From the C99 standard (the N869 draft document), §7.19.2/2,

A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one- to-one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.

And in §7.19.3/2

Binary files are not truncated, except as defined in 7.19.5.3. Whether a write on a text stream causes the associated file to be truncated beyond that point is implementation- defined.

About use of fseek, in §7.19.9.2/4:

For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET.

About use of ftell, in §17.19.9.4:

The ftell function obtains the current value of the file position indicator for the stream pointed to by stream. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by the fseek function for returning the file position indicator for the stream to its position at the time of the ftell call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.

I think that’s the most important, but there are some more details.

Count specific character occurrences in a string

Thanks, @guffa. The ability to do it in one line, or even within a longer statement in .NET is very handy. This VB.NET example counts the number of LineFeed characters:

Dim j As Integer = MyString.Count(Function(c As Char) c = vbLf)

j returns the number of LineFeeds in MyString.

How to know elastic search installed version from kibana?

You can Try this, After starting Service of elasticsearch Type below line in your browser.

         localhost:9200

     It will give Output Something like that,

          {
           "status" : 200,
           "name" : "Hypnotia",
           "cluster_name" : "elasticsearch",
           "version" : {
           "number" : "1.7.1",
           "build_hash" : "b88f43fc40b0bcd7f173a1f9ee2e97816de80b19",
           "build_timestamp" : "2015-07-29T09:54:16Z",
           "build_snapshot" : false,
            "lucene_version" : "4.10.4"
                  },
            "tagline" : "You Know, for Search"
                  }

How to export a table dataframe in PySpark to csv?

If data frame fits in a driver memory and you want to save to local files system you can convert Spark DataFrame to local Pandas DataFrame using toPandas method and then simply use to_csv:

df.toPandas().to_csv('mycsv.csv')

Otherwise you can use spark-csv:

  • Spark 1.3

    df.save('mycsv.csv', 'com.databricks.spark.csv')
    
  • Spark 1.4+

    df.write.format('com.databricks.spark.csv').save('mycsv.csv')
    

In Spark 2.0+ you can use csv data source directly:

df.write.csv('mycsv.csv')

Delete entire row if cell contains the string X

Ok I know this for VBA but if you need to do this for a once off bulk delete you can use the following Excel functionality: http://blog.contextures.com/archives/2010/06/21/fast-way-to-find-and-delete-excel-rows/ Hope this helps anyone

Example looking for the string "paper":

  1. In the Find and Replace dialog box, type "paper" in the Find What box.
  2. Click Find All, to see a list of cells with "paper"
  3. Select an item in the list, and press Ctrl+A, to select the entire list, and to select all the "paper" cells on the worksheet.
  4. On the Ribbon's Home tab, click Delete, and then click Delete Sheet Rows.

How do I print a double value with full precision using cout?

The iostreams way is kind of clunky. I prefer using boost::lexical_cast because it calculates the right precision for me. And it's fast, too.

#include <string>
#include <boost/lexical_cast.hpp>

using boost::lexical_cast;
using std::string;

double d = 3.14159265358979;
cout << "Pi: " << lexical_cast<string>(d) << endl;

Output:

Pi: 3.14159265358979

How to create a HTTP server in Android?

Consider this one: https://github.com/NanoHttpd/nanohttpd. Very small, written in Java. I used it without any problem.

I want to load another HTML page after a specific amount of time

<script>
    setTimeout(function(){
        window.location.href = 'form2.html';
    }, 5000);
</script>

And for home page add only '/'

<script>
    setTimeout(function(){
        window.location.href = '/';
    }, 5000);
</script>

Where to change the value of lower_case_table_names=2 on windows xampp

On linux I cannot set lower_case_table_names to 2 (it reverts to 0), but I can set it to 1.

Before changing this setting, do a complete dump of all databases, and drop all databases. You won't be able to drop them after setting lower_case_table_names to 1, because any uppercase characters in database or table names will prevent them from being referenced.

Then set lower_case_table_names to 1, restart MySQL, and re-load your data, which will convert everything to lowercase, including any subsequent queries made.

How do I convert two lists into a dictionary?

>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> dict(zip(keys, values))
{'food': 'spam', 'age': 42, 'name': 'Monty'}

How to set a binding in Code?

In addition to the answer of Dyppl, I think it would be nice to place this inside the OnDataContextChanged event:

private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    // Unforunately we cannot bind from the viewmodel to the code behind so easily, the dependency property is not available in XAML. (for some reason).
    // To work around this, we create the binding once we get the viewmodel through the datacontext.
    var newViewModel = e.NewValue as MyViewModel;

    var executablePathBinding = new Binding
    {
        Source = newViewModel,
        Path = new PropertyPath(nameof(newViewModel.ExecutablePath))
    };

    BindingOperations.SetBinding(LayoutRoot, ExecutablePathProperty, executablePathBinding);
}

We have also had cases were we just saved the DataContext to a local property and used that to access viewmodel properties. The choice is of course yours, I like this approach because it is more consistent with the rest. You can also add some validation, like null checks. If you actually change your DataContext around, I think it would be nice to also call:

BindingOperations.ClearBinding(myText, TextBlock.TextProperty);

to clear the binding of the old viewmodel (e.oldValue in the event handler).

How to check if an int is a null

primitives dont have null value. default have for an int is 0.

if(person.getId()==0){}

Default values for primitives in java:

Data Type   Default Value (for fields)

byte                0
short               0
int                 0
long            0L
float           0.0f
double          0.0d
char            '\u0000'
boolean         false

Objects have null as default value.

String (or any object)--->null

1.) I need to check if the object is not null; Is the following expression correct;

if (person == null){
}

the above piece of code checks if person is null. you need to do

if (person != null){ // checks if person is not null
}

and

if(person.equals(null))

The above code would throw NullPointerException when person is null.

XSS prevention in JSP/Servlet web application

My personal opinion is that you should avoid using JSP/ASP/PHP/etc pages. Instead output to an API similar to SAX (only designed for calling rather than handling). That way there is a single layer that has to create well formed output.

Fragment onCreateView and onActivityCreated called twice

Ok, Here's what I found out.

What I didn't understand is that all fragments that are attached to an activity when a config change happens (phone rotates) are recreated and added back to the activity. (which makes sense)

What was happening in the TabListener constructor was the tab was detached if it was found and attached to the activity. See below:

mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
    if (mFragment != null && !mFragment.isDetached()) {
        Log.d(TAG, "constructor: detaching fragment " + mTag);
        FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction();
        ft.detach(mFragment);
        ft.commit();
    }

Later in the activity onCreate the previously selected tab was selected from the saved instance state. See below:

if (savedInstanceState != null) {
    bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
    Log.d(TAG, "FragmentTabs.onCreate tab: " + savedInstanceState.getInt("tab"));
    Log.d(TAG, "FragmentTabs.onCreate number: " + savedInstanceState.getInt("number"));
}

When the tab was selected it would be reattached in the onTabSelected callback.

public void onTabSelected(Tab tab, FragmentTransaction ft) {
    if (mFragment == null) {
        mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
        Log.d(TAG, "onTabSelected adding fragment " + mTag);
        ft.add(android.R.id.content, mFragment, mTag);
    } else {
        Log.d(TAG, "onTabSelected attaching fragment " + mTag);
        ft.attach(mFragment);
    }
}

The fragment being attached is the second call to the onCreateView and onActivityCreated methods. (The first being when the system is recreating the acitivity and all attached fragments) The first time the onSavedInstanceState Bundle would have saved data but not the second time.

The solution is to not detach the fragment in the TabListener constructor, just leave it attached. (You still need to find it in the FragmentManager by it's tag) Also, in the onTabSelected method I check to see if the fragment is detached before I attach it. Something like this:

public void onTabSelected(Tab tab, FragmentTransaction ft) {
            if (mFragment == null) {
                mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
                Log.d(TAG, "onTabSelected adding fragment " + mTag);
                ft.add(android.R.id.content, mFragment, mTag);
            } else {

                if(mFragment.isDetached()) {
                    Log.d(TAG, "onTabSelected attaching fragment " + mTag);
                    ft.attach(mFragment);
                } else {
                    Log.d(TAG, "onTabSelected fragment already attached " + mTag);
                }
            }
        }

using scp in terminal

You can download in the current directory with a . :

cd # by default, goes to $HOME
scp me@host:/path/to/file .

or in you HOME directly with :

scp me@host:/path/to/file ~

WordPress asking for my FTP credentials to install plugins

On OSX, I used the following, and it worked:

sudo chown -R _www:_www {path to wordpress folder}

_www is the user that PHP runs under on the Mac.

(You may also need to chmod some folders too. I had done that first and it didn't fix it. It wasn't until I did the chown command that it worked, so I'm not sure if it was the chown command alone, or a combination of chmod and chown.)

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

How do I add PHP code/file to HTML(.html) files?

In order to use php in .html files, you must associate them with your PHP processor in your HTTP server's config file. In Apache, that looks like this:

AddHandler application/x-httpd-php .html

How to HTML encode/escape a string? Is there a built-in?

Checkout the Ruby CGI class. There are methods to encode and decode HTML as well as URLs.

CGI::escapeHTML('Usage: foo "bar" <baz>')
# => "Usage: foo &quot;bar&quot; &lt;baz&gt;"

How can I create a unique constraint on my column (SQL Server 2008 R2)?

Here's another way through the GUI that does exactly what your script does even though it goes through Indexes (not Constraints) in the object explorer.

  1. Right click on "Indexes" and click "New Index..." (note: this is disabled if you have the table open in design view)

enter image description here

  1. Give new index a name ("U_Name"), check "Unique", and click "Add..."

enter image description here

  1. Select "Name" column in the next windown

enter image description here

  1. Click OK in both windows

How to set background color of HTML element using css properties in JavaScript

Javascript:

document.getElementById("ID").style.background = "colorName"; //JS ID

document.getElementsByClassName("ClassName")[0].style.background = "colorName"; //JS Class

Jquery:

$('#ID/.className').css("background","colorName") // One style

$('#ID/.className').css({"background":"colorName","color":"colorname"}); //Multiple style

hash function for string

Wikipedia shows a nice string hash function called Jenkins One At A Time Hash. It also quotes improved versions of this hash.

uint32_t jenkins_one_at_a_time_hash(char *key, size_t len)
{
    uint32_t hash, i;
    for(hash = i = 0; i < len; ++i)
    {
        hash += key[i];
        hash += (hash << 10);
        hash ^= (hash >> 6);
    }
    hash += (hash << 3);
    hash ^= (hash >> 11);
    hash += (hash << 15);
    return hash;
}

Pure JavaScript Send POST Data Without a Form

You can use XMLHttpRequest, fetch API, ...

If you want to use XMLHttpRequest you can do the following

var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
    name: "Deska",
    email: "[email protected]",
    phone: "342234553"
 }));
xhr.onload = function() {
    var data = JSON.parse(this.responseText);
    console.log(data);
};

Or if you want to use fetch API

fetch(url, {
    method:"POST",
    body: JSON.stringify({
        name: "Deska",
        email: "[email protected]",
        phone: "342234553"
        })
    })
    .then(result => {
        // do something with the result
        console.log("Completed with result:", result);
    });

rm: cannot remove: Permission denied

The code says everything:

max@serv$ chmod 777 .

Okay, it doesn't say everything.

In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.

Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.

How to delete object?

What you're asking is not possible. There is no mechanism in .Net that would set all references to some object to null.

And I think that the fact that you're trying to do this indicates some sort of design problem. You should probably think about the underlying problem and solve it in another way (the other answers here suggest some options).

how to reference a YAML "setting" from elsewhere in the same YAML file?

Yes, using custom tags. Example in Python, making the !join tag join strings in an array:

import yaml

## define custom tag handler
def join(loader, node):
    seq = loader.construct_sequence(node)
    return ''.join([str(i) for i in seq])

## register the tag handler
yaml.add_constructor('!join', join)

## using your sample data
yaml.load("""
paths:
    root: &BASE /path/to/root/
    patha: !join [*BASE, a]
    pathb: !join [*BASE, b]
    pathc: !join [*BASE, c]
""")

Which results in:

{
    'paths': {
        'patha': '/path/to/root/a',
        'pathb': '/path/to/root/b',
        'pathc': '/path/to/root/c',
        'root': '/path/to/root/'
     }
}

The array of arguments to !join can have any number of elements of any data type, as long as they can be converted to string, so !join [*a, "/", *b, "/", *c] does what you would expect.

Migrating from VMWARE to VirtualBox

I will suggest something totally different, we used it at work for many years ago on real computers and it worked perfect.

Boot both old and new machine on linux rescue Cd.

read the disk from one, and write it down to the other one, block by block, effectively copying the dist over the network.

You have to play around a little bit with the command line, but it worked so well that both machine complained about IP-conflict when they both booted :-) :-)

cat /dev/sda | ssh user@othermachine cat - > /dev/sda

How to return a 200 HTTP Status Code from ASP.NET MVC 3 controller

The way to do this in .NET Core is (at the time of writing) as follows:

public async Task<IActionResult> YourAction(YourModel model)
{
    if (ModelState.IsValid)
    {
        return StatusCode(200);
    }

    return StatusCode(400);
}

The StatusCode method returns a type of StatusCodeResult which implements IActionResult and can thus be used as a return type of your action.

As a refactor, you could improve readability by using a cast of the HTTP status codes enum like:

return StatusCode((int)HttpStatusCode.OK);

Furthermore, you could also use some of the built in result types. For example:

return Ok(); // returns a 200
return BadRequest(ModelState); // returns a 400 with the ModelState as JSON

Ref. StatusCodeResult - https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.statuscoderesult?view=aspnetcore-2.1

How to open a new tab using Selenium WebDriver

The same example for Node.js:

var webdriver = require('selenium-webdriver');
...
driver = new webdriver.Builder().
                    withCapabilities(capabilities).
                    build();
...
driver.findElement(webdriver.By.tagName("body")).sendKeys(webdriver.Key.COMMAND + "t");

Create a simple HTTP server with Java?

A servlet container is definitely the way to go. If Tomcat or Jetty are too heavyweight for you, consider Winstone or TTiny.

Getting the parameters of a running JVM

You can use the JConsole command (or any other JMX client) to access that information.

Appending a list to a list of lists in R

The purrr package has a lot of handy functions for working on lists. The flatten command can clean up unwanted nesting.

resultsa <- list(1,2,3,4,5)
resultsb <- list(6,7,8,9,10)
resultsc <- list(11,12,13,14,15)

nested_outlist <- list(resultsa, resultsb, resultsc)
outlist <- purrr::flatten(nested_outlist)

Convert bytes to bits in python

Operations are much faster when you work at the integer level. In particular, converting to a string as suggested here is really slow.

If you want bit 7 and 8 only, use e.g.

val = (byte >> 6) & 3

(this is: shift the byte 6 bits to the right - dropping them. Then keep only the last two bits 3 is the number with the first two bits set...)

These can easily be translated into simple CPU operations that are super fast.

How to specify test directory for mocha?

I am on Windows 7 using node.js v0.10.0 and mocha v1.8.2 and npm v1.2.14. I was just trying to get mocha to use the path test/unit to find my tests, After spending to long and trying several things I landed,

Using the "test/unit/*.js" option does not work on windows. For good reasons that windows shell doesn't expand wildcards like unixen.

However using "test/unit" does work, without the file pattern. eg. "mocha test/unit" runs all files found in test/unit folder.

This only still runs one folder files as tests but you can pass multiple directory names as parameters.

Also to run a single test file you can specify the full path and filename. eg. "mocha test/unit/mytest1.js"

I actually setup in package.json for npm "scripts": { "test": "mocha test/unit" },

So that 'npm test' runs my unit tests.

How can I use Timer (formerly NSTimer) in Swift?

Repeated event

You can use a timer to do an action multiple times, as seen in the following example. The timer calls a method to update a label every half second.

enter image description here

Here is the code for that:

import UIKit

class ViewController: UIViewController {

    var counter = 0
    var timer = Timer()

    @IBOutlet weak var label: UILabel!

    // start timer
    @IBAction func startTimerButtonTapped(sender: UIButton) {
        timer.invalidate() // just in case this button is tapped multiple times

        // start the timer
        timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
    }

    // stop timer
    @IBAction func cancelTimerButtonTapped(sender: UIButton) {
        timer.invalidate()
    }

    // called every time interval from the timer
    func timerAction() {
        counter += 1
        label.text = "\(counter)"
    }
}

Delayed event

You can also use a timer to schedule a one time event for some time in the future. The main difference from the above example is that you use repeats: false instead of true.

timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(delayedAction), userInfo: nil, repeats: false)

The above example calls a method named delayedAction two seconds after the timer is set. It is not repeated, but you can still call timer.invalidate() if you need to cancel the event before it ever happens.

Notes

  • If there is any chance of starting your timer instance multiple times, be sure that you invalidate the old timer instance first. Otherwise you lose the reference to the timer and you can't stop it anymore. (see this Q&A)
  • Don't use timers when they aren't needed. See the timers section of the Energy Efficiency Guide for iOS Apps.

Related

Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

Truncate the tables and then try adding the FK Constraint.

I know this solution is a bit awkward but it does work 100%. But I agree that this is not an ideal solution to deal with problem, but I hope it helps.

AcquireConnection method call to the connection manager <Excel Connection Manager> failed with error code 0xC0202009

In order to resolve this issue make all your data flow tasks in one sequence. It means it should not execute parallel. One data flow task sequence should contain only one data flow task and for this another data flow task as sequence.

Ex:-

enter image description here

How to remove unused imports from Eclipse

Not to reorganize imports (not to unfold .* and not to reorder lines) to have least VCS changeset
you can use custom eclipse clenup as this answer suggests

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

You can match those three groups separately, and make sure that they all present. Also, [^\w] seems a bit too broad, but if that's what you want you might want to replace it with \W.

Reference an Element in a List of Tuples

All of the other answers here are correct but do not explain why what you were trying was wrong. When you do myList[i[0]] you are telling Python that i is a tuple and you want the value or the first element of tuple i as the index for myList.

In the majority of programming languages when you need to access a nested data type (such as arrays, lists, or tuples), you append the brackets to get to the innermost item. The first bracket gives you the location of the tuple in your list. The second bracket gives you the location of the item in the tuple.

This is a quick rudimentary example that I came up with:

info = [ ( 1, 2), (3, 4), (5, 6) ]

info[0][0] == 1
info[0][1] == 2
info[1][0] == 3
info[1][1] == 4
info[2][0] == 5
info[2][1] == 6

Why is __init__() always called after __new__()?

To quote the documentation:

Typical implementations create a new instance of the class by invoking the superclass's __new__() method using "super(currentclass, cls).__new__(cls[, ...])"with appropriate arguments and then modifying the newly-created instance as necessary before returning it.

...

If __new__() does not return an instance of cls, then the new instance's __init__() method will not be invoked.

__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation.

How to select Python version in PyCharm?

File -> Settings

Preferences->Project Interpreter->Python Interpreters

If it's not listed add it.

enter image description here

How to get screen dimensions as pixels in Android

I found this did the trick.

Rect dim = new Rect();
getWindowVisibleDisplayFrame(dim);

Accept function as parameter in PHP

PHP VERSION >= 5.3.0

Example 1: basic

function test($test_param, $my_function) {
    return $my_function($test_param);
}

test("param", function($param) {
    echo $param;
}); //will echo "param"

Example 2: std object

$obj = new stdClass();
$obj->test = function ($test_param, $my_function) {
    return $my_function($test_param);
};

$test = $obj->test;
$test("param", function($param) {
    echo $param;
});

Example 3: non static class call

class obj{
    public function test($test_param, $my_function) {
        return $my_function($test_param);
    }
}

$obj = new obj();
$obj->test("param", function($param) {
    echo $param;
});

Example 4: static class call

class obj {
    public static function test($test_param, $my_function) {
        return $my_function($test_param);
    }
}

obj::test("param", function($param) {
    echo $param;
});

IDEA: javac: source release 1.7 requires target release 1.7

You need to change Java compiler version in in build config.

enter image description here

Haversine Formula in Python (Bearing and Distance between two GPS points)

There is also a vectorized implementation, which allows to use 4 numpy arrays instead of scalar values for coordinates:

def distance(s_lat, s_lng, e_lat, e_lng):

   # approximate radius of earth in km
   R = 6373.0

   s_lat = s_lat*np.pi/180.0                      
   s_lng = np.deg2rad(s_lng)     
   e_lat = np.deg2rad(e_lat)                       
   e_lng = np.deg2rad(e_lng)  

   d = np.sin((e_lat - s_lat)/2)**2 + np.cos(s_lat)*np.cos(e_lat) * np.sin((e_lng - s_lng)/2)**2

   return 2 * R * np.arcsin(np.sqrt(d))

How to initialize weights in PyTorch?

Iterate over parameters

If you cannot use apply for instance if the model does not implement Sequential directly:

Same for all

# see UNet at https://github.com/milesial/Pytorch-UNet/tree/master/unet


def init_all(model, init_func, *params, **kwargs):
    for p in model.parameters():
        init_func(p, *params, **kwargs)

model = UNet(3, 10)
init_all(model, torch.nn.init.normal_, mean=0., std=1) 
# or
init_all(model, torch.nn.init.constant_, 1.) 

Depending on shape

def init_all(model, init_funcs):
    for p in model.parameters():
        init_func = init_funcs.get(len(p.shape), init_funcs["default"])
        init_func(p)

model = UNet(3, 10)
init_funcs = {
    1: lambda x: torch.nn.init.normal_(x, mean=0., std=1.), # can be bias
    2: lambda x: torch.nn.init.xavier_normal_(x, gain=1.), # can be weight
    3: lambda x: torch.nn.init.xavier_uniform_(x, gain=1.), # can be conv1D filter
    4: lambda x: torch.nn.init.xavier_uniform_(x, gain=1.), # can be conv2D filter
    "default": lambda x: torch.nn.init.constant(x, 1.), # everything else
}

init_all(model, init_funcs)

You can try with torch.nn.init.constant_(x, len(x.shape)) to check that they are appropriately initialized:

init_funcs = {
    "default": lambda x: torch.nn.init.constant_(x, len(x.shape))
}

Property getters and setters

Setters and Getters apply to computed properties; such properties do not have storage in the instance - the value from the getter is meant to be computed from other instance properties. In your case, there is no x to be assigned.

Explicitly: "How can I do this without explicit backing ivars". You can't - you'll need something to backup the computed property. Try this:

class Point {
  private var _x: Int = 0             // _x -> backingX
  var x: Int {
    set { _x = 2 * newValue }
    get { return _x / 2 }
  }
}

Specifically, in the Swift REPL:

 15> var pt = Point()
pt: Point = {
  _x = 0
}
 16> pt.x = 10
 17> pt
$R3: Point = {
  _x = 20
}
 18> pt.x
$R4: Int = 10

Invariant Violation: Objects are not valid as a React child

I too was getting this "Objects are not valid as a React child" error and for me the cause was due to calling an asynchronous function in my JSX. See below.

class App extends React.Component {
    showHello = async () => {
        const response = await someAPI.get("/api/endpoint");

        // Even with response ignored in JSX below, this JSX is not immediately returned, 
        // causing "Objects are not valid as a React child" error.
        return (<div>Hello!</div>);
    }

    render() {
        return (
            <div>
                {this.showHello()}
            </div>
        );
    }
}

What I learned is that asynchronous rendering is not supported in React. The React team is working on a solution as documented here.

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

As described in the API of java.sql.PreparedStatement.setBinaryStream() it is available since 1.6 so it is a JDBC 4.0 API! You use a JDBC 3 Driver so this method is not available!

How to print something when running Puppet client?

You can run the client like this ...

puppet agent --test --debug --noop

with that command you get all the output you can get.

excerpt puppet agent help
* --test:
  Enable the most common options used for testing. These are 'onetime',
  'verbose', 'ignorecache', 'no-daemonize', 'no-usecacheonfailure',
  'detailed-exitcodes', 'no-splay', and 'show_diff'.

NOTE: No need to include --verbose when you use the --test|-t switch, it implies the --verbose as well.

What is the difference between Hibernate and Spring Data JPA

Hibernate is implementation of "JPA" which is a specification for Java objects in Database.

I would recommend to use w.r.t JPA as you can switch between different ORMS.

When you use JDBC then you need to use SQL Queries, so if you are proficient in SQL then go for JDBC.

How do I print out the contents of a vector?

I see two problems. As pointed out in

for (x = 17; isalpha(firstsquare); x++)

there's either an infinite loop or never executed at all, and also in if (entrance == 'S') if the entrance character is different than 'S' then nothing in pushed to the path vector, making it empty and thus printing nothing on screen. You can test the latter checking for path.empty() or printing path.size().

Either way, wouldn't it be better to use a string instead of a vector? You can access the string contents like an array as well, seek characters, extract substrings and print the string easily (without a loop).

Doing it all with strings might be the way to have it written in a less convoluted way and make it easier to spot the problem.

How can I clear the SQL Server query cache?

Here is some good explaination. check out it.

http://www.mssqltips.com/tip.asp?tip=1360

CHECKPOINT; 
GO 
DBCC DROPCLEANBUFFERS; 
GO

From the linked article:

If all of the performance testing is conducted in SQL Server the best approach may be to issue a CHECKPOINT and then issue the DBCC DROPCLEANBUFFERS command. Although the CHECKPOINT process is an automatic internal system process in SQL Server and occurs on a regular basis, it is important to issue this command to write all of the dirty pages for the current database to disk and clean the buffers. Then the DBCC DROPCLEANBUFFERS command can be executed to remove all buffers from the buffer pool.

Create a batch file to run an .exe with an additional parameter

Found another solution for the same. It will be more helpful.

START C:\"Program Files (x86)"\Test\"Test Automation"\finger.exe ConfigFile="C:\Users\PCName\Desktop\Automation\Documents\Validation_ZoneWise_Default.finger.Config"

finger.exe is a parent program that is calling config solution. Note: if your path folder name consists of spaces, then do not forget to add "".

How can I list all collections in the MongoDB shell?

You can use show tables or show collections.

Mongoose and multiple database in single node.js project

Pretty late but this might help someone. The current answers assumes you are using the same file for your connections and models.

In real life, there is a high chance that you are splitting your models into different files. You can use something like this in your main file:

mongoose.connect('mongodb://localhost/default');

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
  console.log('connected');
});

which is just how it is described in the docs. And then in your model files, do something like the following:

import mongoose, { Schema } from 'mongoose';

const userInfoSchema = new Schema({
  createdAt: {
    type: Date,
    required: true,
    default: new Date(),
  },
  // ...other fields
});

const myDB = mongoose.connection.useDb('myDB');

const UserInfo = myDB.model('userInfo', userInfoSchema);

export default UserInfo;

Where myDB is your database name.

Curl Command to Repeat URL Request

for i in `seq 1 20`; do curl http://url; done

Or if you want to get timing information back, use ab:

ab -n 20 http://url/

How to make 'submit' button disabled?

Here is a working example (you'll have to trust me that there's a submit() method on the controller - it prints an Object, like {user: 'abc'} if 'abc' is entered in the input field):

<form #loginForm="ngForm" (ngSubmit)="submit(loginForm.value)">
    <input type="text" name="user" ngModel required>
    <button  type="submit"  [disabled]="loginForm.invalid">
        Submit
    </button>
</form>

As you can see:

  • don't use loginForm.form, just use loginForm
  • loginForm.invalid works as well as !loginForm.valid
  • if you want submit() to be passed the correct value(s), the input element should have name and ngModel attributes

Also, this is when you're NOT using the new FormBuilder, which I recommend. Things are very different when using FormBuilder.

How do I create 7-Zip archives with .NET?

EggCafe 7Zip cookie example This is an example (zipping cookie) with the DLL of 7Zip.

CodePlex Wrapper This is an open source project that warp zipping function of 7z.

7Zip SDK The official SDK for 7zip (C, C++, C#, Java) <---My suggestion

.Net zip library by SharpDevelop.net

CodeProject example with 7zip

SharpZipLib Many zipping

How do I compile and run a program in Java on my Mac?

Download and install Eclipse, and you're good to go.
http://www.eclipse.org/downloads/

Apple provides its own version of Java, so make sure it's up-to-date.
http://developer.apple.com/java/download/


Eclipse is an integrated development environment. It has many features, but the ones that are relevant for you at this stage is:

  • The source code editor
    • With syntax highlighting, colors and other visual cues
    • Easy cross-referencing to the documentation to facilitate learning
  • Compiler
    • Run the code with one click
    • Get notified of errors/mistakes as you go

As you gain more experience, you'll start to appreciate the rest of its rich set of features.

How to access the ith column of a NumPy multidimensional array?

Although the question has been answered, let me mention some nuances.

Let's say you are interested in the first column of the array

arr = numpy.array([[1, 2],
                   [3, 4],
                   [5, 6]])

As you already know from other answers, to get it in the form of "row vector" (array of shape (3,)), you use slicing:

arr_col1_view = arr[:, 1]         # creates a view of the 1st column of the arr
arr_col1_copy = arr[:, 1].copy()  # creates a copy of the 1st column of the arr

To check if an array is a view or a copy of another array you can do the following:

arr_col1_view.base is arr  # True
arr_col1_copy.base is arr  # False

see ndarray.base.

Besides the obvious difference between the two (modifying arr_col1_view will affect the arr), the number of byte-steps for traversing each of them is different:

arr_col1_view.strides[0]  # 8 bytes
arr_col1_copy.strides[0]  # 4 bytes

see strides and this answer.

Why is this important? Imagine that you have a very big array A instead of the arr:

A = np.random.randint(2, size=(10000, 10000), dtype='int32')
A_col1_view = A[:, 1] 
A_col1_copy = A[:, 1].copy()

and you want to compute the sum of all the elements of the first column, i.e. A_col1_view.sum() or A_col1_copy.sum(). Using the copied version is much faster:

%timeit A_col1_view.sum()  # ~248 µs
%timeit A_col1_copy.sum()  # ~12.8 µs

This is due to the different number of strides mentioned before:

A_col1_view.strides[0]  # 40000 bytes
A_col1_copy.strides[0]  # 4 bytes

Although it might seem that using column copies is better, it is not always true for the reason that making a copy takes time too and uses more memory (in this case it took me approx. 200 µs to create the A_col1_copy). However if we needed the copy in the first place, or we need to do many different operations on a specific column of the array and we are ok with sacrificing memory for speed, then making a copy is the way to go.

In the case we are interested in working mostly with columns, it could be a good idea to create our array in column-major ('F') order instead of the row-major ('C') order (which is the default), and then do the slicing as before to get a column without copying it:

A = np.asfortranarray(A)   # or np.array(A, order='F')
A_col1_view = A[:, 1]
A_col1_view.strides[0]     # 4 bytes

%timeit A_col1_view.sum()  # ~12.6 µs vs ~248 µs

Now, performing the sum operation (or any other) on a column-view is as fast as performing it on a column copy.

Finally let me note that transposing an array and using row-slicing is the same as using the column-slicing on the original array, because transposing is done by just swapping the shape and the strides of the original array.

A[:, 1].strides[0]    # 40000 bytes
A.T[1, :].strides[0]  # 40000 bytes

how to find my angular version in my project?

For Angular 1 or 2 (but not for Angular 4+):

You can also open the console and go to the element tab on the developer tools of whatever browser you use.

Or

Type angular.version to access the Javascript object that holds angular version.

For Angular 4+ There is are the number of ways as listed below :

Write below code in the command prompt/or in the terminal in the VS Code.

  1. ng version or ng --version (See the attachment for the reference.)
  2. ng v
  3. ng -v

In the terminal you can find the angular version as shown in the attached image : enter image description here

  1. You can also open the console and go to the element tab on the developer tools of whatever browser you use. As displayed in the below image :

enter image description here

5.Find the package.json file, You will find all the installed packages and their version.

  1. declare the variable named as 'VERSION', Import the dependencies.
import { VERSION } from '@angular/core';

// To display the version in the console.

console.log(VERSION.full); 

Fit Image in ImageButton in Android

Refer below link and try to find what you really want:

ImageView.ScaleType CENTER Center the image in the view, but perform no scaling.

ImageView.ScaleType CENTER_CROP Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding).

ImageView.ScaleType CENTER_INSIDE Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding).

ImageView.ScaleType FIT_CENTER Scale the image using CENTER.

ImageView.ScaleType FIT_END Scale the image using END.

ImageView.ScaleType FIT_START Scale the image using START.

ImageView.ScaleType FIT_XY Scale the image using FILL.

ImageView.ScaleType MATRIX Scale using the image matrix when drawing.

https://developer.android.com/reference/android/widget/ImageView.ScaleType.html

Powershell remoting with ip-address as target

The error message is giving you most of what you need. This isn't just about the TrustedHosts list; it's saying that in order to use an IP address with the default authentication scheme, you have to ALSO be using HTTPS (which isn't configured by default) and provide explicit credentials. I can tell you're at least not using SSL, because you didn't use the -UseSSL switch.

Note that SSL/HTTPS is not configured by default - that's an extra step you'll have to take. You can't just add -UseSSL.

The default authentication mechanism is Kerberos, and it wants to see real host names as they appear in AD. Not IP addresses, not DNS CNAME nicknames. Some folks will enable Basic authentication, which is less picky - but you should also set up HTTPS since you'd otherwise pass credentials in cleartext. Enable-PSRemoting only sets up HTTP.

Adding names to your hosts file won't work. This isn't an issue of name resolution; it's about how the mutual authentication between computers is carried out.

Additionally, if the two computers involved in this connection aren't in the same AD domain, the default authentication mechanism won't work. Read "help about_remote_troubleshooting" for information on configuring non-domain and cross-domain authentication.

From the docs at http://technet.microsoft.com/en-us/library/dd347642.aspx

HOW TO USE AN IP ADDRESS IN A REMOTE COMMAND
-----------------------------------------------------
    ERROR:  The WinRM client cannot process the request. If the
    authentication scheme is different from Kerberos, or if the client
    computer is not joined to a domain, then HTTPS transport must be used
    or the destination machine must be added to the TrustedHosts
    configuration setting.

The ComputerName parameters of the New-PSSession, Enter-PSSession and
Invoke-Command cmdlets accept an IP address as a valid value. However,
because Kerberos authentication does not support IP addresses, NTLM
authentication is used by default whenever you specify an IP address. 

When using NTLM authentication, the following procedure is required
for remoting.

1. Configure the computer for HTTPS transport or add the IP addresses
   of the remote computers to the TrustedHosts list on the local
   computer.

   For instructions, see "How to Add a Computer to the TrustedHosts
   List" below.


2. Use the Credential parameter in all remote commands.

   This is required even when you are submitting the credentials
   of the current user.

How can I pass an argument to a PowerShell script?

Let PowerShell analyze and decide the data type. It internally uses a 'Variant' for this.

And generally it does a good job...

param($x)
$iTunes = New-Object -ComObject iTunes.Application
if ($iTunes.playerstate -eq 1)
{
    $iTunes.PlayerPosition = $iTunes.PlayerPosition + $x
}

Or if you need to pass multiple parameters:

param($x1, $x2)
$iTunes = New-Object -ComObject iTunes.Application
if ($iTunes.playerstate -eq 1)
{
    $iTunes.PlayerPosition = $iTunes.PlayerPosition + $x1
    $iTunes.<AnyProperty>  = $x2
}

How to animate RecyclerView items when they appear

You can add a android:layoutAnimation="@anim/rv_item_animation" attribute to RecyclerView like this:

<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"                                        
    android:layoutAnimation="@anim/layout_animation_fall_down"
    />

thanks for the excellent article here: https://proandroiddev.com/enter-animation-using-recyclerview-and-layoutanimation-part-1-list-75a874a5d213

How abstraction and encapsulation differ?

As I knowit, encapsulation is hiding data of classes in themselves, and only making it accessible via setters / getters, if they must be accessed from the outer world.

Abstraction is the class design for itself.

Means, how You create Your class tree, which methods are general ones, which are inherited, which can be overridden,which attributes are only on private level, or on protected, how Do You build up Your class inheritance tree, Do You use final classes, abtract classes, interface-implementation.

Abstraction is more placed the oo-design phase, while encapsulation also enrolls into developmnent-phase.

How can I center an image in Bootstrap?

Since the img is an inline element, Just use text-center on it's container. Using mx-auto will center the container (column) too.

<div class="row">
    <div class="col-4 mx-auto text-center">
        <img src="..">
    </div>
</div>

By default, images are display:inline. If you only want the center the image (and not the other column content), make the image display:block using the d-block class, and then mx-auto will work.

<div class="row">
  <div class="col-4">
    <img class="mx-auto d-block" src="..">
  </div>
</div>

Demo: http://codeply.com/go/iakGGLdB8s

Hashcode and Equals for Hashset

Because in 2nd case you adding same reference twice and HashSet have check against this in HashMap.put() on which HashSet is based:

        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }

As you can see, equals will be called only if hash of key being added equals to the key already present in set and references of these two are different.

Disable Logback in SpringBoot

If this error occurred in SpringBoot when you are trying to use log4j2 then do these steps:

  • Remove the jar from while packeging by adding this "excludeGroupIds log4j-slf4j-impl /excludeGroupIds"
  • Find out the which library is depends on "logback-classic" by using command "mvn dependecy:tree"
  • Wherever you find it exclude it from the dependency.

This error occurred because logback override the log4j2 changes. SO if you want to use log4j2 then you have to remove logback library and dependencies.

Hope this will help someone.

Prevent form submission on Enter key press

if(characterCode == 13)
{
    return false; // returning false will prevent the event from bubbling up.
}
else
{
    return true;
}

Ok, so imagine you have the following textbox in a form:

<input id="scriptBox" type="text" onkeypress="return runScript(event)" />

In order to run some "user defined" script from this text box when the enter key is pressed, and not have it submit the form, here is some sample code. Please note that this function doesn't do any error checking and most likely will only work in IE. To do this right you need a more robust solution, but you will get the general idea.

function runScript(e) {
    //See notes about 'which' and 'key'
    if (e.keyCode == 13) {
        var tb = document.getElementById("scriptBox");
        eval(tb.value);
        return false;
    }
}

returning the value of the function will alert the event handler not to bubble the event any further, and will prevent the keypress event from being handled further.

NOTE:

It's been pointed out that keyCode is now deprecated. The next best alternative which has also been deprecated.

Unfortunately the favored standard key, which is widely supported by modern browsers, has some dodgy behavior in IE and Edge. Anything older than IE11 would still need a polyfill.

Furthermore, while the deprecated warning is quite ominous about keyCode and which, removing those would represent a massive breaking change to untold numbers of legacy websites. For that reason, it is unlikely they are going anywhere anytime soon.

Get the date (a day before current time) in Bash

Try the below code , which takes care of the DST part as well.

if [ $(date +%w) -eq $(date -u +%w) ]; then
  tz=$(( 10#$gmthour - 10#$localhour ))
else
  tz=$(( 24 - 10#$gmthour + 10#$localhour ))
fi
echo $tz
myTime=`TZ=GMT+$tz date +'%Y%m%d'`

Courtsey Ansgar Wiechers

Create view with primary key?

This worked for me..

select ROW_NUMBER() over (order by column_name_of your choice ) as pri_key, the other columns of the view

Python - Extracting and Saving Video Frames

From here download this video so we have the same video file for the test. Make sure to have that mp4 file in the same directory of your python code. Then also make sure to run the python interpreter from the same directory.

Then modify the code, ditch waitKey that's wasting time also without a window it cannot capture the keyboard events. Also we print the success value to make sure it's reading the frames successfully.

import cv2
vidcap = cv2.VideoCapture('big_buck_bunny_720p_5mb.mp4')
success,image = vidcap.read()
count = 0
while success:
  cv2.imwrite("frame%d.jpg" % count, image)     # save frame as JPEG file      
  success,image = vidcap.read()
  print('Read a new frame: ', success)
  count += 1

How does that go?

Null pointer Exception on .setOnClickListener

android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Because Submit button is inside login_modal so you need to use loginDialog view to access button:

Submit = (Button)loginDialog.findViewById(R.id.Submit);

How to recover just deleted rows in mysql?

There is another solution, if you have binary logs active on your server you can use mysqlbinlog

generate a sql file with it

mysqlbinlog binary_log_file > query_log.sql

then search for your missing rows. If you don't have it active, no other solution. Make backups next time.

Spring RestTemplate timeout

Here are my 2 cents. Nothing new, but some explanations, improvements and newer code.

By default, RestTemplate has infinite timeout. There are two kinds of timeouts: connection timeout and read time out. For instance, I could connect to the server but I could not read data. The application was hanging and you have no clue what's going on.

I am going to use annotations, which these days are preferred over XML.

@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate() {

        var factory = new SimpleClientHttpRequestFactory();

        factory.setConnectTimeout(3000);
        factory.setReadTimeout(3000);

        return new RestTemplate(factory);
    }
}

Here we use SimpleClientHttpRequestFactory to set the connection and read time outs. It is then passed to the constructor of RestTemplate.

@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {

        return builder
                .setConnectTimeout(Duration.ofMillis(3000))
                .setReadTimeout(Duration.ofMillis(3000))
                .build();
    }
}

In the second solution, we use the RestTemplateBuilder. Also notice the parameters of the two methods: they take Duration. The overloaded methods that take directly milliseconds are now deprecated.

Edit Tested with Spring Boot 2.1.0 and Java 11.

Change a web.config programmatically with C# (.NET)

Here it is some code:

var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=...";
configuration.Save();

See more examples in this article, you may need to take a look to impersonation.

How can I align the columns of tables in Bash?

Below code has been tested and does exactly what is requested in the original question.

Parameters: %30s Column of 30 char and text right align. %10d integer notation, %10s will also work. Added clarification included on code comments.

stringarray[0]="a very long string.........."
# 28Char (max length for this column)
numberarray[0]=1122324333
# 10digits (max length for this column)
anotherfield[0]="anotherfield"
# 12Char (max length for this column)
stringarray[1]="a smaller string....."
numberarray[1]=123124343
anotherfield[1]="anotherfield"

printf "%30s %10d %13s" "${stringarray[0]}" ${numberarray[0]} "${anotherfield[0]}"
printf "\n"
printf "%30s %10d %13s" "${stringarray[1]}" ${numberarray[1]} "${anotherfield[1]}"
# a var string with spaces has to be quoted
printf "\n Next line will fail \n"      
printf "%30s %10d %13s" ${stringarray[0]} ${numberarray[0]} "${anotherfield[0]}"



  a very long string.......... 1122324333  anotherfield
         a smaller string.....  123124343  anotherfield

Using Exit button to close a winform program

You can also do like this:

private void button2_Click(object sender, EventArgs e)
{
    System.Windows.Forms.Application.ExitThread();
}

How to check if a date is in a given range?

Convert both dates to timestamps then do

pseudocode:

if date_from_user > start_date && date_from_user < end_date
    return true

A generic list of anonymous class

For your second example, where you have to initialize a new List<T>, one idea is to create an anonymous list, and then clear it.

var list = new[] { o, o1 }.ToList();
list.Clear();

//and you can keep adding.
while (....)
{
    ....
    list.Add(new { Id = x, Name = y });
    ....
}

Or as an extension method, should be easier:

public static List<T> GetEmptyListOfThisType<T>(this T item)
{
    return new List<T>();
}

//so you can call:
var list = new { Id = 0, Name = "" }.GetEmptyListOfThisType();

Or probably even shorter,

var list = new int[0].Select(x => new { Id = 0, Name = "" }).Tolist();

Create Carriage Return in PHP String?

$postfields["message"] = "This is a sample ticket opened by the API\rwith a carriage return";

Execute a command line binary with Node.js

If you don't mind a dependency and want to use promises, child-process-promise works:

installation

npm install child-process-promise --save

exec Usage

var exec = require('child-process-promise').exec;

exec('echo hello')
    .then(function (result) {
        var stdout = result.stdout;
        var stderr = result.stderr;
        console.log('stdout: ', stdout);
        console.log('stderr: ', stderr);
    })
    .catch(function (err) {
        console.error('ERROR: ', err);
    });

spawn usage

var spawn = require('child-process-promise').spawn;

var promise = spawn('echo', ['hello']);

var childProcess = promise.childProcess;

console.log('[spawn] childProcess.pid: ', childProcess.pid);
childProcess.stdout.on('data', function (data) {
    console.log('[spawn] stdout: ', data.toString());
});
childProcess.stderr.on('data', function (data) {
    console.log('[spawn] stderr: ', data.toString());
});

promise.then(function () {
        console.log('[spawn] done!');
    })
    .catch(function (err) {
        console.error('[spawn] ERROR: ', err);
    });

Select Tag Helper in ASP.NET Core MVC

In Get:

public IActionResult Create()
{
    ViewData["Tags"] = new SelectList(_context.Tags, "Id", "Name");
    return View();
}

In Post:

var selectedIds= Request.Form["Tags"];

In View :

<label>Tags</label>
<select  asp-for="Tags"  id="Tags" name="Tags" class="form-control" asp-items="ViewBag.Tags" multiple></select>

How to dynamically insert a <script> tag via jQuery after page load?

Here's the correct way to do it with modern (2014) JQuery:

$(function () {
  $('<script>')
    .attr('type', 'text/javascript')
    .text('some script here')
    .appendTo('head');
})

or if you really want to replace a div you could do:

$(function () {
  $('<script>')
    .attr('type', 'text/javascript')
    .text('some script here')
    .replaceAll('#someelement');
});

"if not exist" command in batch file

When testing for directories remember that every directory contains two special files.

One is called '.' and the other '..'

. is the directory's own name while .. is the name of it's parent directory.

To avoid trailing backslash problems just test to see if the directory knows it's own name.

eg:

if not exist %temp%\buffer\. mkdir %temp%\buffer

Why do you need to put #!/bin/bash at the beginning of a script file?

Also you will see some other parameters after #!/bin/bash, for example
#!/bin/bash -v -x
read this to get more idea.
https://unix.stackexchange.com/questions/124272/what-do-the-arguments-v-and-x-mean-to-bash .

How do I change the font-size of an <option> element within <select>?

One solution could be to wrap the options inside optgroup:

_x000D_
_x000D_
optgroup { font-size:40px; }
_x000D_
<select>
  <optgroup>
    <option selected="selected" class="service-small">Service area?</option>
    <option class="service-small">Volunteering</option>
    <option class="service-small">Partnership &amp; Support</option>
    <option class="service-small">Business Services</option>
  </optgroup>
</select>
_x000D_
_x000D_
_x000D_

EditText request focus

Yes, I got the answer.. just simply edit the manifest file as:

        <activity android:name=".MainActivity"
        android:label="@string/app_name"
        android:windowSoftInputMode="stateAlwaysVisible" />

and set EditText.requestFocus() in onCreate()..

Thanks..