Programs & Examples On #Voronoi

A Voronoi diagram is a subdivision of space.

JQuery datepicker not working

after that all html we want to write these lines of code

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/base/jquery-ui.css" type="text/css" media="all">



<script>
$('#date').datepicker({
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    yearRange: "-100:+0",
    dateFormat: 'dd/mm/yy'

});
</script>

Python Progress Bar

@Massagran: It works well in my programs. Furthermore, we need to add a counter to indicate the loop times. This counter plays as the argument of the method update. For example: read all lines of a test file and treat them on something. Suppose that the function dosth() do not concern in the variable i.

lines = open(sys.argv[1]).readlines()
i = 0
widgets=[Percentage(), Bar()]
pbar = ProgressBar(widgets=widgets,maxval=len(lines)).start()
pbar.start()
for line in lines:<pre>
    dosth();
    i += 1
    pbar.update(i)</pre>
pbar.finish()

The variable i controls the status of pbar via the method update

Excel Reference To Current Cell

Several years too late:

Just for completeness I want to give yet another answer:

First, go to Excel-Options -> Formulas and enable R1C1 references. Then use

  =CELL("width", RC)

RC always refers the current Row, current Column, i.e. "this cell".

Rick Teachey's solution is basically a tweak to make the same possible in A1 reference style (see also GSerg's comment to Joey's answer and note his comment to Patrick McDonald's answer).

Cheers
:-)

Modulo operator in Python

When you have the expression:

a % b = c

It really means there exists an integer n that makes c as small as possible, but non-negative.

a - n*b = c

By hand, you can just subtract 2 (or add 2 if your number is negative) over and over until the end result is the smallest positive number possible:

  3.14 % 2
= 3.14 - 1 * 2
= 1.14

Also, 3.14 % 2 * pi is interpreted as (3.14 % 2) * pi. I'm not sure if you meant to write 3.14 % (2 * pi) (in either case, the algorithm is the same. Just subtract/add until the number is as small as possible).

HQL ERROR: Path expected for join

You need to name the entity that holds the association to User. For example,

... INNER JOIN ug.user u ...

That's the "path" the error message is complaining about -- path from UserGroup to User entity.

Hibernate relies on declarative JOINs, for which the join condition is declared in the mapping metadata. This is why it is impossible to construct the native SQL query without having the path.

What is the difference between bindParam and bindValue?

Here are some I can think about :

  • With bindParam, you can only pass variables ; not values
  • with bindValue, you can pass both (values, obviously, and variables)
  • bindParam works only with variables because it allows parameters to be given as input/output, by "reference" (and a value is not a valid "reference" in PHP) : it is useful with drivers that (quoting the manual) :

support the invocation of stored procedures that return data as output parameters, and some also as input/output parameters that both send in data and are updated to receive it.

With some DB engines, stored procedures can have parameters that can be used for both input (giving a value from PHP to the procedure) and ouput (returning a value from the stored proc to PHP) ; to bind those parameters, you've got to use bindParam, and not bindValue.

Spring: How to inject a value to static field?

Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.

    @RestController 
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {

    @Value("${name}")//not necessary
    private String name;//not necessary

    private static String NAME_STATIC;

    @Value("${name}")
    public void setNameStatic(String name){
        PropertyController.NAME_STATIC = name;
    }
}

Extracting extension from filename in Python

New in version 3.4.

import pathlib

print(pathlib.Path('yourPath.example').suffix) # '.example'

I'm surprised no one has mentioned pathlib yet, pathlib IS awesome!

If you need all the suffixes (eg if you have a .tar.gz), .suffixes will return a list of them!

How to insert data into elasticsearch

Simple fundamentals, Elastic community has exposed indexing, searching, deleting operation as rest web service. You can interact elastic using curl or sense(chrome plugin) or any rest client like postman.

If you are just testing few commands, I would recommend can use of sense chrome plugin which has simple UI and pretty mature plugin now.

Do standard windows .ini files allow comments?

I have seen comments in INI files, so yes. Please refer to this Wikipedia article. I could not find an official specification, but that is the correct syntax for comments, as many game INI files had this as I remember.

Edit

The API returns the Value and the Comment (forgot to mention this in my reply), just construct and example INI file and call the API on this (with comments) and you can see how this is returned.

How do you allow spaces to be entered using scanf?

You can use this

char name[20];
scanf("%20[^\n]", name);

Or this

void getText(char *message, char *variable, int size){
    printf("\n %s: ", message);
    fgets(variable, sizeof(char) * size, stdin);
    sscanf(variable, "%[^\n]", variable);
}

char name[20];
getText("Your name", name, 20);

DEMO

Print an ArrayList with a for-each loop

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

class ArrLst{

    public static void main(String args[]){

        List l=new ArrayList();
        l.add(10);
        l.add(11);
        l.add(12);
        l.add(13);
        l.add(14);
        l.forEach((a)->System.out.println(a));
    }
}

Vue-router redirect on page not found (404)

@mani's Original answer is all you want, but if you'd also like to read it in official way, here's

Reference to Vue's official page:

https://router.vuejs.org/guide/essentials/history-mode.html#caveat

Inline style to act as :hover in CSS

I put together a quick solution for anyone wanting to create hover popups without CSS using the onmouseover and onmouseout behaviors.

http://jsfiddle.net/Lk9w1mkv/

<div style="position:relative;width:100px;background:#ddffdd;overflow:hidden;" onmouseover="this.style.overflow='';" onmouseout="this.style.overflow='hidden';">first hover<div style="width:100px;position:absolute;top:5px;left:110px;background:white;border:1px solid gray;">stuff inside</div></div>

Send Post Request with params using Retrofit

build.gradle

      compile 'com.google.code.gson:gson:2.6.2'

      compile 'com.squareup.retrofit2:retrofit:2.1.0'// compulsory

      compile 'com.squareup.retrofit2:converter-gson:2.1.0' //for retrofit conversion

Login APi Put Two Parameters

    {
        "UserId": "1234",
        "Password":"1234"
    }

Login Response

    {
        "UserId": "1234",
        "FirstName": "Keshav",
        "LastName": "Gera",
        "ProfilePicture": "312.113.221.1/GEOMVCAPI/Files/1.500534651736E12p.jpg"
    }

APIClient.java

    import retrofit2.Retrofit;
    import retrofit2.converter.gson.GsonConverterFactory;

    class APIClient {

        public static final String BASE_URL = "Your Base Url ";
        private static Retrofit retrofit = null;

        public static Retrofit getClient() {
            if (retrofit == null) {
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
            return retrofit;
        }
    }

APIInterface interface

    interface APIInterface {

        @POST("LoginController/Login")
        Call<LoginResponse> createUser(@Body LoginResponse login);
    }

Login Pojo

    package pojos;

    import com.google.gson.annotations.SerializedName;

    public class LoginResponse {


        @SerializedName("UserId")
        public String UserId;
        @SerializedName("FirstName")
        public String FirstName;
        @SerializedName("LastName")
        public String LastName;
        @SerializedName("ProfilePicture")
        public String ProfilePicture;
        @SerializedName("Password")
        public String Password;
        @SerializedName("ResponseCode")
        public String ResponseCode;
        @SerializedName("ResponseMessage")
        public String ResponseMessage;

        public LoginResponse(String UserId, String Password) {
            this.UserId = UserId;
            this.Password = Password;
        }

        public String getUserId() {
            return UserId;
        }

        public String getFirstName() {
            return FirstName;
        }

        public String getLastName() {
            return LastName;
        }

        public String getProfilePicture() {
            return ProfilePicture;
        }

        public String getResponseCode() {
            return ResponseCode;
        }

        public String getResponseMessage() {
            return ResponseMessage;
        }
    }

MainActivity

    package com.keshav.retrofitloginexampleworkingkeshav;

    import android.app.Dialog;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    import pojos.LoginResponse;
    import retrofit2.Call;
    import retrofit2.Callback;
    import retrofit2.Response;
    import utilites.CommonMethod;

    public class MainActivity extends AppCompatActivity {

        TextView responseText;
        APIInterface apiInterface;

        Button loginSub;
        EditText et_Email;
        EditText et_Pass;
        private Dialog mDialog;
        String userId;
        String password;

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

            apiInterface = APIClient.getClient().create(APIInterface.class);

            loginSub = (Button) findViewById(R.id.loginSub);
            et_Email = (EditText) findViewById(R.id.edtEmail);
            et_Pass = (EditText) findViewById(R.id.edtPass);

            loginSub.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (checkValidation()) {
                        if (CommonMethod.isNetworkAvailable(MainActivity.this))
                            loginRetrofit2Api(userId, password);
                        else
                            CommonMethod.showAlert("Internet Connectivity Failure", MainActivity.this);
                    }
                }
            });
        }

        private void loginRetrofit2Api(String userId, String password) {
            final LoginResponse login = new LoginResponse(userId, password);
            Call<LoginResponse> call1 = apiInterface.createUser(login);
            call1.enqueue(new Callback<LoginResponse>() {
                @Override
                public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                    LoginResponse loginResponse = response.body();

                    Log.e("keshav", "loginResponse 1 --> " + loginResponse);
                    if (loginResponse != null) {
                        Log.e("keshav", "getUserId          -->  " + loginResponse.getUserId());
                        Log.e("keshav", "getFirstName       -->  " + loginResponse.getFirstName());
                        Log.e("keshav", "getLastName        -->  " + loginResponse.getLastName());
                        Log.e("keshav", "getProfilePicture  -->  " + loginResponse.getProfilePicture());

                        String responseCode = loginResponse.getResponseCode();
                        Log.e("keshav", "getResponseCode  -->  " + loginResponse.getResponseCode());
                        Log.e("keshav", "getResponseMessage  -->  " + loginResponse.getResponseMessage());
                        if (responseCode != null && responseCode.equals("404")) {
                            Toast.makeText(MainActivity.this, "Invalid Login Details \n Please try again", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this, "Welcome " + loginResponse.getFirstName(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }

                @Override
                public void onFailure(Call<LoginResponse> call, Throwable t) {
                    Toast.makeText(getApplicationContext(), "onFailure called ", Toast.LENGTH_SHORT).show();
                    call.cancel();
                }
            });
        }

        public boolean checkValidation() {
            userId = et_Email.getText().toString();
            password = et_Pass.getText().toString();

            Log.e("Keshav", "userId is -> " + userId);
            Log.e("Keshav", "password is -> " + password);

            if (et_Email.getText().toString().trim().equals("")) {
                CommonMethod.showAlert("UserId Cannot be left blank", MainActivity.this);
                return false;
            } else if (et_Pass.getText().toString().trim().equals("")) {
                CommonMethod.showAlert("password Cannot be left blank", MainActivity.this);
                return false;
            }
            return true;
        }
    }

CommonMethod.java

    public class CommonMethod {


        public static final String DISPLAY_MESSAGE_ACTION =
                "com.codecube.broking.gcm";

        public static final String EXTRA_MESSAGE = "message";

        public  static boolean isNetworkAvailable(Context ctx) {
            ConnectivityManager connectivityManager
                    = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
        }

        public static void showAlert(String message, Activity context) {

            final AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage(message).setCancelable(false)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                        }
                    });
            try {
                builder.show();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

activity_main.xml

    <LinearLayout android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:orientation="vertical"
        xmlns:android="http://schemas.android.com/apk/res/android">

            <ImageView
                android:id="@+id/imgLogin"
                android:layout_width="200dp"
                android:layout_height="150dp"
                android:layout_gravity="center"
                android:layout_marginTop="20dp"
                android:padding="5dp"
                android:background="@mipmap/ic_launcher_round"
                />

            <TextView
                android:id="@+id/txtLogo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/imgLogin"
                android:layout_centerHorizontal="true"
                android:text="Holostik Track and Trace"
                android:textSize="20dp"
                android:visibility="gone" />

            <android.support.design.widget.TextInputLayout
                android:id="@+id/textInputLayout1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/box_layout_margin_left"
                android:layout_marginRight="@dimen/box_layout_margin_right"
                android:layout_marginTop="8dp"
                android:padding="@dimen/text_input_padding">

                <EditText
                    android:id="@+id/edtEmail"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    android:ems="10"
                    android:fontFamily="sans-serif"
                    android:gravity="top"
                    android:hint="Login ID"
                    android:maxLines="10"
                    android:paddingLeft="@dimen/edit_input_padding"
                    android:paddingRight="@dimen/edit_input_padding"
                    android:paddingTop="@dimen/edit_input_padding"
                    android:singleLine="true"></EditText>

            </android.support.design.widget.TextInputLayout>

            <android.support.design.widget.TextInputLayout
                android:id="@+id/textInputLayout2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/textInputLayout1"
                android:layout_marginLeft="@dimen/box_layout_margin_left"
                android:layout_marginRight="@dimen/box_layout_margin_right"
                android:padding="@dimen/text_input_padding">

                <EditText
                    android:id="@+id/edtPass"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:focusable="true"
                    android:fontFamily="sans-serif"
                    android:hint="Password"
                    android:inputType="textPassword"

                    android:singleLine="true" />

            </android.support.design.widget.TextInputLayout>

            <RelativeLayout
                android:id="@+id/rel12"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/textInputLayout2"
                android:layout_marginTop="10dp"
                android:layout_marginLeft="10dp"
                >

                <Button
                    android:id="@+id/loginSub"
                    android:layout_width="wrap_content"
                    android:layout_height="45dp"
                    android:layout_alignParentRight="true"
                    android:layout_centerVertical="true"
                    android:background="@drawable/border_button"
                    android:paddingLeft="30dp"
                    android:paddingRight="30dp"
                    android:layout_marginRight="10dp"
                    android:text="Login"
                    android:textColor="#ffffff" />    
            </RelativeLayout>

    </LinearLayout>

How to shift a column in Pandas DataFrame

If you don't want to lose the columns you shift past the end of your dataframe, simply append the required number first:

    offset = 5
    DF = DF.append([np.nan for x in range(offset)])
    DF = DF.shift(periods=offset)
    DF = DF.reset_index() #Only works if sequential index

How do I do a case-insensitive string comparison?

Assuming ASCII strings:

string1 = 'Hello'
string2 = 'hello'

if string1.lower() == string2.lower():
    print("The strings are the same (case insensitive)")
else:
    print("The strings are NOT the same (case insensitive)")

How can you determine a point is between two other points on a line segment?

Here's how I'd do it:

def distance(a,b):
    return sqrt((a.x - b.x)**2 + (a.y - b.y)**2)

def is_between(a,c,b):
    return distance(a,c) + distance(c,b) == distance(a,b)

How do I make a dictionary with multiple keys to one value?

If you're going to be adding to this dictionary frequently you'd want to take a class based approach, something similar to @Latty's answer in this SO question 2d-dictionary-with-many-keys-that-will-return-the-same-value.

However, if you have a static dictionary, and you need only access values by multiple keys then you could just go the very simple route of using two dictionaries. One to store the alias key association and one to store your actual data:

alias = {
    'a': 'id1',
    'b': 'id1',
    'c': 'id2',
    'd': 'id2'
}

dictionary = {
    'id1': 1,
    'id2': 2
}

dictionary[alias['a']]

If you need to add to the dictionary you could write a function like this for using both dictionaries:

def add(key, id, value=None)
    if id in dictionary:
        if key in alias:
            # Do nothing
            pass
        else:
            alias[key] = id
    else:
        dictionary[id] = value
        alias[key] = id

add('e', 'id2')
add('f', 'id3', 3)

While this works, I think ultimately if you want to do something like this writing your own data structure is probably the way to go, though it could use a similar structure.

IIS7: Setup Integrated Windows Authentication like in IIS6

So do you want them to get the IE password-challenge box, or should they be directed to your login page and enter their information there? If it's the second option, then you should at least enable Anonymous access to your login page, since the site won't know who they are yet.

If you want the first option, then the login page they're getting forwarded to will need to read the currently logged-in user and act based on that, since they would have had to correctly authenticate to get this far.

How to convert index of a pandas dataframe into a column?

A very simple way of doing this is to use reset_index() method.For a data frame df use the code below:

df.reset_index(inplace=True)

This way, the index will become a column, and by using inplace as True,this become permanent change.

How do I get the function name inside a function in PHP?

If you are using PHP 5 you can try this:

function a() {
    $trace = debug_backtrace();
    echo $trace[0]["function"];
}

Getting the parameters of a running JVM

If you can do this in java, try:

RuntimeMXBean

ManagementFactory

Example:

RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
List<String> jvmArgs = runtimeMXBean.getInputArguments();
for (String arg : jvmArgs) {
    System.out.println(arg);
}

TypeError: expected string or buffer

'lines' term from your snippet consists of set of strings.

 lines = f.readlines()
 match = re.findall('[A-Z]+', lines)

You cannot send entire lines into the re.findall('pattern',<string>)

You can try to send line by line

 for i in lines:
  match = re.findall('[A-Z]+', i)
  print match

or to convert the entire lines collection into single line (each line seperated by space)

 NEW_LIST=' '.join(lines)
 match=re.findall('[A-Z]+' ,NEW_LIST)
 print match

This might help you

Showing an image from an array of images - Javascript

Here's a somewhat cleaner way of implementing this. This makes the following changes:

  1. The code is DRYed up a bit to remove redundant and repeated code and strings.
  2. The code is made more generic/reusable.
  3. We make the cache into an object so it has a self-contained interface and there are fewer globals.
  4. We compare .src attributes instead of DOM elements to make it work properly.

Code:

function imageCache(base, firstNum, lastNum) {
    this.cache = [];
    var img;
    for (var i = firstNum; i <= lastnum; i++) {
        img = new Image();
        img.src = base + i + ".jpg";
        this.cache.push(img);
    }
}

imageCache.prototype.nextImage(id) {
    var element = document.getElementById(id);
    var targetSrc = element.src;
    var cache = this.cache;
    for (var i = 0; i < cache.length; i++) {
        if (cache[i].src) === targetSrc) {
            i++;
            if (i >= cache.length) {
                i = 0;
            }
            element.src = cache[i].src;
            return;
        }
    }
}

// sample usage

var myCache = new imageCache('images/img/Splash_image', 1, 6);
myCache.nextImage("foo");

Some advantages of this more object oriented and DRYed approach:

  1. You can add more images by just creating the images in the numeric sequences and changing one numeric value in the constructor rather than copying lots more lines of array declarations.
  2. You can use this more than one place in your app by just creating more than one imageCache object.
  3. You can change the base URL by changing one string rather than N strings.
  4. The code size is smaller (because of the removal of repeated code).
  5. The cache object could easily be extended to offer more capabilities such as first, last, skip, etc...
  6. You could add centralize error handling in one place so if one image doesn't exist and doesn't load successfully, it's automatically removed from the cache.
  7. You can reuse this in other web pages you develop by only change the arguments to the constructor and not actually changing the implementation code.

P.S. If you don't know what DRY stands for, it's "Don't Repeat Yourself" and basically means that you should never have many copies of similar looking code. Anytime you have that, it should be reduced somehow to a loop or function or something that removes the need for lots of similarly looking copies of code. The end result will be smaller, usually easier to maintain and often more reusable.

How to fix nginx throws 400 bad request headers on any header testing tools?

Yes changing the error_to debug level as Emmanuel Joubaud suggested worked out (edit /etc/nginx/sites-enabled/default ):

        error_log /var/log/nginx/error.log debug;

Then after restaring nginx I got in the error log with my Python application using uwsgi:

        2017/02/08 22:32:24 [debug] 1322#1322: *1 connect to unix:///run/uwsgi/app/socket, fd:20 #2
        2017/02/08 22:32:24 [debug] 1322#1322: *1 connected
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream connect: 0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 posix_memalign: 0000560E1F25A2A0:128 @16
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream send request
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream send request body
        2017/02/08 22:32:24 [debug] 1322#1322: *1 chain writer buf fl:0 s:454
        2017/02/08 22:32:24 [debug] 1322#1322: *1 chain writer in: 0000560E1F2A0928
        2017/02/08 22:32:24 [debug] 1322#1322: *1 writev: 454 of 454
        2017/02/08 22:32:24 [debug] 1322#1322: *1 chain writer out: 0000000000000000
        2017/02/08 22:32:24 [debug] 1322#1322: *1 event timer add: 20: 60000:1486593204249
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http finalize request: -4, "/?" a:1, c:2
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http request count:2 blk:0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 post event 0000560E1F2E5DE0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 post event 0000560E1F2E5E40
        2017/02/08 22:32:24 [debug] 1322#1322: *1 delete posted event 0000560E1F2E5DE0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http run request: "/?"
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream check client, write event:1, "/"
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream recv(): -1 (11: Resource temporarily unavailable)

Then I took a look to my uwsgi log and found out that:

        Invalid HTTP_HOST header: 'www.mysite.local'. You may need to add u'www.mysite.local' to ALLOWED_HOSTS.
        [pid: 10903|app: 0|req: 2/4] 192.168.221.2 () {38 vars in 450 bytes} [Wed Feb  8 22:32:24 2017] GET / => generated 54098 bytes in 55 msecs (HTTP/1.1 400) 4 headers in 135 bytes (1 switches on core 0)

And adding www.mysite.local to the settings.py ALLOWED_HOSTS fixed the issue :)

        ALLOWED_HOSTS = ['www.mysite.local']

Ruby, remove last N characters from a string?

If the characters you want to remove are always the same characters, then consider chomp:

'abc123'.chomp('123')    # => "abc"

The advantages of chomp are: no counting, and the code more clearly communicates what it is doing.

With no arguments, chomp removes the DOS or Unix line ending, if either is present:

"abc\n".chomp      # => "abc"
"abc\r\n".chomp    # => "abc"

From the comments, there was a question of the speed of using #chomp versus using a range. Here is a benchmark comparing the two:

require 'benchmark'

S = 'asdfghjkl'
SL = S.length
T = 10_000
A = 1_000.times.map { |n| "#{n}#{S}" }

GC.disable

Benchmark.bmbm do |x|
  x.report('chomp') { T.times { A.each { |s| s.chomp(S) } } }
  x.report('range') { T.times { A.each { |s| s[0...-SL] } } }
end

Benchmark Results (using CRuby 2.13p242):

Rehearsal -----------------------------------------
chomp   1.540000   0.040000   1.580000 (  1.587908)
range   1.810000   0.200000   2.010000 (  2.011846)
-------------------------------- total: 3.590000sec

            user     system      total        real
chomp   1.550000   0.070000   1.620000 (  1.610362)
range   1.970000   0.170000   2.140000 (  2.146682)

So chomp is faster than using a range, by ~22%.

Convert String XML fragment to Document Node in Java

If you're using dom4j, you can just do:

Document document = DocumentHelper.parseText(text);

(dom4j now found here: https://github.com/dom4j/dom4j)

How to count the number of true elements in a NumPy bool array

That question solved a quite similar question for me and I thought I should share :

In raw python you can use sum() to count True values in a list :

>>> sum([True,True,True,False,False])
3

But this won't work :

>>> sum([[False, False, True], [True, False, True]])
TypeError...

window.close and self.close do not close the window in Chrome

I found a new way that works for me perfetly

var win = window.open("about:blank", "_self");
win.close();

Remove HTML tags from string including &nbsp in C#

this:

(<.+?> | &nbsp;)

will match any tag or &nbsp;

string regex = @"(<.+?>|&nbsp;)";
var x = Regex.Replace(originalString, regex, "").Trim();

then x = hello

Integrating Dropzone.js into existing HTML form with other fields

I have a more automated solution for this.

HTML:

<form role="form" enctype="multipart/form-data" action="{{ $url }}" method="{{ $method }}">
    {{ csrf_field() }}

    <!-- You can add extra form fields here -->

    <input hidden id="file" name="file"/>

    <!-- You can add extra form fields here -->

    <div class="dropzone dropzone-file-area" id="fileUpload">
        <div class="dz-default dz-message">
            <h3 class="sbold">Drop files here to upload</h3>
            <span>You can also click to open file browser</span>
        </div>
    </div>

    <!-- You can add extra form fields here -->

    <button type="submit">Submit</button>
</form>

JavaScript:

Dropzone.options.fileUpload = {
    url: 'blackHole.php',
    addRemoveLinks: true,
    accept: function(file) {
        let fileReader = new FileReader();

        fileReader.readAsDataURL(file);
        fileReader.onloadend = function() {

            let content = fileReader.result;
            $('#file').val(content);
            file.previewElement.classList.add("dz-success");
        }
        file.previewElement.classList.add("dz-complete");
    }
}

Laravel:

// Get file content
$file = base64_decode(request('file'));

No need to disable DropZone Discovery and the normal form submit will be able to send the file with any other form fields through standard form serialization.

This mechanism stores the file contents as base64 string in the hidden input field when it gets processed. You can decode it back to binary string in PHP through the standard base64_decode() method.

I don't know whether this method will get compromised with large files but it works with ~40MB files.

"Please provide a valid cache path" error in laravel

You can edit your readme.md with instructions to install your laravel app in other environment like this:

## Create folders

```
#!terminal

cp .env.example .env && mkdir bootstrap/cache storage storage/framework && cd storage/framework && mkdir sessions views cache

```

## Folder permissions

```
#!terminal

sudo chown :www-data app storage bootstrap -R
sudo chmod 775 app storage bootstrap -R

```

## Install dependencies

```
#!terminal

composer install

```

sql primary key and index

Here the passage from the MSDN:

When you specify a PRIMARY KEY constraint for a table, the Database Engine enforces data uniqueness by creating a unique index for the primary key columns. This index also permits fast access to data when the primary key is used in queries. Therefore, the primary keys that are chosen must follow the rules for creating unique indexes.

Position last flex item at the end of container

Flexible Box Layout Module - 8.1. Aligning with auto margins

Auto margins on flex items have an effect very similar to auto margins in block flow:

  • During calculations of flex bases and flexible lengths, auto margins are treated as 0.

  • Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

Therefore you could use margin-top: auto to distribute the space between the other elements and the last element.

This will position the last element at the bottom.

p:last-of-type {
  margin-top: auto;
}

_x000D_
_x000D_
.container {
  display: flex;
  flex-direction: column;
  border: 1px solid #000;
  min-height: 200px;
  width: 100px;
}
p {
  height: 30px;
  background-color: blue;
  margin: 5px;
}
p:last-of-type {
  margin-top: auto;
}
_x000D_
<div class="container">
  <p></p>
  <p></p>
  <p></p>
</div>
_x000D_
_x000D_
_x000D_

vertical example


Likewise, you can also use margin-left: auto or margin-right: auto for the same alignment horizontally.

p:last-of-type {
  margin-left: auto;
}

_x000D_
_x000D_
.container {
  display: flex;
  width: 100%;
  border: 1px solid #000;
}
p {
  height: 50px;
  width: 50px;
  background-color: blue;
  margin: 5px;
}
p:last-of-type {
  margin-left: auto;
}
_x000D_
<div class="container">
  <p></p>
  <p></p>
  <p></p>
  <p></p>
</div>
_x000D_
_x000D_
_x000D_

horizontal example

How do I open an .exe from another C++ .exe?

I've had great success with this:

#include <iostream>
#include <windows.h>

int main() {
    ShellExecute(NULL, "open", "path\\to\\file.exe", NULL, NULL, SW_SHOWDEFAULT);
}

If you're interested, the full documentation is here:

http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx.

The executable was signed with invalid entitlements

Had this issue occur when everything seemed to be setup correctly, build setting were pointing to correct provisioning profile, code signing was properly setup, etc.

Issue occurred because I had just created a new scheme and hadn't regenerated my CocoaPods for the new configurations. As you can see from the image, the new ad-hoc configuration is pointing to the Pods.production configuration, instead of a Pods.ad-hoc configuration (and test respectively)

Demonstrating a mis-match of ad-hoc configuration and scheme configuration

To fix:

  • Set the offending configuration to None -- cocoapods wouldn't generate the configs unless I did this
  • Close XCode
  • Run pod install
  • Re-open XCode and set the new scheme's configurations to the newly generated configurations.

That's it!

AngularJS Directive Restrict A vs E

Element is not supported in IE8 out of the box you have to do some work to make IE8 accept custom tags.

One advantage of using an attribute over an element is that you can apply multiple directives to the same DOM node. This is particularly handy for things like form controls where you can highlight, disable, or add labels etc. with additional attributes without having to wrap the element in a bunch of tags.

Bitwise and in place of modulus operator

This only works for powers of two (and frequently only positive ones) because they have the unique property of having only one bit set to '1' in their binary representation. Because no other class of numbers shares this property, you can't create bitwise-and expressions for most modulus expressions.

Getting assembly name

Assembly.GetExecutingAssembly().Location

Why is python setup.py saying invalid command 'bdist_wheel' on Travis CI?

This problem is due to:

  • an old version of pip (6.1.1) being installed for Python 2.7
  • multiple copies of Python 2.7 installed on the Trusty Beta image
  • a different location for Python 2.7 being used for sudo

It's all a bit complicated and better explained here https://github.com/travis-ci/travis-ci/issues/4989.

My solution was to install with user travis instead of sudo:

- pip2.7 install --upgrade --user travis pip setuptools wheel virtualenv

Why call super() in a constructor?

We can access super class elements by using super keyword

Consider we have two classes, Parent class and Child class, with different implementations of method foo. Now in child class if we want to call the method foo of parent class, we can do so by super.foo(); we can also access parent elements by super keyword.

    class parent {
    String str="I am parent";
    //method of parent Class
    public void foo() {
        System.out.println("Hello World " + str);
    }
}

class child extends parent {
    String str="I am child";
    // different foo implementation in child Class
    public void foo() {
        System.out.println("Hello World "+str);
    }

    // calling the foo method of parent class
    public void parentClassFoo(){
        super.foo();
    }

    // changing the value of str in parent class and calling the foo method of parent class
    public void parentClassFooStr(){
        super.str="parent string changed";
        super.foo();
    }
}


public class Main{
        public static void main(String args[]) {
            child obj = new child();
            obj.foo();
            obj.parentClassFoo();
            obj.parentClassFooStr();
        }
    }

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

In case you want to search for all the issues updated after 9am previous day until today at 9AM, please try: updated >= startOfDay(-15h) and updated <= startOfDay(9h). (explanation: 9AM - 24h/day = -15h)

You can also use updated >= startOfDay(-900m) . where 900m = 15h*60m

Reference: https://confluence.atlassian.com/display/JIRA/Advanced+Searching

How do I start/stop IIS Express Server?

Open Task Manager and Kill both of these processes. They will autostart back up. Then try debugging your project again.

enter image description here

Unique constraint violation during insert: why? (Oracle)

It looks like you are not providing a value for the primary key field DB_ID. If that is a primary key, you must provide a unique value for that column. The only way not to provide it would be to create a database trigger that, on insert, would provide a value, most likely derived from a sequence.

If this is a restoration from another database and there is a sequence on this new instance, it might be trying to reuse a value. If the old data had unique keys from 1 - 1000 and your current sequence is at 500, it would be generating values that already exist. If a sequence does exist for this table and it is trying to use it, you would need to reconcile the values in your table with the current value of the sequence.

You can use SEQUENCE_NAME.CURRVAL to see the current value of the sequence (if it exists of course)

CSS to keep element at "fixed" position on screen

position: fixed;

Will make this happen.

It handles like position:absolute; with the exception that it will scroll with the window as the user scrolls down the content.

Automate scp file transfer using a shell script

The command scp can be used like a traditional UNIX cp. SO if you do :

scp -r myDirectory/ mylogin@host:TargetDirectory

will work

Python Pandas: Get index of rows which column matches certain value

First you may check query when the target column is type bool (PS: about how to use it please check link )

df.query('BoolCol')
Out[123]: 
    BoolCol
10     True
40     True
50     True

After we filter the original df by the Boolean column we can pick the index .

df=df.query('BoolCol')
df.index
Out[125]: Int64Index([10, 40, 50], dtype='int64')

Also pandas have nonzero, we just select the position of True row and using it slice the DataFrame or index

df.index[df.BoolCol.nonzero()[0]]
Out[128]: Int64Index([10, 40, 50], dtype='int64')

Plot logarithmic axes with matplotlib in python

You can use the Axes.set_yscale method. That allows you to change the scale after the Axes object is created. That would also allow you to build a control to let the user pick the scale if you needed to.

The relevant line to add is:

ax.set_yscale('log')

You can use 'linear' to switch back to a linear scale. Here's what your code would look like:

import pylab
import matplotlib.pyplot as plt
a = [pow(10, i) for i in range(10)]
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)

line, = ax.plot(a, color='blue', lw=2)

ax.set_yscale('log')

pylab.show()

result chart

Set font-weight using Bootstrap classes

I found this on the Bootstrap website, but it really isn't a Bootstrap class, it's just HTML.

<strong>rendered as bold text</strong>

Drawing Isometric game worlds

Real problem is when you need draw some tile/sprites intersecting/spanning two or more other tiles.

After 2 (hard) months of personal analisys of problem I finally found and implemented a "correct render drawing" for my new cocos2d-js game. Solution consists in mapping, for each tile (susceptible), which sprites are "front, back, top and behind". Once doing that you can draw them following a "recursive logic".

How is the 'use strict' statement interpreted in Node.js?

"use strict";

Basically it enables the strict mode.

Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.

As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.

So, there will be no major difference how "use strict"; is interpreted by the Chrome browser and Node.js.

Please read what is strict mode in JavaScript.

For more information:

  1. Strict mode
  2. ECMAScript 5 Strict mode support in browsers
  3. Strict mode is coming to town
  4. Compatibility table for strict mode
  5. Stack Overflow questions: what does 'use strict' do in JavaScript & what is the reasoning behind it


ECMAScript 6:

ECMAScript 6 Code & strict mode. Following is brief from the specification:

10.2.1 Strict Mode Code

An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:

  • Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
  • Module code is always strict mode code.
  • All parts of a ClassDeclaration or a ClassExpression are strict mode code.
  • Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
  • Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
  • Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.

Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).

How can I find out the current route in Rails?

I'll assume you mean the URI:

class BankController < ActionController::Base
  before_filter :pre_process 

  def index
    # do something
  end

  private
    def pre_process
      logger.debug("The URL" + request.url)
    end
end

As per your comment below, if you need the name of the controller, you can simply do this:

  private
    def pre_process
      self.controller_name        #  Will return "order"
      self.controller_class_name  # Will return "OrderController"
    end

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

View and check the reference paths in your csproj.

I had removed references to System.Web.Mvc (and others) and readded them to a custom path. C:\Project\OurWebReferences

However, after doing this, the reference path in the still csproj did not change. WAS

<Reference Include="System.Web.Mvc, Version=4.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\..\..\..\OurWebProject\bin\Debug\System.Web.Mvc.dll</HintPath>
</Reference>

Changed to manually

<Reference Include="System.Web.Mvc, Version=4.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
        <HintPath>..\..\..\..\OurWebReferences\System.Web.Mvc.dll</HintPath>
</Reference>

Paths are an example only.

How to access the GET parameters after "?" in Express?

Update: req.param() is now deprecated, so going forward do not use this answer.


Your answer is the preferred way to do it, however I thought I'd point out that you can also access url, post, and route parameters all with req.param(parameterName, defaultValue).

In your case:

var color = req.param('color');

From the express guide:

lookup is performed in the following order:

  • req.params
  • req.body
  • req.query

Note the guide does state the following:

Direct access to req.body, req.params, and req.query should be favoured for clarity - unless you truly accept input from each object.

However in practice I've actually found req.param() to be clear enough and makes certain types of refactoring easier.

how to get current location in google map android

package com.example.sandeep.googlemapsample;

import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        GoogleMap.OnMarkerDragListener,
        GoogleMap.OnMapLongClickListener,
        GoogleMap.OnMarkerClickListener,
        View.OnClickListener {

    private static final String TAG = "MapsActivity";
    private GoogleMap mMap;
    private double longitude;
    private double latitude;
    private GoogleApiClient googleApiClient;


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

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        //Initializing googleApiClient
        googleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
       // googleMapOptions.mapType(googleMap.MAP_TYPE_HYBRID)
                    //    .compassEnabled(true);

        // Add a marker in Sydney and move the camera
        LatLng india = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(india).title("Marker in India"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(india));
        mMap.setOnMarkerDragListener(this);
        mMap.setOnMapLongClickListener(this);
    }

    //Getting current location
    private void getCurrentLocation() {
        mMap.clear();
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        if (location != null) {
            //Getting longitude and latitude
            longitude = location.getLongitude();
            latitude = location.getLatitude();

            //moving the map to location
            moveMap();
        }
    }

    private void moveMap() {
        /**
         * Creating the latlng object to store lat, long coordinates
         * adding marker to map
         * move the camera with animation
         */
        LatLng latLng = new LatLng(latitude, longitude);
        mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .draggable(true)
                .title("Marker in India"));

        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
        mMap.getUiSettings().setZoomControlsEnabled(true);


    }

    @Override
    public void onClick(View view) {
        Log.v(TAG,"view click event");
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        getCurrentLocation();
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onMapLongClick(LatLng latLng) {
        // mMap.clear();
        mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
    }

    @Override
    public void onMarkerDragStart(Marker marker) {
        Toast.makeText(MapsActivity.this, "onMarkerDragStart", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onMarkerDrag(Marker marker) {
        Toast.makeText(MapsActivity.this, "onMarkerDrag", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onMarkerDragEnd(Marker marker) {
        // getting the Co-ordinates
        latitude = marker.getPosition().latitude;
        longitude = marker.getPosition().longitude;

        //move to current position
        moveMap();
    }

    @Override
    protected void onStart() {
        googleApiClient.connect();
        super.onStart();
    }

    @Override
    protected void onStop() {
        googleApiClient.disconnect();
        super.onStop();
    }


    @Override
    public boolean onMarkerClick(Marker marker) {
        Toast.makeText(MapsActivity.this, "onMarkerClick", Toast.LENGTH_SHORT).show();
        return true;
    }

}

How to dismiss a Twitter Bootstrap popover by clicking outside?

$('html').on('mouseup', function(e) {
    if(!$(e.target).closest('.popover').length) {
        $('.popover').each(function(){
            $(this.previousSibling).popover('hide');
        });
    }
});

This closes all popovers if you click anywhere except on a popover

UPDATE for Bootstrap 4.1

$("html").on("mouseup", function (e) {
    var l = $(e.target);
    if (l[0].className.indexOf("popover") == -1) {
        $(".popover").each(function () {
            $(this).popover("hide");
        });
    }
});

pass array to method Java

There is an important point of arrays that is often not taught or missed in java classes. When arrays are passed to a function, then another pointer is created to the same array ( the same pointer is never passed ). You can manipulate the array using both the pointers, but once you assign the second pointer to a new array in the called method and return back by void to calling function, then the original pointer still remains unchanged.

You can directly run the code here : https://www.compilejava.net/

import java.util.Arrays;

public class HelloWorld
{
    public static void main(String[] args)
    {
        int Main_Array[] = {20,19,18,4,16,15,14,4,12,11,9};
        Demo1.Demo1(Main_Array);
        // THE POINTER Main_Array IS NOT PASSED TO Demo1
        // A DIFFERENT POINTER TO THE SAME LOCATION OF Main_Array IS PASSED TO Demo1

        System.out.println("Main_Array = "+Arrays.toString(Main_Array));
        // outputs : Main_Array = [20, 19, 18, 4, 16, 15, 14, 4, 12, 11, 9]
        // Since Main_Array points to the original location,
        // I cannot access the results of Demo1 , Demo2 when they are void.
        // I can use array clone method in Demo1 to get the required result,
        // but it would be faster if Demo1 returned the result to main
    }
}

public class Demo1
{
    public static void Demo1(int A[])
    {
        int B[] = new int[A.length];
        System.out.println("B = "+Arrays.toString(B)); // output : B = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        Demo2.Demo2(A,B);
        System.out.println("B = "+Arrays.toString(B)); // output : B = [9999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        System.out.println("A = "+Arrays.toString(A)); // output : A = [20, 19, 18, 4, 16, 15, 14, 4, 12, 11, 9]

        A = B;
        // A was pointing to location of Main_Array, now it points to location of B
        // Main_Array pointer still keeps pointing to the original location in void main

        System.out.println("A = "+Arrays.toString(A)); // output : A = [9999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        // Hence to access this result from main, I have to return it to main
    }
}
public class Demo2
{
    public static void Demo2(int AAA[],int BBB[])
    {
        BBB[0] = 9999;
        // BBB points to the same location as B in Demo1, so whatever I do
        // with BBB, I am manipulating the location. Since B points to the
        // same location, I can access the results from B
    }
}

MySQL select rows where left join is null

Here is a query that returns only the rows where no correspondance has been found in both columns user_one and user_two of table2:

SELECT T1.*
FROM table1 T1
LEFT OUTER JOIN table2 T2A ON T2A.user_one = T1.id
LEFT OUTER JOIN table2 T2B ON T2B.user_two = T1.id
WHERE T2A.user_one IS NULL
    AND T2B.user_two IS NULL

There is one jointure for each column (user_one and user_two) and the query only returns rows that have no matching jointure.

Hope this will help you.

Is there a kind of Firebug or JavaScript console debug for Android?

On 2013-12-03 Google launched Chrome DevTools for Mobile, which lets developers remote debug mobile web applications via emulation and screen-casting with Zero Configuration.

For all features, checkout Paul Irish's talk on YouTube.

How to get last items of a list in Python?

You can use negative integers with the slicing operator for that. Here's an example using the python CLI interpreter:

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> a[-9:]
[4, 5, 6, 7, 8, 9, 10, 11, 12]

the important line is a[-9:]

How get total sum from input box values using Javascript?

I need to sum the span elements so I edited Akhil Sekharan's answer below.

var arr = document.querySelectorAll('span[id^="score"]');
var total=0;
    for(var i=0;i<arr.length;i++){
        if(parseInt(arr[i].innerHTML))
            total+= parseInt(arr[i].innerHTML);
    }
console.log(total)

You can change the elements with other elements link will guide you with editing.

https://www.w3.org/TR/css3-selectors/#attribute-substrings

MySQL pivot table query with dynamic columns

I have a slightly different way of doing this than the accepted answer. This way you can avoid using GROUP_CONCAT which has a limit of 1024 characters and will not work if you have a lot of fields.

SET @sql = '';
SELECT
    @sql := CONCAT(@sql,if(@sql='','',', '),temp.output)
FROM
(
    SELECT
      DISTINCT
        CONCAT(
         'MAX(IF(pa.fieldname = ''',
          fieldname,
          ''', pa.fieldvalue, NULL)) AS ',
          fieldname
        ) as output
    FROM
        product_additional
) as temp;

SET @sql = CONCAT('SELECT p.id
                    , p.name
                    , p.description, ', @sql, ' 
                   FROM product p
                   LEFT JOIN product_additional AS pa 
                    ON p.id = pa.id
                   GROUP BY p.id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

I started mongod in cmd,It threw error like C:\data\db\ not found. Created folder then typed mongod opened another cmd typed mongo it worked.

Problems when trying to load a package in R due to rJava

Its because either one of the Java versions(32 bit/64 bit) is missing from your computer. Try installing both the Jdks and run the code.
After installing the Jdks open R and type the code

system("java -version")

This will give you the version of Jdk installed. Then try loading the rJava package. This worked for me.

image size (drawable-hdpi/ldpi/mdpi/xhdpi)

MDPI - 32px
HDPI - 48px
XHDPI- 64px

This Cheat Sheet might be handy for you. check the image :-)

image

Choose Git merge strategy for specific files ("ours", "mine", "theirs")

For each conflicted file you get, you can specify

git checkout --ours -- <paths>
# or
git checkout --theirs -- <paths>

From the git checkout docs

git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] [--] <paths>...

--ours
--theirs
When checking out paths from the index, check out stage #2 (ours) or #3 (theirs) for unmerged paths.

The index may contain unmerged entries because of a previous failed merge. By default, if you try to check out such an entry from the index, the checkout operation will fail and nothing will be checked out. Using -f will ignore these unmerged entries. The contents from a specific side of the merge can be checked out of the index by using --ours or --theirs. With -m, changes made to the working tree file can be discarded to re-create the original conflicted merge result.

How to remove index.php from URLs?

I tried everything on the post but nothing had worked. I then changed the .htaccess snippet that ErJab put up to read:

RewriteRule ^(.*)$ 'folder_name'/index.php/$1 [L]

The above line fixed it for me. where *folder_name* is the magento root folder.

Hope this helps!

Best practice for storing and protecting private API keys in applications

Few ideas, in my opinion only first one gives some guarantee:

  1. Keep your secrets on some server on internet, and when needed just grab them and use. If user is about to use dropbox then nothing stops you from making request to your site and get your secret key.

  2. Put your secrets in jni code, add some variable code to make your libraries bigger and more difficult to decompile. You might also split key string in few parts and keep them in various places.

  3. use obfuscator, also put in code hashed secret and later on unhash it when needed to use.

  4. Put your secret key as last pixels of one of your image in assets. Then when needed read it in your code. Obfuscating your code should help hide code that will read it.

If you want to have a quick look at how easy it is to read you apk code then grab APKAnalyser:

http://developer.sonymobile.com/knowledge-base/tool-guides/analyse-your-apks-with-apkanalyser/

How to run a class from Jar which is not the Main-Class in its Manifest file

Another similar option that I think Nick briefly alluded to in the comments is to create multiple wrapper jars. I haven't tried it, but I think they could be completely empty other than the manifest file, which should specify the main class to load as well as the inclusion of the MyJar.jar to the classpath.

MyJar1.jar\META-INF\MANIFEST.MF

Manifest-Version: 1.0
Main-Class: com.mycomp.myproj.dir1.MainClass1
Class-Path: MyJar.jar

MyJar2.jar\META-INF\MANIFEST.MF

Manifest-Version: 1.0
Main-Class: com.mycomp.myproj.dir2.MainClass2
Class-Path: MyJar.jar

etc. Then just run it with java -jar MyJar2.jar

How to create dynamic href in react render function?

In addition to Felix's answer,

href={`/posts/${posts.id}`}

would work well too. This is nice because it's all in one string.

undefined reference to WinMain@16 (codeblocks)

I had the same error problem using Code Blocks rev 13.12. I may be wrong here since I am less than a beginner :)

My problem was that I accidentally capitalized "M" in Main() instead of ALL lowercase = main() - once corrected, it worked!!!

I noticed that you have "int main()" instead of "main()". Is this the problem, or is it supposed to be that way?

Hope I could help...

Split comma separated column data into additional columns

split_part() does what you want in one step:

SELECT split_part(col, ',', 1) AS col1
     , split_part(col, ',', 2) AS col2
     , split_part(col, ',', 3) AS col3
     , split_part(col, ',', 4) AS col4
FROM   tbl;

Add as many lines as you have items in col (the possible maximum). Columns exceeding data items will be empty strings ('').

Get querystring from URL using jQuery

Have a look at this Stack Overflow answer.

 function getParameterByName(name, url) {
     if (!url) url = window.location.href;
     name = name.replace(/[\[\]]/g, "\\$&");
     var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
         results = regex.exec(url);
     if (!results) return null;
     if (!results[2]) return '';
     return decodeURIComponent(results[2].replace(/\+/g, " "));
 }

You can use the method to animate:

I.e.:

var thequerystring = getParameterByName("location");
$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);

How do I get the current absolute URL in Ruby on Rails?

For Rails 3.x and up:

#{request.protocol}#{request.host_with_port}#{request.fullpath}

For Rails 3.2 and up:

request.original_url

Because in rails 3.2 and up:

request.original_url = request.base_url + request.original_fullpath

For more info, plese visit http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-original_url

CSS for the "down arrow" on a <select> element?

http://jsfiddle.net/u3cybk2q/2/ check on windows, iOS and Android (iexplorer patch)

_x000D_
_x000D_
.styled-select select {_x000D_
   background: transparent;_x000D_
   width: 240px;_x000D_
   padding: 5px;_x000D_
   font-size: 16px;_x000D_
   line-height: 1;_x000D_
   border: 0;_x000D_
   border-radius: 0;_x000D_
   height: 34px;_x000D_
   -webkit-appearance: none;_x000D_
}_x000D_
.styled-select {_x000D_
   width: 240px;_x000D_
   height: 34px;_x000D_
   overflow: visible;_x000D_
   background: url(http://nightly.enyojs.com/latest/lib/moonstone/dist/moonstone/images/caret-black-small-down-icon.png) no-repeat right #FFF;_x000D_
   border: 1px solid #ccc;_x000D_
}_x000D_
.styled-select select::-ms-expand {_x000D_
    display: none; /*patch iexplorer*/_x000D_
}
_x000D_
  <div class="styled-select">_x000D_
       <select>_x000D_
          <option>Here is the first option</option>_x000D_
          <option>The second option</option>_x000D_
       </select>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

how to format date in Component of angular 5

Refer to the below link,

https://angular.io/api/common/DatePipe

**Code Sample**

@Component({
 selector: 'date-pipe',
 template: `<div>
   <p>Today is {{today | date}}</p>
   <p>Or if you prefer, {{today | date:'fullDate'}}</p>
   <p>The time is {{today | date:'h:mm a z'}}</p>
 </div>`
})
// Get the current date and time as a date-time value.
export class DatePipeComponent {
  today: number = Date.now();
}

{{today | date:'MM/dd/yyyy'}} output: 17/09/2019

or

{{today | date:'shortDate'}} output: 17/9/19

Load image from resources area of project in C#

With and ImageBox named "ImagePreview FormStrings.MyImageNames contains a regular get/set string cast method, which are linked to a scrollbox type list. The images have the same names as the linked names on the list, except for the .bmp endings. All bitmaps are dragged into the resources.resx

Object rm = Properties.Resources.ResourceManager.GetObject(FormStrings.MyImageNames);
Bitmap myImage = (Bitmap)rm;
ImagePreview.Image = myImage;

Superscript in CSS only?

This is another clean solution:

sub, sup {vertical-align: baseline; position: relative; font-size: 70%;} /* 70% size of its parent element font-size which is good. */
sub {bottom: -0.6em;} /* use em becasue they adapt to parent font-size */
sup {top: -0.6em;} /* use em becasue they adapt to parent font-size */

In this way you can still use sup/sub tags but you fixed their idious behavior to always screw up paragraph line height.

So now you can do:

  <p>This is a line of text.</p>
  <p>This is a line of text, <sub>with sub text.</sub></p>
  <p>This is a line of text, <sup>with sup text.</sup></p>
  <p>This is a line of text.</p>

And your paragraph line height should not get screwed up.

Tested on IE7, IE8, FF3.6, SAFARI4, CHROME5, OPERA9

I tested using a p {line-height: 1.3;} (that is a good line height unless you want your lines to stick too close) and it still works, cause "-0.6em" is such a small amount that also with that line height the sub/sub text will fit and don't go over each other.

Forgot a detail that might be relevant I always use DOCTYPE in the 1st line of my page (specifically I use the HTML 4.01 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">). So I don't know if this solution works well when browser is in quirkmode (or not standard mode) due to lack of DOCTYPE or to a DOCTYPE that does not triggers Standard/Almost Standard mode.

Failed to load AppCompat ActionBar with unknown error in android studio

Replace implementation 'com.android.support:appcompat-v7:28.0.0-beta01' with

implementation 'com.android.support:appcompat-v7:28.0.0-alpha1' 

in build.gradle (Module:app). It fixed my red mark in Android Studio 3.1.3

Axios Delete request with body and headers?

axios.delete is passed a url and an optional configuration.

axios.delete(url[, config])

The fields available to the configuration can include the headers.

This makes it so that the API call can be written as:

const headers = {
  'Authorization': 'Bearer paperboy'
}
const data = {
  foo: 'bar'
}

axios.delete('https://foo.svc/resource', {headers, data})

JavaFX open new window

I use the following method in my JavaFX applications.

newWindowButton.setOnMouseClicked((event) -> {
    try {
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(getClass().getResource("NewWindow.fxml"));
        /* 
         * if "fx:controller" is not set in fxml
         * fxmlLoader.setController(NewWindowController);
         */
        Scene scene = new Scene(fxmlLoader.load(), 600, 400);
        Stage stage = new Stage();
        stage.setTitle("New Window");
        stage.setScene(scene);
        stage.show();
    } catch (IOException e) {
        Logger logger = Logger.getLogger(getClass().getName());
        logger.log(Level.SEVERE, "Failed to create new Window.", e);
    }
});

How to write dynamic variable in Ansible playbook

my_var: the variable declared

VAR: the variable, whose value is to be checked

param_1, param_2: values of the variable VAR

value_1, value_2, value_3: the values to be assigned to my_var according to the values of my_var

my_var: "{{ 'value_1' if VAR == 'param_1' else 'value_2' if VAR == 'param_2' else 'value_3' }}"

ProcessStartInfo hanging on "WaitForExit"? Why?

The problem is that if you redirect StandardOutput and/or StandardError the internal buffer can become full. Whatever order you use, there can be a problem:

  • If you wait for the process to exit before reading StandardOutput the process can block trying to write to it, so the process never ends.
  • If you read from StandardOutput using ReadToEnd then your process can block if the process never closes StandardOutput (for example if it never terminates, or if it is blocked writing to StandardError).

The solution is to use asynchronous reads to ensure that the buffer doesn't get full. To avoid any deadlocks and collect up all output from both StandardOutput and StandardError you can do this:

EDIT: See answers below for how avoid an ObjectDisposedException if the timeout occurs.

using (Process process = new Process())
{
    process.StartInfo.FileName = filename;
    process.StartInfo.Arguments = arguments;
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;

    StringBuilder output = new StringBuilder();
    StringBuilder error = new StringBuilder();

    using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
    using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
    {
        process.OutputDataReceived += (sender, e) => {
            if (e.Data == null)
            {
                outputWaitHandle.Set();
            }
            else
            {
                output.AppendLine(e.Data);
            }
        };
        process.ErrorDataReceived += (sender, e) =>
        {
            if (e.Data == null)
            {
                errorWaitHandle.Set();
            }
            else
            {
                error.AppendLine(e.Data);
            }
        };

        process.Start();

        process.BeginOutputReadLine();
        process.BeginErrorReadLine();

        if (process.WaitForExit(timeout) &&
            outputWaitHandle.WaitOne(timeout) &&
            errorWaitHandle.WaitOne(timeout))
        {
            // Process completed. Check process.ExitCode here.
        }
        else
        {
            // Timed out.
        }
    }
}

Real world use of JMS/message queues?

I have seen JMS used in different commercial and academic projects. JMS can easily come into your picture, whenever you want to have a totally decoupled distributed systems. Generally speaking, when you need to send your request from one node, and someone in your network takes care of it without/with giving the sender any information about the receiver.

In my case, I have used JMS in developing a message-oriented middleware (MOM) in my thesis, where specific types of object-oriented objects are generated in one side as your request, and compiled and executed on the other side as your response.

React Router with optional path parameter

If you are looking to do an exact match, use the following syntax: (param)?.

Eg.

<Route path={`my/(exact)?/path`} component={MyComponent} />

The nice thing about this is that you'll have props.match to play with, and you don't need to worry about checking the value of the optional parameter:

{ props: { match: { "0": "exact" } } }

Convert to binary and keep leading zeros in Python

Use the format() function:

>>> format(14, '#010b')
'0b00001110'

The format() function simply formats the input following the Format Specification mini language. The # makes the format include the 0b prefix, and the 010 size formats the output to fit in 10 characters width, with 0 padding; 2 characters for the 0b prefix, the other 8 for the binary digits.

This is the most compact and direct option.

If you are putting the result in a larger string, use an formatted string literal (3.6+) or use str.format() and put the second argument for the format() function after the colon of the placeholder {:..}:

>>> value = 14
>>> f'The produced output, in binary, is: {value:#010b}'
'The produced output, in binary, is: 0b00001110'
>>> 'The produced output, in binary, is: {:#010b}'.format(value)
'The produced output, in binary, is: 0b00001110'

As it happens, even for just formatting a single value (so without putting the result in a larger string), using a formatted string literal is faster than using format():

>>> import timeit
>>> timeit.timeit("f_(v, '#010b')", "v = 14; f_ = format")  # use a local for performance
0.40298633499332936
>>> timeit.timeit("f'{v:#010b}'", "v = 14")
0.2850222919951193

But I'd use that only if performance in a tight loop matters, as format(...) communicates the intent better.

If you did not want the 0b prefix, simply drop the # and adjust the length of the field:

>>> format(14, '08b')
'00001110'

Don't change link color when a link is clicked

You need to use an explicit color value (e.g. #000 or blue) for the color-property. none is invalid here. The initial value is browser-specific and cannot be restored using CSS. Keep in mind that there are some other pseudo-classes than :active, too.

SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

First line of the error message describes the error type: "PDOException". The next line displays PDO::errorInfo, i.e:

  1. SQLSTATE error code (a five characters alphanumeric identifier defined in the ANSI SQL standard).
  2. Driver-specific error code.
  3. Driver-specific error message.
  • "HY000" is a general server error (see Server Error Codes and Messages in MySQL docs).
  • "2002" is MySQL Client Error Code meaning "Can't connect to local MySQL server through socket" (see (Client Error Codes and Messages in MySQL docs).
  • The driver specific error code and message ("php_network_getaddresses: getaddrinfo failed: Name or service not known") tell you that PDO is not able to resolve the host name.

The stack trace you attached, line 3, reveals that you did not specify the database connection parameters in the configuration file. The error show up when you test on local, right? You need to update /.env with the actual database connection parameters.

Linking a UNC / Network drive on an html page

Setup IIS on the network server and change the path to http://server/path/to/file.txt

EDIT: Make sure you enable directory browsing in IIS

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

Check to find the root cause by reading logs in the tomcat installation log folder if all the above answers failed.Read the catalina.out file to find out the exact cause. It might be database credentials error or class definition not found.

SELECT only rows that contain only alphanumeric characters in MySQL

There is also this:

select m from table where not regexp_like(m, '^[0-9]\d+$')

which selects the rows that contains characters from the column you want (which is m in the example but you can change).

Most of the combinations don't work properly in Oracle platforms but this does. Sharing for future reference.

How to get setuptools and easy_install?

For python3 on Ubuntu

 sudo apt-get install python3-setuptools

How can I update NodeJS and NPM to the next versions?

See the docs for the update command:

npm update [-g] [<pkg>...]

This command will update all the packages listed to the latest version (specified by the tag config), respecting semver.

Additionally, see the documentation on Node.js and NPM installation and Upgrading NPM.

The following original answer is from the old FAQ that no longer exists, but should work for Linux and Mac:

How do I update npm?

npm install -g npm

Please note that this command will remove your current version of npm. Make sure to use sudo npm install -g npm if on a Mac.

You can also update all outdated local packages by doing npm update without any arguments, or global packages by doing npm update -g.

Occasionally, the version of npm will progress such that the current version cannot be properly installed with the version that you have installed already. (Consider, if there is ever a bug in the update command.) In those cases, you can do this:

curl https://www.npmjs.com/install.sh | sh

To update Node.js itself, I recommend you use nvm, the Node Version Manager.

Abstract Class:-Real Time Example

The best example of an abstract class is GenericServlet. GenericServlet is the parent class of HttpServlet. It is an abstract class.

When inheriting 'GenericServlet' in a custom servlet class, the service() method must be overridden.

How to put labels over geom_bar for each bar in R with ggplot2

Try this:

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
     geom_bar(position = 'dodge', stat='identity') +
     geom_text(aes(label=Number), position=position_dodge(width=0.9), vjust=-0.25)

ggplot output

Reshaping data.frame from wide to long format

With tidyr_1.0.0, another option is pivot_longer

library(tidyr)
pivot_longer(df1, -c(Code, Country), values_to = "Value", names_to = "Year")
# A tibble: 10 x 4
#   Code  Country     Year  Value 
#   <fct> <fct>       <chr> <fct> 
# 1 AFG   Afghanistan 1950  20,249
# 2 AFG   Afghanistan 1951  21,352
# 3 AFG   Afghanistan 1952  22,532
# 4 AFG   Afghanistan 1953  23,557
# 5 AFG   Afghanistan 1954  24,555
# 6 ALB   Albania     1950  8,097 
# 7 ALB   Albania     1951  8,986 
# 8 ALB   Albania     1952  10,058
# 9 ALB   Albania     1953  11,123
#10 ALB   Albania     1954  12,246

data

df1 <- structure(list(Code = structure(1:2, .Label = c("AFG", "ALB"), class = "factor"), 
    Country = structure(1:2, .Label = c("Afghanistan", "Albania"
    ), class = "factor"), `1950` = structure(1:2, .Label = c("20,249", 
    "8,097"), class = "factor"), `1951` = structure(1:2, .Label = c("21,352", 
    "8,986"), class = "factor"), `1952` = structure(2:1, .Label = c("10,058", 
    "22,532"), class = "factor"), `1953` = structure(2:1, .Label = c("11,123", 
    "23,557"), class = "factor"), `1954` = structure(2:1, .Label = c("12,246", 
    "24,555"), class = "factor")), class = "data.frame", row.names = c(NA, 
-2L))

Bash Templating: How to build configuration files from templates with Bash?

Edit Jan 6, 2017

I needed to keep double quotes in my configuration file so double escaping double quotes with sed helps:

render_template() {
  eval "echo \"$(sed 's/\"/\\\\"/g' $1)\""
}

I can't think of keeping trailing new lines, but empty lines in between are kept.


Although it is an old topic, IMO I found out more elegant solution here: http://pempek.net/articles/2013/07/08/bash-sh-as-template-engine/

#!/bin/sh

# render a template configuration file
# expand variables + preserve formatting
render_template() {
  eval "echo \"$(cat $1)\""
}

user="Gregory"
render_template /path/to/template.txt > path/to/configuration_file

All credits to Grégory Pakosz.

How to get a list of installed Jenkins plugins with name and version pair

These days I use the same approach as the answer described by @Behe below instead, updated link: https://stackoverflow.com/a/35292719/3423146 (old link: https://stackoverflow.com/a/35292719/1597808)


You can use the API in combination with depth, XPath, and wrapper arguments.

The following will query the API of the pluginManager to list all plugins installed, but only to return their shortName and version attributes. You can of course retrieve additional fields by adding '|' to the end of the XPath parameter and specifying the pattern to identify the node.

wget http://<jenkins>/pluginManager/api/xml?depth=1&xpath=/*/*/shortName|/*/*/version&wrapper=plugins

The wrapper argument is required in this case, because it's returning more than one node as part of the result, both in that it is matching multiple fields with the XPath and multiple plugin nodes.

It's probably useful to use the following URL in a browser to see what information on the plugins is available and then decide what you want to limit using XPath:

http://<jenkins>/pluginManager/api/xml?depth=1

add an element to int [] array in java

The ... can only be used in JDK 1.5 or later. If you are using JDK 4 or lower, use this code:'

public static int[] addElement(int[] original, int newelement) {
    int[] nEw = new int[original.length + 1];
    System.arraycopy(original, 0, nEw, 0, original.length);
    nEw[original.length] = newelement;
}

otherwise (JDK 5 or higher):

public static int[] addElement(int[] original, int... elements) { // This can add multiple elements at once; addElement(int[], int) will still work though.
    int[] nEw = new int[original.length + elements.length];
    System.arraycopy(original, 0, nEw, 0, original.length);
    System.arraycopy(elements, 0, nEw, original.length, elements.length);
    return nEw;
}

Of course, as many have mentioned above, you could use a Collection or an ArrayList, which allows you to use the .add() method.

Adding values to specific DataTable cells

If anyone is looking for an updated correct syntax for this as I was, try the following:

Example:
dg.Rows[0].Cells[6].Value = "test";

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

UPDATE  table
SET     columnx = CASE WHEN condition THEN 25 ELSE columnx END,
        columny = CASE WHEN condition THEN columny ELSE 25 END

Aligning a float:left div to center?

Perhaps this what you're looking for - https://www.w3schools.com/css/css3_flexbox.asp

CSS:

#container {
  display:                 flex;
  flex-wrap:               wrap;
  justify-content:         center;
}

.block {
  width:              150px;
  height:             150px;
  margin:             10px;        
}

HTML:

<div id="container">
  <div class="block">1</div>    
  <div class="block">2</div>    
  <div class="block">3</div>          
</div>

Get WooCommerce product categories from WordPress

In my opinion this is the simplest solution

$orderby = 'name';
                $order = 'asc';
                $hide_empty = false ;
                $cat_args = array(
                    'orderby'    => $orderby,
                    'order'      => $order,
                    'hide_empty' => $hide_empty,
                );

                $product_categories = get_terms( 'product_cat', $cat_args );

                if( !empty($product_categories) ){
                    echo '

                <ul>';
                    foreach ($product_categories as $key => $category) {
                        echo '

                <li>';
                        echo '<a href="'.get_term_link($category).'" >';
                        echo $category->name;
                        echo '</a>';
                        echo '</li>';
                    }
                    echo '</ul>


                ';
                }

makefiles - compile all c files at once

LIBS  = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall

# Should be equivalent to your list of C files, if you don't build selectively
SRC=$(wildcard *.c)

test: $(SRC)
    gcc -o $@ $^ $(CFLAGS) $(LIBS)

Link to reload current page

Completely idempotent url that preserves path, parameters, and anchor.

 <a href="javascript:"> click me </a>

it only uses a little tiny bit of JS.

EDIT: this does not reload the page. It is a link that does nothing.

Authenticate Jenkins CI for Github private repository

Another option is to use GitHub personal access tokens:

  • Go to https://github.com/settings/tokens/new
  • Add repo scope
  • In Jenkins, add a GitHub source
  • Use Repository HTTPS URL
  • Add the HTTPS URL of the git repo (not the SSH one, eg. https://github.com/my-username/my-project.git)
  • Add credential
    • Kind: Username with Password
    • Username: the GitHub username
    • Password: the personal access token you created on GitHub
    • ID: something like github-token-for-my-username

I tested this on Jenkins ver. 2.222.1 and Jenkins GitHub plugin 1.29.5 with a private GitHub repo.

MySQL error - #1062 - Duplicate entry ' ' for key 2

As it was said you have a unique index.

However, when I added most of the list yesterday I didn't get this error once even though a lot of the entries I added yesterday have a blank cell in column 2 as well. Whats going on?

That means that all these entries contain value NULL, not empty string ''. Mysql lets you have multiple NULL values in unique fields.

Can I use an image from my local file system as background in HTML?

background: url(../images/backgroundImage.jpg) no-repeat center center fixed;

this should help

How do you pass a function as a parameter in C?

Functions can be "passed" as function pointers, as per ISO C11 6.7.6.3p8: "A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1. ". For example, this:

void foo(int bar(int, int));

is equivalent to this:

void foo(int (*bar)(int, int));

CSS selectors ul li a {...} vs ul > li > a {...}

to answer to your second question - performance IS affected - if you are using those selectors with a single (no nested) ul:

<ul>
    <li>jjj</li>
    <li>jjj</li>    
    <li>jjj</li>
</ul>

the child selector ul > li is more performant than ul li because it is more specific. the browser traverse the dom "right to left", so when it finds a li it then looks for a any ul as a parent in the case of a child selector, while it has to traverse the whole dom tree to find any ul ancestors in case of the descendant selector

How to convert a char array back to a string?

Try this:

CharSequence[] charArray = {"a","b","c"};

for (int i = 0; i < charArray.length; i++){
    String str = charArray.toString().join("", charArray[i]);
    System.out.print(str);
}

Adding a caption to an equation in LaTeX

You may want to look at http://tug.ctan.org/tex-archive/macros/latex/contrib/float/ which allows you to define new floats using \newfloat

I say this because captions are usually applied to floats.

Straight ahead equations (those written with $ ... $, $$ ... $$, begin{equation}...) are in-line objects that do not support \caption.

This can be done using the following snippet just before \begin{document}

\usepackage{float}
\usepackage{aliascnt}
\newaliascnt{eqfloat}{equation}
\newfloat{eqfloat}{h}{eqflts}
\floatname{eqfloat}{Equation}

\newcommand*{\ORGeqfloat}{}
\let\ORGeqfloat\eqfloat
\def\eqfloat{%
  \let\ORIGINALcaption\caption
  \def\caption{%
    \addtocounter{equation}{-1}%
    \ORIGINALcaption
  }%
  \ORGeqfloat
}

and when adding an equation use something like

\begin{eqfloat}
\begin{equation}
f( x ) = ax + b
\label{eq:linear}
\end{equation}
\caption{Caption goes here}
\end{eqfloat}

cast or convert a float to nvarchar?

DECLARE @MyFloat [float]

SET @MyFloat = 1000109360.050

SELECT REPLACE (RTRIM (REPLACE (REPLACE (RTRIM ((REPLACE (CAST (CAST (@MyFloat AS DECIMAL (38 ,18 )) AS VARCHAR( max)), '0' , ' '))), ' ' , '0'), '.', ' ')), ' ','.')

Postgres integer arrays as parameters?

See: http://www.postgresql.org/docs/9.1/static/arrays.html

If your non-native driver still does not allow you to pass arrays, then you can:

  • pass a string representation of an array (which your stored procedure can then parse into an array -- see string_to_array)

    CREATE FUNCTION my_method(TEXT) RETURNS VOID AS $$ 
    DECLARE
           ids INT[];
    BEGIN
           ids = string_to_array($1,',');
           ...
    END $$ LANGUAGE plpgsql;
    

    then

    SELECT my_method(:1)
    

    with :1 = '1,2,3,4'

  • rely on Postgres itself to cast from a string to an array

    CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$ 
           ...
    END $$ LANGUAGE plpgsql;
    

    then

    SELECT my_method('{1,2,3,4}')
    
  • choose not to use bind variables and issue an explicit command string with all parameters spelled out instead (make sure to validate or escape all parameters coming from outside to avoid SQL injection attacks.)

    CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$ 
           ...
    END $$ LANGUAGE plpgsql;
    

    then

    SELECT my_method(ARRAY [1,2,3,4])
    

How to properly create composite primary keys - MYSQL

the syntax is CONSTRAINT constraint_name PRIMARY KEY(col1,col2,col3) for example ::

CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

the above example will work if you are writting it while you are creating the table for example ::

CREATE TABLE person (
   P_Id int ,
   ............,
   ............,
   CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
);

to add this constraint to an existing table you need to follow the following syntax

ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY (P_Id,LastName)

How to set JAVA_HOME for multiple Tomcat instances?

You can add setenv.sh in the the bin directory with:

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")

and it will dynamically change when you update your packages.

How to set the Default Page in ASP.NET?

I prefer using the following method:

system.webServer>
  <defaultDocument>
    <files>
      <clear />
      <add value="CreateThing.aspx" />
    </files>
  </defaultDocument>
</system.webServer>

Find all files with name containing string

If the string is at the beginning of the name, you can do this

$ compgen -f .bash
.bashrc
.bash_profile
.bash_prompt

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

  • Xmlns means xml namespace.
  • It is created to avoid naming conflicts in the xml’s.
  • In order to avoid naming conflicts by any other way we need to provide each element with a prefix.
  • to avoid repetitive usage of the prefix in each xml tag we use xmlns at the root of the xml. Hence we have the tag xmlns:android=”http://schemas.android.com/apk/res/android
  • Now android here simply means we are assigning the namespace “http://schemas.android.com/apk/res/android” to it.
  • This namespace is not a URL but a URI also known as URN(universal resource name) which is rarely used in place of URI.
  • Due to this android will be responsible to identify the android related elements in the xml document which would be android:xxxxxxx etc. Without this namespace android:xxxxxxx will be not recognized.

To put in layman’s term :

without xmlns:android=”http://schemas.android.com/apk/res/android” android related tags wont be recognized in the xml document of our layout.

HTML form readonly SELECT tag/input

If the select dropdown is read-only since birth and does not need to change at all, perhaps you should use another control instead? Like a simple <div> (plus hidden form field) or an <input type="text">?

Added: If the dropdown is not read-only all the time and JavaScript is used to enable/disable it, then this is still a solution - just modify the DOM on-the-fly.

Renaming a branch in GitHub

Another way is to rename the following files:

  1. Navigate your project directory.
  2. Rename .git/refs/head/[branch-name] to .git/refs/head/new-branch-name.
  3. Rename .git/refs/remotes/[all-remote-names]/[branch-name] to .git/refs/remotes/[all-remote-names]/new-branch-name.

Rename head and remotes both on your local PC and on origins(s)/remote server(s).

Branch is now renamed (local and remote!)


Attention

If your current branch-name contains slashes (/) Git will create the directories like so:

current branch-name: "awe/some/branch"

  • .git/refs/head/awe/some/branch
  • .git/refs/remotes/[all-remote-names]/awe/some/branch

wish branch-name: "new-branch-name"

  1. Navigate your project directory.
  2. Copy the branch file from .git/refs/*/awe/some/.
  3. Put it in .git/refs/head/.
  4. Copy the branch file from all of .git/refs/remotes/*/awe/some/.
  5. Put them in .git/refs/remotes/*/.
  6. Rename all copied branch files to new-branch-name.
  7. Check if the directory and file structure now looks like this:
  • .git/refs/head/new-branch-name
  • .git/refs/remotes/[all-remote-names]/new-branch-name
  1. Do the same on all your remote origins/servers (if they exist)
  • Info: on remote-servers there are usually no refs/remotes/* directories because you're already on remote-server ;) (Well, maybe in advanced Git configurations it might be possible, but I have never seen that)

Branch is now renamed from awe/some/branch to new-branch-name (local and remote!)

Directories in branch-name got removed.


Information: This way might not be the best, but it still works for people who might have problems with the other ways

how to set cursor style to pointer for links without hrefs

in your css file add this....

a:hover {
 cursor:pointer;
}

if you don't have a css file, add this to the HEAD of your HTML page

<style type="text/css">
 a:hover {
  cursor:pointer;
 }
</style>

also you can use the href="" attribute by returning false at the end of your javascript.

<a href="" onclick="doSomething(); return false;">a link</a>

this is good for many reasons. SEO or if people don't have javascript, the href="" will work. e.g.

<a href="nojavascriptpage.html" onclick="doSomething(); return false;">a link</a>

@see http://www.alistapart.com/articles/behavioralseparation

Edit: Worth noting @BalusC's answer where he mentions :hover is not necessary for the OP's use case. Although other style can be add with the :hover selector.

Set inputType for an EditText Programmatically?

Here are the various Input Types as shown on the standard keyboard.

input types demo

Setting the input type programmatically

editText.setInputType(InputType.TYPE_CLASS_TEXT);

Other options besides TYPE_CLASS_TEXT can be found in the documentation.

Setting the input type in XML

<EditText
    android:inputType="text"
/>

Other options besides text can be found in the documentation.

Supplemental code

Here is the code for the image above.

public class MainActivity extends AppCompatActivity {

    EditText editText;
    TextView textView;
    List<InputTypeItem> inputTypes;
    int counter = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);
        initArray();
    }

    public void onChangeInputTypeButtonClick(View view) {
        if (counter >= inputTypes.size()) {
            startOver();
            return;
        }
        textView.setText(inputTypes.get(counter).name);
        editText.setInputType(inputTypes.get(counter).value);
        editText.setSelection(editText.getText().length());
        counter++;
    }

    private void startOver() {
        counter = 0;
        textView.setText("");
        editText.setInputType(InputType.TYPE_CLASS_TEXT);
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }


    private void initArray() {
        inputTypes = new ArrayList<>();
        inputTypes.add(new InputTypeItem("date",  InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_DATE));
        inputTypes.add(new InputTypeItem("datetime", InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_NORMAL));
        inputTypes.add(new InputTypeItem("none", InputType.TYPE_NULL));
        inputTypes.add(new InputTypeItem("number",  InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL));
        inputTypes.add(new InputTypeItem("numberDecimal",  InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL));
        inputTypes.add(new InputTypeItem("numberPassword",  InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD));
        inputTypes.add(new InputTypeItem("numberSigned", InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED));
        inputTypes.add(new InputTypeItem("phone",  InputType.TYPE_CLASS_PHONE));
        inputTypes.add(new InputTypeItem("text",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL));
        inputTypes.add(new InputTypeItem("textAutoComplete", InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE));
        inputTypes.add(new InputTypeItem("textAutoCorrect",  InputType.TYPE_TEXT_FLAG_AUTO_CORRECT));
        inputTypes.add(new InputTypeItem("textCapCharacters",  InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS));
        inputTypes.add(new InputTypeItem("textCapSentences",  InputType.TYPE_TEXT_FLAG_CAP_SENTENCES));
        inputTypes.add(new InputTypeItem("textCapWords",  InputType.TYPE_TEXT_FLAG_CAP_WORDS));
        inputTypes.add(new InputTypeItem("textEmailAddress",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS));
        inputTypes.add(new InputTypeItem("textEmailSubject", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_SUBJECT));
        inputTypes.add(new InputTypeItem("textFilter",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_FILTER));
        inputTypes.add(new InputTypeItem("textLongMessage",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE));
        inputTypes.add(new InputTypeItem("textMultiLine",  InputType.TYPE_TEXT_FLAG_MULTI_LINE));
        inputTypes.add(new InputTypeItem("textNoSuggestions", InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS));
        inputTypes.add(new InputTypeItem("textPassword",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD));
        inputTypes.add(new InputTypeItem("textPersonName", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PERSON_NAME));
        inputTypes.add(new InputTypeItem("textPhonetic",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PHONETIC));
        inputTypes.add(new InputTypeItem("textPostalAddress", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS));
        inputTypes.add(new InputTypeItem("textShortMessage", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE));
        inputTypes.add(new InputTypeItem("textUri",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI));
        inputTypes.add(new InputTypeItem("textVisiblePassword",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD));
        inputTypes.add(new InputTypeItem("textWebEditText",  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT));
        inputTypes.add(new InputTypeItem("textWebEmailAddress", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS));
        inputTypes.add(new InputTypeItem("textWebPassword", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD));
        inputTypes.add(new InputTypeItem("time", InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_TIME));
    }

    class InputTypeItem {
        private String name;
        private int value;
        InputTypeItem(String name, int value) {
            this.name = name;
            this.value = value;
        }
    }
}

See also

How to use Monitor (DDMS) tool to debug application

Could it be a problem with past preview versions of Android Studio ? nowadays "beta" has replaced the "preview". I try it out step by step debugging while using Memory Monitor at same time by Android Studio (Beta) 0.8.11 on OSX 10.9.5 without any problems.

The tutorial Debugging with Android Studio also helps, specially this paragraph :

To track memory allocation of objects:

  1. Start your app as described in Run Your App in Debug Mode.
  2. Click Android to open the Android DDMS tool window.
  3. On the Android DDMS tool window, select the Devices | logcat tab.
  4. Select your device from the dropdown list.
  5. Select your app by its package name from the list of running apps.
  6. Click Start Allocation Tracking Interact with your app on the device. Click Stop Allocation Tracking

Here a couple of screenshot while debugging step by step on a breakpoint a monitoring the memory on the emulator:
breakpointmemory monitor

Push items into mongo array via mongoose

First I tried this code

const peopleSchema = new mongoose.Schema({
  name: String,
  friends: [
    {
      firstName: String,
      lastName: String,
    },
  ],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
  name: "Yash Salvi",
  notes: [
    {
      firstName: "Johnny",
      lastName: "Johnson",
    },
  ],
});
first.save();
const friendNew = {
  firstName: "Alice",
  lastName: "Parker",
};
People.findOneAndUpdate(
  { name: "Yash Salvi" },
  { $push: { friends: friendNew } },
  function (error, success) {
    if (error) {
      console.log(error);
    } else {
      console.log(success);
    }
  }
);

But I noticed that only first friend (i.e. Johhny Johnson) gets saved and the objective to push array element in existing array of "friends" doesn't seem to work as when I run the code , in database in only shows "First friend" and "friends" array has only one element ! So the simple solution is written below

const peopleSchema = new mongoose.Schema({
  name: String,
  friends: [
    {
      firstName: String,
      lastName: String,
    },
  ],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
  name: "Yash Salvi",
  notes: [
    {
      firstName: "Johnny",
      lastName: "Johnson",
    },
  ],
});
first.save();
const friendNew = {
  firstName: "Alice",
  lastName: "Parker",
};
People.findOneAndUpdate(
  { name: "Yash Salvi" },
  { $push: { friends: friendNew } },
  { upsert: true }
);

Adding "{ upsert: true }" solved problem in my case and once code is saved and I run it , I see that "friends" array now has 2 elements ! The upsert = true option creates the object if it doesn't exist. default is set to false.

if it doesn't work use below snippet

People.findOneAndUpdate(
  { name: "Yash Salvi" },
  { $push: { friends: friendNew } },
).exec();

chai test array equality doesn't work as expected

For expect, .equal will compare objects rather than their data, and in your case it is two different arrays.

Use .eql in order to deeply compare values. Check out this link.
Or you could use .deep.equal in order to simulate same as .eql.
Or in your case you might want to check .members.

For asserts you can use .deepEqual, link.

PHP code is not being executed, instead code shows on the page

note for php 7 users, add this to your httpd.conf file:

# PHP 7 specific configuration
<IfModule php7_module>
    AddType application/x-httpd-php .php
    AddType application/x-httpd-php-source .phps
    <IfModule dir_module>
        DirectoryIndex index.html index.php
    </IfModule>
</IfModule>

How do I resolve git saying "Commit your changes or stash them before you can merge"?

You can try one of the following methods:

rebase

For simple changes try rebasing on top of it while pulling the changes, e.g.

git pull origin master -r

So it'll apply your current branch on top of the upstream branch after fetching.

This is equivalent to: checkout master, fetch and rebase origin/master git commands.

This is a potentially dangerous mode of operation. It rewrites history, which does not bode well when you published that history already. Do not use this option unless you have read git-rebase(1) carefully.


checkout

If you don't care about your local changes, you can switch to other branch temporary (with force), and switch it back, e.g.

git checkout origin/master -f
git checkout master -f

reset

If you don't care about your local changes, try to reset it to HEAD (original state), e.g.

git reset HEAD --hard

If above won't help, it may be rules in your git normalization file (.gitattributes) so it's better to commit what it says. Or your file system doesn't support permissions, so you've to disable filemode in your git config.

Related: How do I force "git pull" to overwrite local files?

Swift error : signal SIGABRT how to solve it

I had the same problem. I made a button in the storyboard and connected it to the ViewController, and then later on deleted the button. So the connection was still there, but the button was not, and so I got the same error as you.

To Fix:

Go to the connection inspector (the arrow in the top right corner, in your storyboard), and delete any unused connections.

git discard all changes and pull from upstream

You can do it in a single command:

git fetch --all && git reset --hard origin/master

Or in a pair of commands:

git fetch --all
git reset --hard origin/master

Note than you will lose ALL your local changes

How to BULK INSERT a file into a *temporary* table where the filename is a variable?

You could always construct the #temp table in dynamic SQL. For example, right now I guess you have been trying:

CREATE TABLE #tmp(a INT, b INT, c INT);

DECLARE @sql NVARCHAR(1000);

SET @sql = N'BULK INSERT #tmp ...' + @variables;

EXEC master.sys.sp_executesql @sql;

SELECT * FROM #tmp;

This makes it tougher to maintain (readability) but gets by the scoping issue:

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'CREATE TABLE #tmp(a INT, b INT, c INT);

BULK INSERT #tmp ...' + @variables + ';

SELECT * FROM #tmp;';

EXEC master.sys.sp_executesql @sql;

EDIT 2011-01-12

In light of how my almost 2-year old answer was suddenly deemed incomplete and unacceptable, by someone whose answer was also incomplete, how about:

CREATE TABLE #outer(a INT, b INT, c INT);

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'SET NOCOUNT ON; 

CREATE TABLE #inner(a INT, b INT, c INT);

BULK INSERT #inner ...' + @variables + ';

SELECT * FROM #inner;';

INSERT #outer EXEC master.sys.sp_executesql @sql;

Unable to load Private Key. (PEM routines:PEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY)

Open the key file in Notepad++ and verify the encoding. If it says UTF-8-BOM then change it to UTF-8. Save the file and try again.

How to delete/unset the properties of a javascript object?

simply use delete, but be aware that you should read fully what the effects are of using this:

 delete object.index; //true
 object.index; //undefined

but if I was to use like so:

var x = 1; //1
delete x; //false
x; //1

but if you do wish to delete variables in the global namespace, you can use it's global object such as window, or using this in the outermost scope i.e

var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true

http://perfectionkills.com/understanding-delete/

another fact is that using delete on an array will not remove the index but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity, when it comes to array's you should use splice which is a prototype of the array object.

Example Array:

var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

if I was to do:

delete myCars[1];

the resulting array would be:

["Saab", undefined, "BMW"]

but using splice like so:

myCars.splice(1,1);

would result in:

["Saab", "BMW"]

You should not use <Link> outside a <Router>

Make it simple:

render(<BrowserRouter><Main /></BrowserRouter>, document.getElementById('root'));

and don't forget: import { BrowserRouter } from "react-router-dom";

Strings and character with printf

If you want to display a single character then you can also use name[0] instead of using pointer.

It will serve your purpose but if you want to display full string using %c, you can try this:

#include<stdio.h>
void main()
{ 
    char name[]="siva";
    int i;
    for(i=0;i<4;i++)
    {
        printf("%c",*(name+i));
    }
} 

C# - Winforms - Global Variables

They have already answered how to use a global variable.

I will tell you why the use of global variables is a bad idea as a result of this question carried out in stackoverflow in Spanish.

Explicit translation of the text in Spanish:

Impact of the change

The problem with global variables is that they create hidden dependencies. When it comes to large applications, you yourself do not know / remember / you are clear about the objects you have and their relationships.

So, you can not have a clear notion of how many objects your global variable is using. And if you want to change something of the global variable, for example, the meaning of each of its possible values, or its type? How many classes or compilation units will that change affect? If the amount is small, it may be worth making the change. If the impact will be great, it may be worth looking for another solution.

But what is the impact? Because a global variable can be used anywhere in the code, it can be very difficult to measure it.

In addition, always try to have a variable with the shortest possible life time, so that the amount of code that makes use of that variable is the minimum possible, and thus better understand its purpose, and who modifies it.

A global variable lasts for the duration of the program, and therefore, anyone can use the variable, either to read it, or even worse, to change its value, making it more difficult to know what value the variable will have at any given program point. .

Order of destruction

Another problem is the order of destruction. Variables are always destroyed in reverse order of their creation, whether they are local or global / static variables (an exception is the primitive types, int,enums, etc., which are never destroyed if they are global / static until they end the program).

The problem is that it is difficult to know the order of construction of the global (or static) variables. In principle, it is indeterminate.

If all your global / static variables are in a single compilation unit (that is, you only have a .cpp), then the order of construction is the same as the writing one (that is, variables defined before, are built before).

But if you have more than one .cpp each with its own global / static variables, the global construction order is indeterminate. Of course, the order in each compilation unit (each .cpp) in particular, is respected: if the global variableA is defined before B,A will be built before B, but It is possible that between A andB variables of other .cpp are initialized. For example, if you have three units with the following global / static variables:

Image1

In the executable it could be created in this order (or in any other order as long as the relative order is respected within each .cpp):

Image2

Why is this important? Because if there are relations between different static global objects, for example, that some use others in their destructors, perhaps, in the destructor of a global variable, you use another global object from another compilation unit that turns out to be already destroyed ( have been built later).

Hidden dependencies and * test cases *

I tried to find the source that I will use in this example, but I can not find it (anyway, it was to exemplify the use of singletons, although the example is applicable to global and static variables). Hidden dependencies also create new problems related to controlling the behavior of an object, if it depends on the state of a global variable.

Imagine you have a payment system, and you want to test it to see how it works, since you need to make changes, and the code is from another person (or yours, but from a few years ago). You open a new main, and you call the corresponding function of your global object that provides a bank payment service with a card, and it turns out that you enter your data and they charge you. How, in a simple test, have I used a production version? How can I do a simple payment test?

After asking other co-workers, it turns out that you have to "mark true", a global bool that indicates whether we are in test mode or not, before beginning the collection process. Your object that provides the payment service depends on another object that provides the mode of payment, and that dependency occurs in an invisible way for the programmer.

In other words, the global variables (or singletones), make it impossible to pass to "test mode", since global variables can not be replaced by "testing" instances (unless you modify the code where said code is created or defined). global variable, but we assume that the tests are done without modifying the mother code).

Solution

This is solved by means of what is called * dependency injection *, which consists in passing as a parameter all the dependencies that an object needs in its constructor or in the corresponding method. In this way, the programmer ** sees ** what has to happen to him, since he has to write it in code, making the developers gain a lot of time.

If there are too many global objects, and there are too many parameters in the functions that need them, you can always group your "global objects" into a class, style * factory *, that builds and returns the instance of the "global object" (simulated) that you want , passing the factory as a parameter to the objects that need the global object as dependence.

If you pass to test mode, you can always create a testing factory (which returns different versions of the same objects), and pass it as a parameter without having to modify the target class.

But is it always bad?

Not necessarily, there may be good uses for global variables. For example, constant values ??(the PI value). Being a constant value, there is no risk of not knowing its value at a given point in the program by any type of modification from another module. In addition, constant values ??tend to be primitive and are unlikely to change their definition.

It is more convenient, in this case, to use global variables to avoid having to pass the variables as parameters, simplifying the signatures of the functions.

Another can be non-intrusive "global" services, such as a logging class (saving what happens in a file, which is usually optional and configurable in a program, and therefore does not affect the application's nuclear behavior), or std :: cout,std :: cin or std :: cerr, which are also global objects.

Any other thing, even if its life time coincides almost with that of the program, always pass it as a parameter. Even the variable could be global in a module, only in it without any other having access, but that, in any case, the dependencies are always present as parameters.

Answer by: Peregring-lk

How can I prevent the textarea from stretching beyond his parent DIV element? (google-chrome issue only)

To disable resizing completely:

textarea {
    resize: none;
}

To allow only vertical resizing:

textarea {
    resize: vertical;
}

To allow only horizontal resizing:

textarea {
    resize: horizontal;
}

Or you can limit size:

textarea {
    max-width: 100px; 
    max-height: 100px;
}

To limit size to parents width and/or height:

textarea {
    max-width: 100%; 
    max-height: 100%;
}

Meaning of "[: too many arguments" error from if [] (square brackets)

Another scenario that you can get the [: too many arguments or [: a: binary operator expected errors is if you try to test for all arguments "$@"

if [ -z "$@" ]
then
    echo "Argument required."
fi

It works correctly if you call foo.sh or foo.sh arg1. But if you pass multiple args like foo.sh arg1 arg2, you will get errors. This is because it's being expanded to [ -z arg1 arg2 ], which is not a valid syntax.

The correct way to check for existence of arguments is [ "$#" -eq 0 ]. ($# is the number of arguments).

Truncate Two decimal places without rounding

        public static void ReminderDigints(decimal? number, out decimal? Value,  out decimal? Reminder)
        {
            Reminder = null;
            Value = null;
            if (number.HasValue)
            {
                Value = Math.Floor(number.Value);
                Reminder = (number - Math.Truncate(number.Value));
            }
        }



        decimal? number= 50.55m;             
        ReminderDigints(number, out decimal? Value, out decimal? Reminder);

How to change default language for SQL Server?

Using SQL Server Management Studio

To configure the default language option

  1. In Object Explorer, right-click a server and select Properties.
  2. Click the Misc server settings node.
  3. In the Default language for users box, choose the language in which Microsoft SQL Server should display system messages. The default language is English.

Using Transact-SQL

To configure the default language option

  1. Connect to the Database Engine.
  2. From the Standard bar, click New Query.
  3. Copy and paste the following example into the query window and click Execute.

This example shows how to use sp_configure to configure the default language option to French

USE AdventureWorks2012 ;
GO
EXEC sp_configure 'default language', 2 ;
GO
RECONFIGURE ;
GO

The 33 languages of SQL Server

| LANGID |        ALIAS        |
|--------|---------------------|
|    0   | English             |
|    1   | German              |
|    2   | French              |
|    3   | Japanese            |
|    4   | Danish              |
|    5   | Spanish             |
|    6   | Italian             |
|    7   | Dutch               |
|    8   | Norwegian           |
|    9   | Portuguese          |
|   10   | Finnish             |
|   11   | Swedish             |
|   12   | Czech               |
|   13   | Hungarian           |
|   14   | Polish              |
|   15   | Romanian            |
|   16   | Croatian            |
|   17   | Slovak              |
|   18   | Slovenian           |
|   19   | Greek               |
|   20   | Bulgarian           |
|   21   | Russian             |
|   22   | Turkish             |
|   23   | British English     |
|   24   | Estonian            |
|   25   | Latvian             |
|   26   | Lithuanian          |
|   27   | Brazilian           |
|   28   | Traditional Chinese |
|   29   | Korean              |
|   30   | Simplified Chinese  |
|   31   | Arabic              |
|   32   | Thai                |
|   33   | Bokmål              |

How to call javascript function from asp.net button click event

You're already prepending the hash sign in your showDialog() function, and you're missing single quotes in your second code snippet. You should also return false from the handler to prevent a postback from occurring. Try:

<asp:Button ID="ButtonAdd" runat="server" Text="Add"
    OnClientClick="showDialog('<%=addPerson.ClientID %>'); return false;" />

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

Since JsonSerializer is deprecated in .Net 4.0+ I used http://www.newtonsoft.com/json to solve this issue.

NuGet- > Install-Package Newtonsoft.Json

Android, Java: HTTP POST Request

HTTP request POST in java does not dump the answer?

public class HttpClientExample 
{
 private final String USER_AGENT = "Mozilla/5.0";
 public static void main(String[] args) throws Exception 
 {

HttpClientExample http = new HttpClientExample();

System.out.println("\nTesting 1 - Send Http POST request");
http.sendPost();

}

 // HTTP POST request
 private void sendPost() throws Exception {
 String url = "http://www.wmtechnology.org/Consultar-RUC/index.jsp";

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);

// add header
post.setHeader("User-Agent", USER_AGENT);

List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("accion", "busqueda"));
        urlParameters.add(new BasicNameValuePair("modo", "1"));
urlParameters.add(new BasicNameValuePair("nruc", "10469415177"));

post.setEntity(new UrlEncodedFormEntity(urlParameters));

HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +response.getStatusLine().getStatusCode());

 BufferedReader rd = new BufferedReader(new 
 InputStreamReader(response.getEntity().getContent()));

  StringBuilder result = new StringBuilder();
  String line = "";
  while ((line = rd.readLine()) != null) 
        {
      result.append(line);
                System.out.println(line);
    }

   }
 }

This is the web: http://www.wmtechnology.org/Consultar-RUC/index.jsp,from you can consult Ruc without captcha. Your opinions are welcome!

how to fix groovy.lang.MissingMethodException: No signature of method:

You can also get this error if the objects you're passing to the method are out of order. In other words say your method takes, in order, a string, an integer, and a date. If you pass a date, then a string, then an integer you will get the same error message.

Zsh: Conda/Pip installs command not found

If anaconda is fully updated, a simple "conda init zsh" should work. Navigate into the anaconda3 folder using

cd /path/to/anaconda3/

of course replacing "/path/to/anaconda/" with "~/anaconda3" or "/anaconda3" or wherever the "anaconda3" folder is kept.

To make sure it's updated, run

./bin/conda update --prefix . anaconda

After this, running

./bin/conda init zsh

(or whatever shell you're using) will finish the job cleanly.

Java 8 - Best way to transform a list: map or foreach?

If using 3rd Pary Libaries is ok cyclops-react defines Lazy extended collections with this functionality built in. For example we could simply write

ListX myListToParse;

ListX myFinalList = myListToParse.filter(elt -> elt != null) .map(elt -> doSomething(elt));

myFinalList is not evaluated until first access (and there after the materialized list is cached and reused).

[Disclosure I am the lead developer of cyclops-react]

Should I use Java's String.format() if performance is important?

I took hhafez code and added a memory test:

private static void test() {
    Runtime runtime = Runtime.getRuntime();
    long memory;
    ...
    memory = runtime.freeMemory();
    // for loop code
    memory = memory-runtime.freeMemory();

I run this separately for each approach, the '+' operator, String.format and StringBuilder (calling toString()), so the memory used will not be affected by other approaches. I added more concatenations, making the string as "Blah" + i + "Blah"+ i +"Blah" + i + "Blah".

The result are as follow (average of 5 runs each):
Approach       Time(ms)  Memory allocated (long)
'+' operator     747           320,504
String.format  16484       373,312
StringBuilder  769           57,344

We can see that String '+' and StringBuilder are practically identical time-wise, but StringBuilder is much more efficient in memory use. This is very important when we have many log calls (or any other statements involving strings) in a time interval short enough so the Garbage Collector won't get to clean the many string instances resulting of the '+' operator.

And a note, BTW, don't forget to check the logging level before constructing the message.

Conclusions:

  1. I'll keep on using StringBuilder.
  2. I have too much time or too little life.

When use getOne and findOne methods Spring Data JPA

1. Why does the getOne(id) method fail?

See this section in the docs. You overriding the already in place transaction might be causing the issue. However, without more info this one is difficult to answer.

2. When I should use the getOne(id) method?

Without digging into the internals of Spring Data JPA, the difference seems to be in the mechanism used to retrieve the entity.

If you look at the JavaDoc for getOne(ID) under See Also:

See Also:
EntityManager.getReference(Class, Object)

it seems that this method just delegates to the JPA entity manager's implementation.

However, the docs for findOne(ID) do not mention this.

The clue is also in the names of the repositories. JpaRepository is JPA specific and therefore can delegate calls to the entity manager if so needed. CrudRepository is agnostic of the persistence technology used. Look here. It's used as a marker interface for multiple persistence technologies like JPA, Neo4J etc.

So there's not really a 'difference' in the two methods for your use cases, it's just that findOne(ID) is more generic than the more specialised getOne(ID). Which one you use is up to you and your project but I would personally stick to the findOne(ID) as it makes your code less implementation specific and opens the doors to move to things like MongoDB etc. in the future without too much refactoring :)

How to use Python to execute a cURL command?

Some background: I went looking for exactly this question because I had to do something to retrieve content, but all I had available was an old version of python with inadequate SSL support. If you're on an older MacBook, you know what I'm talking about. In any case, curl runs fine from a shell (I suspect it has modern SSL support linked in) so sometimes you want to do this without using requests or urllib2.

You can use the subprocess module to execute curl and get at the retrieved content:

import subprocess

// 'response' contains a []byte with the retrieved content.
// use '-s' to keep curl quiet while it does its job, but
// it's useful to omit that while you're still writing code
// so you know if curl is working
response = subprocess.check_output(['curl', '-s', baseURL % page_num])

Python 3's subprocess module also contains .run() with a number of useful options. I'll leave it to someone who is actually running python 3 to provide that answer.

How to restore PostgreSQL dump file into Postgres databases?

You didn't mention how your backup was made, so the generic answer is: Usually with the psql tool.

Depending on what pg_dump was instructed to dump, the SQL file can have different sets of SQL commands. For example, if you instruct pg_dump to dump a database using --clean and --schema-only, you can't expect to be able to restore the database from that dump as there will be no SQL commands for COPYing (or INSERTing if --inserts is used ) the actual data in the tables. A dump like that will contain only DDL SQL commands, and will be able to recreate the schema but not the actual data.

A typical SQL dump is restored with psql:

psql (connection options here) database  < yourbackup.sql

or alternatively from a psql session,

psql (connection options here) database
database=# \i /path/to/yourbackup.sql

In the case of backups made with pg_dump -Fc ("custom format"), which is not a plain SQL file but a compressed file, you need to use the pg_restore tool.

If you're working on a unix-like, try this:

man psql
man pg_dump
man pg_restore

otherwise, take a look at the html docs. Good luck!

How many significant digits do floats and doubles have in java?

A 32-bit float has about 7 digits of precision and a 64-bit double has about 16 digits of precision

Long answer:

Floating-point numbers have three components:

  1. A sign bit, to determine if the number is positive or negative.
  2. An exponent, to determine the magnitude of the number.
  3. A fraction, which determines how far between two exponent values the number is. This is sometimes called “the significand, mantissa, or coefficient”

Essentially, this works out to sign * 2^exponent * (1 + fraction). The “size” of the number, it’s exponent, is irrelevant to us, because it only scales the value of the fraction portion. Knowing that log10(n) gives the number of digits of n,† we can determine the precision of a floating point number with log10(largest_possible_fraction). Because each bit in a float stores 2 possibilities, a binary number of n bits can store a number up to 2n - 1 (a total of 2n values where one of the values is zero). This gets a bit hairier, because it turns out that floating point numbers are stored with one less bit of fraction than they can use, because zeroes are represented specially and all non-zero numbers have at least one non-zero binary bit.‡

Combining this, the digits of precision for a floating point number is log10(2n), where n is the number of bits of the floating point number’s fraction. A 32-bit float has 24 bits of fraction for ˜7.22 decimal digits of precision, and a 64-bit double has 53 bits of fraction for ˜15.95 decimal digits of precision.

For more on floating point accuracy, you might want to read about the concept of a machine epsilon.


† For n = 1 at least — for other numbers your formula will look more like ?log10(|n|)? + 1.

‡ “This rule is variously called the leading bit convention, the implicit bit convention, or the hidden bit convention.” (Wikipedia)

Move existing, uncommitted work to a new branch in Git

This may be helpful for all using tools for GIT

Command

Switch branch - it will move your changes to new-branch. Then you can commit changes.

 $ git checkout -b <new-branch>

TortoiseGIT

Right-click on your repository and then use TortoiseGit->Switch/Checkout

enter image description here enter image description here

SourceTree

Use the "Checkout" button to switch branch. You will see the "checkout" button at the top after clicking on a branch. Changes from the current branch will be applied automatically. Then you can commit them.

enter image description here

Checking on a thread / remove from list

As TokenMacGuy says, you should use thread.is_alive() to check if a thread is still running. To remove no longer running threads from your list you can use a list comprehension:

for t in my_threads:
    if not t.is_alive():
        # get results from thread
        t.handled = True
my_threads = [t for t in my_threads if not t.handled]

This avoids the problem of removing items from a list while iterating over it.

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

If you simply need to get the basic snapshot of the files + folders. Follow these baby steps:

  • Press Windows + R
  • Press Enter
  • Type cmd
  • Press Enter
  • Type dir -s
  • Press Enter

How to create a file in memory for user to download, but not through server?

If you just want to convert a string to be available for download you can try this using jQuery.

$('a.download').attr('href', 'data:application/csv;charset=utf-8,' + encodeURI(data));

R: rJava package install failing

That is how I make it work :

In Linux (Ubuntu 16.04)

sudo apt-get install default-jre
sudo apt-get install default-jdk
sudo R CMD javareconf

in R:

install.packages("rJava")

What does functools.wraps do?

As of python 3.5+:

@functools.wraps(f)
def g():
    pass

Is an alias for g = functools.update_wrapper(g, f). It does exactly three things:

  • it copies the __module__, __name__, __qualname__, __doc__, and __annotations__ attributes of f on g. This default list is in WRAPPER_ASSIGNMENTS, you can see it in the functools source.
  • it updates the __dict__ of g with all elements from f.__dict__. (see WRAPPER_UPDATES in the source)
  • it sets a new __wrapped__=f attribute on g

The consequence is that g appears as having the same name, docstring, module name, and signature than f. The only problem is that concerning the signature this is not actually true: it is just that inspect.signature follows wrapper chains by default. You can check it by using inspect.signature(g, follow_wrapped=False) as explained in the doc. This has annoying consequences:

  • the wrapper code will execute even when the provided arguments are invalid.
  • the wrapper code can not easily access an argument using its name, from the received *args, **kwargs. Indeed one would have to handle all cases (positional, keyword, default) and therefore to use something like Signature.bind().

Now there is a bit of confusion between functools.wraps and decorators, because a very frequent use case for developing decorators is to wrap functions. But both are completely independent concepts. If you're interested in understanding the difference, I implemented helper libraries for both: decopatch to write decorators easily, and makefun to provide a signature-preserving replacement for @wraps. Note that makefun relies on the same proven trick than the famous decorator library.

overlay a smaller image on a larger image python OpenCv

Here it is:

def put4ChannelImageOn4ChannelImage(back, fore, x, y):
    rows, cols, channels = fore.shape    
    trans_indices = fore[...,3] != 0 # Where not transparent
    overlay_copy = back[y:y+rows, x:x+cols] 
    overlay_copy[trans_indices] = fore[trans_indices]
    back[y:y+rows, x:x+cols] = overlay_copy

#test
background = np.zeros((1000, 1000, 4), np.uint8)
background[:] = (127, 127, 127, 1)
overlay = cv2.imread('imagee.png', cv2.IMREAD_UNCHANGED)
put4ChannelImageOn4ChannelImage(background, overlay, 5, 5)

How to find first element of array matching a boolean condition in JavaScript?

foundElement = myArray[myArray.findIndex(element => //condition here)];

Unable to get provider com.google.firebase.provider.FirebaseInitProvider

This should works:

Step1:

defaultConfig {
    applicationId "service.ingreens.com.gpsautoon"
    minSdkVersion 17
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

Step 2:

compile 'com.android.support:multidex:1.0.1'

Step 3: Take another class

public class MyApplication extends MultiDexApplication {
}

Step 4: Add this line on manifest

<application
    android:name="android.support.multidex.MultiDexApplication">
</application>

OSError: [Errno 2] No such file or directory while using python subprocess in Django

Can't upvote so I'll repost @jfs comment cause I think it should be more visible.

@AnneTheAgile: shell=True is not required. Moreover you should not use it unless it is necessary (see @ valid's comment). You should pass each command-line argument as a separate list item instead e.g., use ['command', 'arg 1', 'arg 2'] instead of "command 'arg 1' 'arg 2'". – jfs Mar 3 '15 at 10:02

How to enable zoom controls and pinch zoom in a WebView?

Try this code, I get working fine.

 webSettings.setSupportZoom(true);
 webSettings.setBuiltInZoomControls(true);
 webSettings.setDisplayZoomControls(false);

Parsing query strings on Android

using Guava:

Multimap<String,String> parseQueryString(String queryString, String encoding) {
    LinkedListMultimap<String, String> result = LinkedListMultimap.create();

    for(String entry : Splitter.on("&").omitEmptyStrings().split(queryString)) {
        String pair [] = entry.split("=", 2);
        try {
            result.put(URLDecoder.decode(pair[0], encoding), pair.length == 2 ? URLDecoder.decode(pair[1], encoding) : null);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    return result;
}

Python decorators in classes

I found this question while researching a very similar problem. My solution is to split the problem into two parts. First, you need to capture the data that you want to associate with the class methods. In this case, handler_for will associate a Unix command with handler for that command's output.

class OutputAnalysis(object):
    "analyze the output of diagnostic commands"
    def handler_for(name):
        "decorator to associate a function with a command"
        def wrapper(func):
            func.handler_for = name
            return func
        return wrapper
    # associate mount_p with 'mount_-p.txt'
    @handler_for('mount -p')
    def mount_p(self, slurped):
        pass

Now that we've associated some data with each class method, we need to gather that data and store it in a class attribute.

OutputAnalysis.cmd_handler = {}
for value in OutputAnalysis.__dict__.itervalues():
    try:
        OutputAnalysis.cmd_handler[value.handler_for] = value
    except AttributeError:
        pass

Sending files using POST with HttpURLConnection

To upload file on server with some parameter using MultipartUtility in simple way.

MultipartUtility.java

public class MultipartUtility {

    private final String boundary;
    private static final String LINE_FEED = "\r\n";
    private HttpURLConnection httpConn;
    private String charset;
    private OutputStream outputStream;
    private PrintWriter writer;

    /**
     * This constructor initializes a new HTTP POST request with content type
     * is set to multipart/form-data
     *
     * @param requestURL
     * @param charset
     * @throws IOException
     */
    public MultipartUtility(String requestURL, String charset)
            throws IOException {
        this.charset = charset;

        // creates a unique boundary based on time stamp
        boundary = "===" + System.currentTimeMillis() + "===";

        URL url = new URL(requestURL);
        Log.e("URL", "URL : " + requestURL.toString());
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);
        httpConn.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + boundary);
        httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
        httpConn.setRequestProperty("Test", "Bonjour");
        outputStream = httpConn.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
                true);
    }

    /**
     * Adds a form field to the request
     *
     * @param name  field name
     * @param value field value
     */
    public void addFormField(String name, String value) {
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
                .append(LINE_FEED);
        writer.append("Content-Type: text/plain; charset=" + charset).append(
                LINE_FEED);
        writer.append(LINE_FEED);
        writer.append(value).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Adds a upload file section to the request
     *
     * @param fieldName  name attribute in <input type="file" name="..." />
     * @param uploadFile a File to be uploaded
     * @throws IOException
     */
    public void addFilePart(String fieldName, File uploadFile)
            throws IOException {
        String fileName = uploadFile.getName();
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append(
                "Content-Disposition: form-data; name=\"" + fieldName
                        + "\"; filename=\"" + fileName + "\"")
                .append(LINE_FEED);
        writer.append(
                "Content-Type: "
                        + URLConnection.guessContentTypeFromName(fileName))
                .append(LINE_FEED);
        writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
        writer.append(LINE_FEED);
        writer.flush();

        FileInputStream inputStream = new FileInputStream(uploadFile);
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.flush();
        inputStream.close();

        writer.append(LINE_FEED);
        writer.flush();
    }

    /**
     * Adds a header field to the request.
     *
     * @param name  - name of the header field
     * @param value - value of the header field
     */
    public void addHeaderField(String name, String value) {
        writer.append(name + ": " + value).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Completes the request and receives response from the server.
     *
     * @return a list of Strings as response in case the server returned
     * status OK, otherwise an exception is thrown.
     * @throws IOException
     */
    public String finish() throws IOException {
        StringBuffer response = new StringBuffer();

        writer.append(LINE_FEED).flush();
        writer.append("--" + boundary + "--").append(LINE_FEED);
        writer.close();

        // checks server's status code first
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpConn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            httpConn.disconnect();
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }

        return response.toString();
    }
}

To upload you file along with parameters.

NOTE : put this code below in non-ui-thread to get response.

String charset = "UTF-8";
String requestURL = "YOUR_URL";

MultipartUtility multipart = new MultipartUtility(requestURL, charset);
multipart.addFormField("param_name_1", "param_value");
multipart.addFormField("param_name_2", "param_value");
multipart.addFormField("param_name_3", "param_value");
multipart.addFilePart("file_param_1", new File(file_path));
String response = multipart.finish(); // response from server.

LinkButton Send Value to Code Behind OnClick

Add a CommandName attribute, and optionally a CommandArgument attribute, to your LinkButton control. Then set the OnCommand attribute to the name of your Command event handler.

<asp:LinkButton ID="ENameLinkBtn" runat="server" CommandName="MyValueGoesHere" CommandArgument="OtherValueHere" 
          style="font-weight: 700; font-size: 8pt;" OnCommand="ENameLinkBtn_Command" ><%# Eval("EName") %></asp:LinkButton>

<asp:Label id="Label1" runat="server"/>

Then it will be available when in your handler:

protected void ENameLinkBtn_Command (object sender, CommandEventArgs e)
{
   Label1.Text = "You chose: " + e.CommandName + " Item " + e.CommandArgument;
}

More info on MSDN

Is there a way to instantiate a class by name in Java?

something like this should work...

String name = "Test2";//Name of the class
        Class myClass = Class.forName(name);
        Object o = myClass.newInstance();

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

You're looking for RAISERROR.

From MSDN:

Generates an error message and initiates error processing for the session. RAISERROR can either reference a user-defined message stored in the sys.messages catalog view or build a message dynamically. The message is returned as a server error message to the calling application or to an associated CATCH block of a TRY…CATCH construct.

CodeProject has a good article that also describes in-depth the details of how it works and how to use it.

MomentJS getting JavaScript Date in UTC

Calling toDate will create a copy (the documentation is down-right wrong about it not being a copy), of the underlying JS Date object. JS Date object is stored in UTC and will always print to eastern time. Without getting into whether .utc() modifies the underlying object that moment wraps use the code below.

You don't need moment for this.

new Date().getTime()

This works, because JS Date at its core is in UTC from the Unix Epoch. It's extraordinarily confusing and I believe a big flaw in the interface to mix local and UTC times like this with no descriptions in the methods.

How does internationalization work in JavaScript?

You can also try another library - https://github.com/wikimedia/jquery.i18n .

In addition to parameter replacement and multiple plural forms, it has support for gender a rather unique feature of custom grammar rules that some languages need.

Convert array to string in NodeJS

You're using an Array like an "associative array", which does not exist in JavaScript. Use an Object ({}) instead.

If you are going to continue with an array, realize that toString() will join all the numbered properties together separated by a comma. (the same as .join(",")).

Properties like a and b will not come up using this method because they are not in the numeric indexes. (ie. the "body" of the array)

In JavaScript, Array inherits from Object, so you can add and delete properties on it like any other object. So for an array, the numbered properties (they're technically just strings under the hood) are what counts in methods like .toString(), .join(), etc. Your other properties are still there and very much accessible. :)

Read Mozilla's documentation for more information about Arrays.

var aa = [];

// these are now properties of the object, but not part of the "array body"
aa.a = "A";
aa.b = "B";

// these are part of the array's body/contents
aa[0] = "foo";
aa[1] = "bar";

aa.toString(); // most browsers will say "foo,bar" -- the same as .join(",")

Open a facebook link by native Facebook app on iOS

This will open the URL in Safari:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.facebook.com/comments.php?href=http://wombeta.jiffysoftware.com/ViewWOMPrint.aspx?WPID=317"]];

For the iphone, you can launch the Facebook app if installed by using a url starting with fb://

More information can be found here: http://iphonedevtools.com/?p=302 also here: http://wiki.akosma.com/IPhone_URL_Schemes#Facebook

Stolen from the above site:

fb://profile – Open Facebook app to the user’s profile
fb://friends – Open Facebook app to the friends list
fb://notifications – Open Facebook app to the notifications list (NOTE: there appears to be a bug with this URL. The Notifications page opens. However, it’s not possible to navigate to anywhere else in the Facebook app)
fb://feed – Open Facebook app to the News Feed
fb://events – Open Facebook app to the Events page
fb://requests – Open Facebook app to the Requests list
fb://notes - Open Facebook app to the Notes page
fb://albums – Open Facebook app to Photo Albums list

To launch the above URLs:

NSURL *theURL = [NSURL URLWithString:@"fb://<insert function here>"];
[[UIApplication sharedApplication] openURL:theURL];

How to view .img files?

As you did not mention which OS you are running, here a solution for linux: use losetup

losetup /dev/loop0 /path/to/your/file.img

Then you can mount it.

Escaping Strings in JavaScript

A variation of the function provided by Paolo Bergantino that works directly on String:

String.prototype.addSlashes = function() 
{ 
   //no need to do (str+'') anymore because 'this' can only be a string
   return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
} 

By adding the code above in your library you will be able to do:

var test = "hello single ' double \" and slash \\ yippie";
alert(test.addSlashes());

EDIT:

Following suggestions in the comments, whoever is concerned about conflicts amongst JavaScript libraries can add the following code:

if(!String.prototype.addSlashes)
{
   String.prototype.addSlashes = function()... 
}
else
   alert("Warning: String.addSlashes has already been declared elsewhere.");

Java Wait and Notify: IllegalMonitorStateException

You can't wait() on an object unless the current thread owns that object's monitor. To do that, you must synchronize on it:

class Runner implements Runnable
{
  public void run()
  {
    try
    {
      synchronized(Main.main) {
        Main.main.wait();
      }
    } catch (InterruptedException e) {}
    System.out.println("Runner away!");
  }
}

The same rule applies to notify()/notifyAll() as well.

The Javadocs for wait() mention this:

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws:

IllegalMonitorStateException – if the current thread is not the owner of this object's monitor.

And from notify():

A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Iterate two Lists or Arrays with one ForEach statement in C#

Here's a custom IEnumerable<> extension method that can be used to loop through two lists simultaneously.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    public static class LinqCombinedSort
    {
        public static void Test()
        {
            var a = new[] {'a', 'b', 'c', 'd', 'e', 'f'};
            var b = new[] {3, 2, 1, 6, 5, 4};

            var sorted = from ab in a.Combine(b)
                         orderby ab.Second
                         select ab.First;

            foreach(char c in sorted)
            {
                Console.WriteLine(c);
            }
        }

        public static IEnumerable<Pair<TFirst, TSecond>> Combine<TFirst, TSecond>(this IEnumerable<TFirst> s1, IEnumerable<TSecond> s2)
        {
            using (var e1 = s1.GetEnumerator())
            using (var e2 = s2.GetEnumerator())
            {
                while (e1.MoveNext() && e2.MoveNext())
                {
                    yield return new Pair<TFirst, TSecond>(e1.Current, e2.Current);
                }
            }

        }


    }
    public class Pair<TFirst, TSecond>
    {
        private readonly TFirst _first;
        private readonly TSecond _second;
        private int _hashCode;

        public Pair(TFirst first, TSecond second)
        {
            _first = first;
            _second = second;
        }

        public TFirst First
        {
            get
            {
                return _first;
            }
        }

        public TSecond Second
        {
            get
            {
                return _second;
            }
        }

        public override int GetHashCode()
        {
            if (_hashCode == 0)
            {
                _hashCode = (ReferenceEquals(_first, null) ? 213 : _first.GetHashCode())*37 +
                            (ReferenceEquals(_second, null) ? 213 : _second.GetHashCode());
            }
            return _hashCode;
        }

        public override bool Equals(object obj)
        {
            var other = obj as Pair<TFirst, TSecond>;
            if (other == null)
            {
                return false;
            }
            return Equals(_first, other._first) && Equals(_second, other._second);
        }
    }

}

What is the default stack size, can it grow, how does it work with garbage collection?

As you say, local variables and references are stored on the stack. When a method returns, the stack pointer is simply moved back to where it was before the method started, that is, all local data is "removed from the stack". Therefore, there is no garbage collection needed on the stack, that only happens in the heap.

To answer your specific questions:

  • See this question on how to increase the stack size.
  • You can limit the stack growth by:
    • grouping many local variables in an object: that object will be stored in the heap and only the reference is stored on the stack
    • limit the number of nested function calls (typically by not using recursion)
  • For windows, the default stack size is 320k for 32bit and 1024k for 64bit, see this link.

error: ORA-65096: invalid common user or role name in oracle

SQL> alter session set "_ORACLE_SCRIPT"=true;  
SQL> create user sec_admin identified by "Chutinhbk123@!";

What's the algorithm to calculate aspect ratio?

This algorithm in Python gets you part of the way there.


Tell me what happens if the windows is a funny size.

Maybe what you should have is a list of all acceptable ratios (to the 3rd party component). Then, find the closest match to your window and return that ratio from the list.

Are there .NET implementation of TLS 1.2?

The latest version of SSPI (bundled with Windows 7) has an implementation of TLS 1.2, which can be found in schannel.dll

How do I base64 encode a string efficiently using Excel VBA?

As Mark C points out, you can use the MSXML Base64 encoding functionality as described here.

I prefer late binding because it's easier to deploy, so here's the same function that will work without any VBA references:

Function EncodeBase64(text As String) As String
  Dim arrData() As Byte
  arrData = StrConv(text, vbFromUnicode)

  Dim objXML As Variant
  Dim objNode As Variant

  Set objXML = CreateObject("MSXML2.DOMDocument")
  Set objNode = objXML.createElement("b64")

  objNode.dataType = "bin.base64"
  objNode.nodeTypedValue = arrData
  EncodeBase64 = objNode.text

  Set objNode = Nothing
  Set objXML = Nothing
End Function

What is hashCode used for? Is it unique?

This is from the msdn article here:

https://blogs.msdn.microsoft.com/tomarcher/2006/05/10/are-hash-codes-unique/

"While you will hear people state that hash codes generate a unique value for a given input, the fact is that, while difficult to accomplish, it is technically feasible to find two different data inputs that hash to the same value. However, the true determining factors regarding the effectiveness of a hash algorithm lie in the length of the generated hash code and the complexity of the data being hashed."

So just use a hash algorithm suitable to your data size and it will have unique hashcodes.

How do I format a Microsoft JSON date?

eval() is not necessary. This will work fine:

var date = new Date(parseInt(jsonDate.substr(6)));

The substr() function takes out the /Date( part, and the parseInt() function gets the integer and ignores the )/ at the end. The resulting number is passed into the Date constructor.


I have intentionally left out the radix (the 2nd argument to parseInt); see my comment below.

Also, I completely agree with Rory's comment: ISO-8601 dates are preferred over this old format - so this format generally shouldn't be used for new development. See the excellent Json.NET library for a great alternative that serializes dates using the ISO-8601 format.

For ISO-8601 formatted JSON dates, just pass the string into the Date constructor:

var date = new Date(jsonDate); //no ugly parsing needed; full timezone support

How to get difference between two rows for a column field?

SQL Server 2012 and up support LAG / LEAD functions to access the previous or subsequent row. SQL Server 2005 does not support this (in SQL2005 you need a join or something else).

A SQL 2012 example on this data

/* Prepare */
select * into #tmp
from
(
    select 2  as rowint,      23 as Value
    union select 3,       45
    union select 17,      10
    union select 9,       0
) x


/* The SQL 2012 query */
select rowInt, Value, LEAD(value) over (order by rowInt) - Value  
from #tmp

LEAD(value) will return the value of the next row in respect to the given order in "over" clause.

GROUP BY having MAX date

Fast and easy with HAVING:

SELECT * FROM tblpm n 
FROM tblpm GROUP BY control_number 
HAVING date_updated=MAX(date_updated);

In the context of HAVING, MAX finds the max of each group. Only the latest entry in each group will satisfy date_updated=max(date_updated). If there's a tie for latest within a group, both will pass the HAVING filter, but GROUP BY means that only one will appear in the returned table.

datetime dtypes in pandas read_csv

Why it does not work

There is no datetime dtype to be set for read_csv as csv files can only contain strings, integers and floats.

Setting a dtype to datetime will make pandas interpret the datetime as an object, meaning you will end up with a string.

Pandas way of solving this

The pandas.read_csv() function has a keyword argument called parse_dates

Using this you can on the fly convert strings, floats or integers into datetimes using the default date_parser (dateutil.parser.parser)

headers = ['col1', 'col2', 'col3', 'col4']
dtypes = {'col1': 'str', 'col2': 'str', 'col3': 'str', 'col4': 'float'}
parse_dates = ['col1', 'col2']
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes, parse_dates=parse_dates)

This will cause pandas to read col1 and col2 as strings, which they most likely are ("2016-05-05" etc.) and after having read the string, the date_parser for each column will act upon that string and give back whatever that function returns.

Defining your own date parsing function:

The pandas.read_csv() function also has a keyword argument called date_parser

Setting this to a lambda function will make that particular function be used for the parsing of the dates.

GOTCHA WARNING

You have to give it the function, not the execution of the function, thus this is Correct

date_parser = pd.datetools.to_datetime

This is incorrect:

date_parser = pd.datetools.to_datetime()

Pandas 0.22 Update

pd.datetools.to_datetime has been relocated to date_parser = pd.to_datetime

Thanks @stackoverYC

git error: failed to push some refs to remote

If you are attempting to initialize a directory with an existing GitHub repository, you should ensure you are committing changes.

Try creating a file:

touch initial
git add initial
git commit -m "initial commit"
git push -u origin master

That will place a file named initial that you can delete later.

Hope this answer helps! Goodluck!

Get first letter of a string from column

Cast the dtype of the col to str and you can perform vectorised slicing calling str:

In [29]:
df['new_col'] = df['First'].astype(str).str[0]
df

Out[29]:
   First  Second new_col
0    123     234       1
1     22    4353       2
2     32     355       3
3    453     453       4
4     45     345       4
5    453     453       4
6     56      56       5

if you need to you can cast the dtype back again calling astype(int) on the column

How to read Data from Excel sheet in selenium webdriver

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

String FilePath = "/home/lahiru/Desktop/Sample.xls";
FileInputStream fs = new FileInputStream(FilePath);
Workbook wb = Workbook.getWorkbook(fs);

String <variable> = sh.getCell("A2").getContents();

ASP.NET Web API session or something?

In WebApi 2 you can add this to global.asax

protected void Application_PostAuthorizeRequest() 
{
    System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}

Then you could access the session through:

HttpContext.Current.Session

Mock a constructor with parameter

To my knowledge, you can't mock constructors with mockito, only methods. But according to the wiki on the Mockito google code page there is a way to mock the constructor behavior by creating a method in your class which return a new instance of that class. then you can mock out that method. Below is an excerpt directly from the Mockito wiki:

Pattern 1 - using one-line methods for object creation

To use pattern 1 (testing a class called MyClass), you would replace a call like

   Foo foo = new Foo( a, b, c );

with

   Foo foo = makeFoo( a, b, c );

and write a one-line method

   Foo makeFoo( A a, B b, C c ) { 
        return new Foo( a, b, c );
   }

It's important that you don't include any logic in the method; just the one line that creates the object. The reason for this is that the method itself is never going to be unit tested.

When you come to test the class, the object that you test will actually be a Mockito spy, with this method overridden, to return a mock. What you're testing is therefore not the class itself, but a very slightly modified version of it.

Your test class might contain members like

  @Mock private Foo mockFoo;
  private MyClass toTest = spy(new MyClass());

Lastly, inside your test method you mock out the call to makeFoo with a line like

  doReturn( mockFoo )
      .when( toTest )
      .makeFoo( any( A.class ), any( B.class ), any( C.class ));

You can use matchers that are more specific than any() if you want to check the arguments that are passed to the constructor.

If you're just wanting to return a mocked object of your class I think this should work for you. In any case you can read more about mocking object creation here:

http://code.google.com/p/mockito/wiki/MockingObjectCreation

conflicting types for 'outchar'

In C, the order that you define things often matters. Either move the definition of outchar to the top, or provide a prototype at the top, like this:

#include <stdio.h> #include <stdlib.h>  void outchar(char ch);  int main() {     outchar('A');     outchar('B');     outchar('C');     return 0; }  void outchar(char ch) {     printf("%c", ch); } 

Also, you should be specifying the return type of every function. I added that for you.

Sorting dropdown alphabetically in AngularJS

Angular has an orderBy filter that can be used like this:

<select ng-model="selected" ng-options="f.name for f in friends | orderBy:'name'"></select>

See this fiddle for an example.

It's worth noting that if track by is being used it needs to appear after the orderBy filter, like this:

<select ng-model="selected" ng-options="f.name for f in friends | orderBy:'name' track by f.id"></select>

Setting ANDROID_HOME enviromental variable on Mac OS X

quoting @user2993582's answer

export PATH=$PATH:$ANDROID_HOME/bin

The 'bin' part has changed and it should be

export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

PHP float with 2 decimal places: .00

you can try this,it will work for you

number_format(0.00, 2)

Arduino error: does not name a type?

My code was out of void setup() or void loop() in Arduino.