Programs & Examples On #Remoteobject

java.rmi.ConnectException: Connection refused to host: 127.0.1.1;

When I got the same error on my machine ("connection is refused"), the reason was that I had defined the following on the server side:

 Naming.rebind("rmi://localhost:8080/AddService"
   ,addService); 

Thus the server binds both the IP = 127.0.0.1 and the port 8080.

But on the client side I had used:

AddServerInterface st = (AddServerInterface)Naming.lookup("rmi://localhost"
                        +"/AddService");

Thus I forgot to add the port number after the localhost, so I rewrote the above command and added the port number 8080 as follows:

AddServerInterface st = (AddServerInterface)Naming.lookup("rmi://localhost:8080"
                        +"/AddService");

and everything worked fine.

How to create directory automatically on SD card

With API 8 and greater, the location of the SD card has changed. @fiXedd's answer is good, but for safer code, you should use Environment.getExternalStorageState() to check if the media is available. Then you can use getExternalFilesDir() to navigate to the directory you want (assuming you're using API 8 or greater).

You can read more in the SDK documentation.

Generating UNIQUE Random Numbers within a range

$len = 10;   // total number of numbers
$min = 100;  // minimum
$max = 999;  // maximum
$range = []; // initialize array
foreach (range(0, $len - 1) as $i) {
    while(in_array($num = mt_rand($min, $max), $range));
    $range[] = $num;
}
print_r($range);

I was interested to see how the accepted answer stacks up against mine. It's useful to note, a hybrid of both may be advantageous; in fact a function that conditionally uses one or the other depending on certain values:

# The accepted answer
function randRange1($min, $max, $count)
{
    $numbers = range($min, $max);
    shuffle($numbers);
    return array_slice($numbers, 0, $count);
}

# My answer
function randRange2($min, $max, $count)
{
    $range = array();
    while ($i++ < $count) {
        while(in_array($num = mt_rand($min, $max), $range));
        $range[] = $num;
    }
    return $range;
}

echo 'randRange1: small range, high count' . PHP_EOL;
$time = microtime(true);
randRange1(0, 9999, 5000);
echo (microtime(true) - $time) . PHP_EOL . PHP_EOL;

echo 'randRange2: small range, high count' . PHP_EOL;
$time = microtime(true);
randRange2(0, 9999, 5000);
echo (microtime(true) - $time) . PHP_EOL . PHP_EOL;

echo 'randRange1: high range, small count' . PHP_EOL;
$time = microtime(true);
randRange1(0, 999999, 6);
echo (microtime(true) - $time) . PHP_EOL . PHP_EOL;

echo 'randRange2: high range, small count' . PHP_EOL;
$time = microtime(true);
randRange2(0, 999999, 6);
echo (microtime(true) - $time) . PHP_EOL . PHP_EOL;

The results:

randRange1: small range, high count
0.019910097122192

randRange2: small range, high count
1.5043621063232

randRange1: high range, small count
2.4722430706024

randRange2: high range, small count
0.0001051425933837

If you're using a smaller range and a higher count of returned values, the accepted answer is certainly optimal; however as I had expected, larger ranges and smaller counts will take much longer with the accepted answer, as it must store every possible value in range. You even run the risk of blowing PHP's memory cap. A hybrid that evaluates the ratio between range and count, and conditionally chooses the generator would be the best of both worlds.

TypeError: 'str' object is not callable (Python)

I had the same error. In my case wasn't because of a variable named str. But because I named a function with a str parameter and the variable the same.

same_name = same_name(var_name: str)

I run it in a loop. The first time it run ok. The second time I got this error. Renaming the variable to a name different from the function name fixed this. So I think it's because Python once associate a function name in a scope, the second time tries to associate the left part (same_name =) as a call to the function and detects that the str parameter is not present, so it's missing, then it throws that error.

Where is virtualenvwrapper.sh after pip install?

pip will not try to make things difficult for you on purpose.

The thing is commands based files are always installed in /bin folders they can be anywhere on the system path.

I had the same problem and I found that I have these files in my

~/.local/bin/

folder instead of

/usr/loca/bin/

which is the common case, but I think they changed the default path to

~ or $HOME

directory because its more isolate for the pip installations and provides a distinction between apt-get packages and pip packages.

So coming to the point you have two choices here either you go to your .bashrc and make changes like this

# for virtualenv wrapper
export WORKON_HOME=$HOME/Envs
export PROJECT_HOME=$HOME/Devel
source $HOME/.local/bin/virtualenvwrapper.sh

and than create a directory virtualenvwrapper under /usr/share/ and than symlink your virtualwrapper_lazy.sh like this

sudo ln -s ~/.local/bin/virtualenvwrapper_lazy.sh /usr/share/virtualenvwrapper/virtualenvwrapper_lazy.sh

and you can check if your workon command is working which will list your existing virtualenv's.

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

This should solve your problem, you should try to run the following below:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser 

If Radio Button is selected, perform validation on Checkboxes

You must use the equals operator not the assignment like

if(document.form1.radio1[0].checked == true) {
    alert("You have selected Option 1");
}

Use sed to replace all backslashes with forward slashes

If your text is in a Bash variable, then Parameter Substitution ${var//\\//} can replace substrings:

$ p='C:\foo\bar.xml'
$ printf '%s\n' "$p"
C:\foo\bar.xml
$ printf '%s\n' "${p//\\//}"
C:/foo/bar.xml

This may be leaner and clearer that filtering through a command such as tr or sed.

How to center HTML5 Videos?

I had a similar problem in revamping a web site in Dreamweaver. The site structure is based on a complex set of tables, and this video was in one of the main layout cells. I created a nested table just for the video and then added an align=center attribute to the new table:

<table align=center><tr><td>
    <video width=420 height=236 controls="controls" autoplay="autoplay">
        <source src="video/video.ogv" type='video/ogg; codecs="theora, vorbis"'/>
        <source src="video/video.webm" type='video/webm' >
        <source src="video/video.mp4" type='video/mp4'>
        <p class="sidebar">If video is not visible, your browser does not support HTML5 video</p>
    </video>
</td></tr></table>

Could not locate Gemfile

I solved similar problem just by backing out of the project directory, then cd back into the project directory and bundle install.

FIFO based Queue implementations?

A LinkedList can be used as a Queue - but you need to use it right. Here is an example code :

@Test
public void testQueue() {
    LinkedList<Integer> queue = new LinkedList<>();
    queue.add(1);
    queue.add(2);
    System.out.println(queue.pop());
    System.out.println(queue.pop());
}

Output :

1
2

Remember, if you use push instead of add ( which you will very likely do intuitively ), this will add element at the front of the list, making it behave like a stack.

So this is a Queue only if used in conjunction with add.

Try this :

@Test
public void testQueue() {
    LinkedList<Integer> queue = new LinkedList<>();
    queue.push(1);
    queue.push(2);
    System.out.println(queue.pop());
    System.out.println(queue.pop());
}

Output :

2
1

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

You can use the "filter" filter in your controller to get all the "C" grades. Getting the first element of the result array will give you the title of the subject that has grade "C".

$scope.gradeC = $filter('filter')($scope.results.subjects, {grade: 'C'})[0];

http://jsbin.com/ewitun/1/edit

The same with plain ES6:

$scope.gradeC = $scope.results.subjects.filter((subject) => subject.grade === 'C')[0]

1 = false and 0 = true?

It may very well be a mistake on the original author, however the notion that 1 is true and 0 is false is not a universal concept. In shell scripting 0 is returned for success, and any other number for failure. In other languages such as Ruby, only nil and false are considered false, and any other value is considered true, so in Ruby both 1 and 0 would be considered true.

How to remove an element from a list by index

It doesn't sound like you're working with a list of lists, so I'll keep this short. You want to use pop since it will remove elements not elements that are lists, you should use del for that. To call the last element in python it's "-1"

>>> test = ['item1', 'item2']
>>> test.pop(-1)
'item2'
>>> test
['item1']

android: stretch image in imageview to fit screen

for XML android

android:src="@drawable/foto1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"

How do I execute a program from Python? os.system fails due to spaces in path

Suppose we want to run your Django web server (in Linux) that there is space between your path (path='/home/<you>/<first-path-section> <second-path-section>'), so do the following:

import subprocess

args = ['{}/manage.py'.format('/home/<you>/<first-path-section> <second-path-section>'), 'runserver']
res = subprocess.Popen(args, stdout=subprocess.PIPE)
output, error_ = res.communicate()

if not error_:
    print(output)
else:
    print(error_)

[Note]:

  • Do not forget accessing permission: chmod 755 -R <'yor path'>
  • manage.py is exceutable: chmod +x manage.py

How to run cron once, daily at 10pm

Here are some more examples

  • Run every 6 hours at 46 mins past the hour:

    46 */6 * * *

  • Run at 2:10 am:

    10 2 * * *

  • Run at 3:15 am:

    15 3 * * *

  • Run at 4:20 am:

    20 4 * * *

  • Run at 5:31 am:

    31 5 * * *

  • Run at 5:31 pm:

    31 17 * * *

Save internal file in my own internal folder in Android

The answer of Mintir4 is fine, I would also do the following to load the file.

FileInputStream fis = myContext.openFileInput(fn);
BufferedReader r = new BufferedReader(new InputStreamReader(fis));
String s = "";

while ((s = r.readLine()) != null) {
    txt += s;
}

r.close();

How do I add options to a DropDownList using jQuery?

Lets think your response is "successData". This contains a list which you need to add as options in a dropdown menu.

success: function (successData) {
var sizeOfData = successData.length;
if (sizeOfData == 0) {
    //    NO DATA, throw an alert ...
    alert ("No Data Found");
} else {
    $.each(successData, function(val, text) {
        mySelect.append(
            $('<option></option>').val(val).html(text)
        );
    });
} }

This would work for you ....

Print to the same line and not a new line?

for object "pega" that provides StartRunning(), StopRunning(), boolean getIsRunning() and integer getProgress100() returning value in range of 0 to 100, this provides text progress bar while running...

now = time.time()
timeout = now + 30.0
last_progress = -1

pega.StartRunning()

while now < timeout and pega.getIsRunning():
    time.sleep(0.5)
    now = time.time()

    progress = pega.getTubProgress100()
    if progress != last_progress:
        print('\r'+'='*progress+'-'*(100-progress)+' ' + str(progress) + "% ", end='', flush=True)
        last_progress = progress

pega.StopRunning()

progress = pega.getTubProgress100()
print('\r'+'='*progress+'-'*(100-progress)+' ' + str(progress) + "% ", flush=True)

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>

String to object in JS

This simple way...

var string = "{firstName:'name1', lastName:'last1'}";
eval('var obj='+string);
alert(obj.firstName);

output

name1

No Persistence provider for EntityManager named

You need the following jar files in the classpath:

  1. antlr-2.7.6.jar
  2. commons-collections-3.1.jar
  3. dom4j-1.6.1.jar
  4. hibernate-commons-annotations-4.0.1.Final.jar
  5. hibernate-core-4.0.1.Final.jar
  6. hibernate-entitymanager.jar
  7. hibernate-jpa-2.0-api-1.0.0.Final.jar
  8. javassist-3.9.0.jar
  9. jboss-logging-3.1.1.GA.jar
  10. jta-1.1.jar
  11. slf4j-api-1.5.8.jar
  12. xxx-jdbc-driver.jar

How to convert Hexadecimal #FFFFFF to System.Drawing.Color

string hex = "#FFFFFF";
Color _color = System.Drawing.ColorTranslator.FromHtml(hex);

Note: the hash is important!

Clear back stack using fragments

    private void clearBackStack(){
        SupportFragmentManaer fm = getSupportFragmentManager();
        fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

Call to this method would be very neat.

  1. No Loop required.
  2. If you are using animation in fragments, it will not show too many animations. But using loop will.

How can I have a newline in a string in sh?

Disclaimer: I first wrote this and then stumbled upon this question. I thought this solution wasn't yet posted, and saw that tlwhitec did post a similar answer. Still I'm posting this because I hope it's a useful and thorough explanation.

Short answer:

This seems quite a portable solution, as it works on quite some shells (see comment).
This way you can get a real newline into a variable.

The benefit of this solution is that you don't have to use newlines in your source code, so you can indent your code any way you want, and the solution still works. This makes it robust. It's also portable.

# Robust way to put a real newline in a variable (bash, dash, ksh, zsh; indentation-resistant).
nl="$(printf '\nq')"
nl=${nl%q}

Longer answer:

Explanation of the above solution:

The newline would normally lost due to command substitution, but to prevent that, we add a 'q' and remove it afterwards. (The reason for the double quotes is explained further below.)

We can prove that the variable contains an actual newline character (0x0A):

printf '%s' "$nl" | hexdump -C
00000000  0a  |.|
00000001

(Note that the '%s' was needed, otherwise printf will translate a literal '\n' string into an actual 0x0A character, meaning we would prove nothing.)

Of course, instead of the solution proposed in this answer, one could use this as well (but...):

nl='
'

... but that's less robust and can be easily damaged by accidentally indenting the code, or by forgetting to dedent it afterwards, which makes it inconvenient to use in (indented) functions, whereas the earlier solution is robust.

Now, as for the double quotes:
The reason for the double quotes " surrounding the command substitution as in nl="$(printf '\nq')" is that you can then even prefix the variable assignment with the local keyword or builtin (such as in functions), and it will still work on all shells, whereas otherwise the dash shell would have trouble, in the sense that dash would otherwise lose the 'q' and you'd end up with an empty 'nl' variable (again, due to command substitution).
That issue is better illustrated with another example:

dash_trouble_example() {
    e=$(echo hello world) # Not using 'local'.
    echo "$e" # Fine. Outputs 'hello world' in all shells.

    local e=$(echo hello world) # But now, when using 'local' without double quotes ...:
    echo "$e" # ... oops, outputs just 'hello' in dash,
              # ... but 'hello world' in bash and zsh.

    local f="$(echo hello world)" # Finally, using 'local' and surrounding with double quotes.
    echo "$f" # Solved. Outputs 'hello world' in dash, zsh, and bash.

    # So back to our newline example, if we want to use 'local', we need
    # double quotes to surround the command substitution:
    # (If we didn't use double quotes here, then in dash the 'nl' variable
    # would be empty.)
    local nl="$(printf '\nq')"
    nl=${nl%q}
}

Practical example of the above solution:

# Parsing lines in a for loop by setting IFS to a real newline character:

nl="$(printf '\nq')"
nl=${nl%q}

IFS=$nl

for i in $(printf '%b' 'this is line 1\nthis is line 2'); do
    echo "i=$i"
done

# Desired output:
# i=this is line 1
# i=this is line 2

# Exercise:
# Try running this example without the IFS=$nl assignment, and predict the outcome.

How to read the output from git diff?

@@ -1,2 +3,4 @@ part of the diff

This part took me a while to understand, so I've created a minimal example.

The format is basically the same the diff -u unified diff.

For instance:

diff -u <(seq 16) <(seq 16 | grep -Ev '^(2|3|14|15)$')

Here we removed lines 2, 3, 14 and 15. Output:

@@ -1,6 +1,4 @@
 1
-2
-3
 4
 5
 6
@@ -11,6 +9,4 @@
 11
 12
 13
-14
-15
 16

@@ -1,6 +1,4 @@ means:

  • -1,6 means that this piece of the first file starts at line 1 and shows a total of 6 lines. Therefore it shows lines 1 to 6.

    1
    2
    3
    4
    5
    6
    

    - means "old", as we usually invoke it as diff -u old new.

  • +1,4 means that this piece of the second file starts at line 1 and shows a total of 4 lines. Therefore it shows lines 1 to 4.

    + means "new".

    We only have 4 lines instead of 6 because 2 lines were removed! The new hunk is just:

    1
    4
    5
    6
    

@@ -11,6 +9,4 @@ for the second hunk is analogous:

  • on the old file, we have 6 lines, starting at line 11 of the old file:

    11
    12
    13
    14
    15
    16
    
  • on the new file, we have 4 lines, starting at line 9 of the new file:

    11
    12
    13
    16
    

    Note that line 11 is the 9th line of the new file because we have already removed 2 lines on the previous hunk: 2 and 3.

Hunk header

Depending on your git version and configuration, you can also get a code line next to the @@ line, e.g. the func1() { in:

@@ -4,7 +4,6 @@ func1() {

This can also be obtained with the -p flag of plain diff.

Example: old file:

func1() {
    1;
    2;
    3;
    4;
    5;
    6;
    7;
    8;
    9;
}

If we remove line 6, the diff shows:

@@ -4,7 +4,6 @@ func1() {
     3;
     4;
     5;
-    6;
     7;
     8;
     9;

Note that this is not the correct line for func1: it skipped lines 1 and 2.

This awesome feature often tells exactly to which function or class each hunk belongs, which is very useful to interpret the diff.

How the algorithm to choose the header works exactly is discussed at: Where does the excerpt in the git diff hunk header come from?

href around input type submit

Place the link location in the action="" of a wrapping form tag.

Your first link would be:

<form action="1.html">
    <input type="submit" class="button_active" value="1">
</form>

How can I explicitly free memory in Python?

(del can be your friend, as it marks objects as being deletable when there no other references to them. Now, often the CPython interpreter keeps this memory for later use, so your operating system might not see the "freed" memory.)

Maybe you would not run into any memory problem in the first place by using a more compact structure for your data. Thus, lists of numbers are much less memory-efficient than the format used by the standard array module or the third-party numpy module. You would save memory by putting your vertices in a NumPy 3xN array and your triangles in an N-element array.

Selecting multiple classes with jQuery

// Due to this Code ): Syntax problem.    
$('.myClass', '.myOtherClass').removeClass('theclass'); 

According to jQuery documentation: https://api.jquery.com/multiple-selector/

When can select multiple classes in this way:

jQuery(“selector1, selector2, selectorN”) // double Commas. // IS valid.
jQuery('selector1, selector2, selectorN') // single Commas. // Is valid.

by enclosing all the selectors in a single '...' ' or double commas, "..."

So in your case the correct way to call multiple classes is:

$('.myClass', '.myOtherClass').removeClass('theclass'); // your Code // Invalid.
$('.myClass , .myOtherClass').removeClass('theclass');  // Correct Code // Is valid.

How can I open a website in my web browser using Python?

From the doc.

The webbrowser module provides a high-level interface to allow displaying Web-based documents to users. Under most circumstances, simply calling the open() function from this module will do the right thing.

You have to import the module and use open() function. This will open https://nabinkhadka.com.np in the browser.

To open in new tab:

import webbrowser
webbrowser.open('https://nabinkhadka.com.np', new = 2)

Also from the doc.

If new is 0, the url is opened in the same browser window if possible. If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible

So according to the value of new, you can either open page in same browser window or in new tab etc.

Also you can specify as which browser (chrome, firebox, etc.) to open. Use get() function for this.

Can't subtract offset-naive and offset-aware datetimes

The psycopg2 module has its own timezone definitions, so I ended up writing my own wrapper around utcnow:

def pg_utcnow():
    import psycopg2
    return datetime.utcnow().replace(
        tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None))

and just use pg_utcnow whenever you need the current time to compare against a PostgreSQL timestamptz

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

I have no serial device here to test it, but if you have python and dbus you can try it yourself.

import dbus
bus = dbus.SystemBus()
hwmanager = bus.get_object('org.freedesktop.Hal', '/org/freedesktop/Hal/Manager')
hwmanager_i = dbus.Interface(hwmanager, 'org.freedesktop.Hal.Manager')
print hwmanager_i.FindDeviceByCapability("serial")

If it fails you can search inside hwmanager_i.GetAllDevicesWithProperties() to see if the capability name "serial" that I just guessed has a different name.

HTH

Border Radius of Table is not working

Just add overflow:hidden to the table with border-radius.

.tablewithradius {
  overflow:hidden ;
  border-radius: 15px;
}

Returning pointer from a function

It is not allocating memory at assignment of value 12 to integer pointer. Therefore it crashes, because it's not finding any memory.

You can try this:

#include<stdio.h>
#include<stdlib.h>
int *fun();

int main()
{
    int *ptr;
    ptr=fun();
    printf("\n\t\t%d\n",*ptr);
}

int *fun()
{
    int ptr;
    ptr=12;
    return(&ptr);
}

How to make a Div appear on top of everything else on the screen?

Are you using position: relative?

Try to set position: relative and then z-index because you want this div has a z-index in relation with other div.

By the way, your browser is important to check if it working or not. Neither IE or Firefox is a good one.

Java array assignment (multiple values)

If you know the values at compile time you can do :

float[] values = {0.1f, 0.2f, 0.3f};

There is no way to do that if values are variables in runtime.

Backporting Python 3 open(encoding="utf-8") to Python 2

Not a general answer, but may be useful for the specific case where you are happy with the default python 2 encoding, but want to specify utf-8 for python 3:

if sys.version_info.major > 2:
    do_open = lambda filename: open(filename, encoding='utf-8')
else:
    do_open = lambda filename: open(filename)

with do_open(filename) as file:
    pass

C# switch statement limitations - why?

Microsoft finally heard you!

Now with C# 7 you can:

switch(shape)
{
case Circle c:
    WriteLine($"circle with radius {c.Radius}");
    break;
case Rectangle s when (s.Length == s.Height):
    WriteLine($"{s.Length} x {s.Height} square");
    break;
case Rectangle r:
    WriteLine($"{r.Length} x {r.Height} rectangle");
    break;
default:
    WriteLine("<unknown shape>");
    break;
case null:
    throw new ArgumentNullException(nameof(shape));
}

Powershell equivalent of bash ampersand (&) for forking/running background processes

You can do something like this.

$a = start-process -NoNewWindow powershell {timeout 10; 'done'} -PassThru

And if you want to wait for it:

$a | wait-process

Bonus osx or linux version:

$a = start-process pwsh '-c',{start-sleep 5; 'done'} -PassThru 

Example pinger script I have. The args are passed as an array:

$1 = start -n powershell pinger,comp001 -pa

How can I make a JPA OneToOne relation lazy

For Kotlin devs: To allow Hibernate to inherit from the @Entity types that you want to be lazy-loadable they have to be inheritable/open, which they in Kotlin by default are not. To work around this issue we can make use of the all-open compiler plugin and instruct it to also handle the JPA annotations by adding this to our build.gradle:

allOpen {
   annotation("javax.persistence.Entity")
   annotation("javax.persistence.MappedSuperclass")
   annotation("javax.persistence.Embeddable")
}

If you are using Kotlin and Spring like me, you are most probably also using the kotlin-jpa/no-args and kotlin-spring/all-open compiler plugins already. However, you will still need to add the above lines, as that combination of plugins neither makes such classes open.

Read the great article of Léo Millon for further explanations.

How to create a date object from string in javascript

var d = new Date(2011,10,30);

as months are indexed from 0 in js.

Converting NSData to NSString in Objective c

Use below code.

NSString* myString;
myString = [[NSString alloc] initWithData:nsdata encoding:NSASCIIStringEncoding];

How to remove focus around buttons on click

This works for me, another solution not mentioned. Just throw it in the click event...

$(this).trigger("blur");

Or call it from another event/method...

$(".btn_name").trigger("blur");

Code snippet or shortcut to create a constructor in Visual Studio

In case you want a constructor with properties, you need to do the following:

  1. Place your cursor in any empty line in a class;

  2. Press Ctrl + . to trigger the Quick Actions and Refactorings menu;

    Refactoring menu

  3. Select Generate constructor from the drop-down menu;

  4. Pick the members you want to include as constructor parameters. You can order them using the up and down arrows. Choose OK.

The constructor is created with the specified parameters.

Generate a constructor in Visual Studio

Best timing method in C?

gettimeofday() will probably do what you want.

If you're on Intel hardware, here's how to read the CPU real-time instruction counter. It will tell you the number of CPU cycles executed since the processor was booted. This is probably the finest-grained, lowest overhead counter you can get for performance measurement.

Note that this is the number of CPU cycles. On linux you can get the CPU speed from /proc/cpuinfo and divide to get the number of seconds. Converting this to a double is quite handy.

When I run this on my box, I get

11867927879484732
11867927879692217
it took this long to call printf: 207485

Here's the Intel developer's guide that gives tons of detail.

#include <stdio.h>
#include <stdint.h>

inline uint64_t rdtsc() {
    uint32_t lo, hi;
    __asm__ __volatile__ (
      "xorl %%eax, %%eax\n"
      "cpuid\n"
      "rdtsc\n"
      : "=a" (lo), "=d" (hi)
      :
      : "%ebx", "%ecx");
    return (uint64_t)hi << 32 | lo;
}

main()
{
    unsigned long long x;
    unsigned long long y;
    x = rdtsc();
    printf("%lld\n",x);
    y = rdtsc();
    printf("%lld\n",y);
    printf("it took this long to call printf: %lld\n",y-x);
}

How to fix error Base table or view not found: 1146 Table laravel relationship table?

You can add this in Post Model,

public function categories()
{
 return $this->belongsToMany('App\Category','category_post','post_id','category_id');                 
}

category_post indicate the table you want to use.
post_id indicate the column where you want to store the posts id.
category_id indicate the column where you want to store the categories id.

What is the difference between Nexus and Maven?

This has a good general description: https://gephi.wordpress.com/tag/maven/

Let me make a few statement that can put the difference in focus:

  1. We migrated our code base from Ant to Maven

  2. All 3rd party librairies have been uploaded to Nexus. Maven is using Nexus as a source for libraries.

  3. Basic functionalities of a repository manager like Sonatype are:

    • Managing project dependencies,
    • Artifacts & Metadata,
    • Proxying external repositories
    • and deployment of packaged binaries and JARs to share those artifacts with other developers and end-users.

Grunt watch error - Waiting...Fatal error: watch ENOSPC

To find out who's making inotify instances, try this command (source):

for foo in /proc/*/fd/*; do readlink -f $foo; done | grep inotify | sort | uniq -c | sort -nr

Mine looked like this:

 25 /proc/2857/fd/anon_inode:inotify
  9 /proc/2880/fd/anon_inode:inotify
  4 /proc/1375/fd/anon_inode:inotify
  3 /proc/1851/fd/anon_inode:inotify
  2 /proc/2611/fd/anon_inode:inotify
  2 /proc/2414/fd/anon_inode:inotify
  1 /proc/2992/fd/anon_inode:inotify

Using ps -p 2857, I was able to identify process 2857 as sublime_text. Only after closing all sublime windows was I able to run my node script.

How to check if an environment variable exists and get its value?

NEW_VAR=""
if [[ ${ENV_VAR} && ${ENV_VAR-x} ]]; then
  NEW_VAR=${ENV_VAR}
else
  NEW_VAR="new value"
fi

Android Studio: Module won't show up in "Edit Configuration"

resolved this issue by clicking on "File->Sync Project with Gradle Files"

Can I write or modify data on an RFID tag?

Some RFID chips are read-write, the majority are read-only. You can find out if your chip is read-only by checking the datasheet.

How do I convert 2018-04-10T04:00:00.000Z string to DateTime?

Update: Using DateTimeFormat, introduced in java 8:

The idea is to define two formats: one for the input format, and one for the output format. Parse with the input formatter, then format with the output formatter.

Your input format looks quite standard, except the trailing Z. Anyway, let's deal with this: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'". The trailing 'Z' is the interesting part. Usually there's time zone data here, like -0700. So the pattern would be ...Z, i.e. without apostrophes.

The output format is way more simple: "dd-MM-yyyy". Mind the small y -s.

Here is the example code:

DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse("2018-04-10T04:00:00.000Z", inputFormatter);
String formattedDate = outputFormatter.format(date);
System.out.println(formattedDate); // prints 10-04-2018

Original answer - with old API SimpleDateFormat

SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = inputFormat.parse("2018-04-10T04:00:00.000Z");
String formattedDate = outputFormat.format(date);
System.out.println(formattedDate); // prints 10-04-2018

Allow 2 decimal places in <input type="number">

Instead of step="any", which allows for any number of decimal places, use step=".01", which allows up to two decimal places.

More details in the spec: https://www.w3.org/TR/html/sec-forms.html#the-step-attribute

Can I change the checkbox size using CSS?

My understanding is that this isn't easy at all to do cross-browser. Instead of trying to manipulate the checkbox control, you could always build your own implementation using images, javascript, and hidden input fields. I'm assuming this is similar to what niceforms is (from Staicu lonut's answer above), but wouldn't be particularly difficult to implement. I believe jQuery has a plugin to allow for this custom behavior as well (will look for the link and post here if I can find it).

Using Mockito's generic "any()" method

You can use Mockito.isA() for that:

import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.verify;

verify(bar).doStuff(isA(Foo[].class));

http://site.mockito.org/mockito/docs/current/org/mockito/Matchers.html#isA(java.lang.Class)

node.js http 'get' request with query string parameters

Check out the request module.

It's more full featured than node's built-in http client.

var request = require('request');

var propertiesObject = { field1:'test1', field2:'test2' };

request({url:url, qs:propertiesObject}, function(err, response, body) {
  if(err) { console.log(err); return; }
  console.log("Get response: " + response.statusCode);
});

AngularJS is rendering <br> as text not as a newline

Why so complicated?

I solved my problem this way simply:

  <pre>{{existingCategory+thisCategory}}</pre>

It will make <br /> automatically if the string contains '\n' that contain when I was saving data from textarea.

How does database indexing work?

Classic example "Index in Books"

Consider a "Book" of 1000 pages, divided by 10 Chapters, each section with 100 pages.

Simple, huh?

Now, imagine you want to find a particular Chapter that contains a word "Alchemist". Without an index page, you have no other option than scanning through the entire book/Chapters. i.e: 1000 pages.

This analogy is known as "Full Table Scan" in database world.

enter image description here

But with an index page, you know where to go! And more, to lookup any particular Chapter that matters, you just need to look over the index page, again and again, every time. After finding the matching index you can efficiently jump to that chapter by skipping the rest.

But then, in addition to actual 1000 pages, you will need another ~10 pages to show the indices, so totally 1010 pages.

Thus, the index is a separate section that stores values of indexed column + pointer to the indexed row in a sorted order for efficient look-ups.

Things are simple in schools, isn't it? :P

CSS Pseudo-classes with inline styles

Not CSS, but inline:

<a href="#" 
   onmouseover = "this.style.textDecoration = 'none'"
   onmouseout  = "this.style.textDecoration = 'underline'">Hello</a>

See example →

How do I add items to an array in jQuery?

Hope this will help you..

var list = [];
    $(document).ready(function () {
        $('#test').click(function () {
            var oRows = $('#MainContent_Table1 tr').length;
            $('#MainContent_Table1 tr').each(function (index) {
                list.push(this.cells[0].innerHTML);
            });
        });
    });

How do I store the select column in a variable?

select @EmpID = ID from dbo.Employee

Or

set @EmpID =(select id from dbo.Employee)

Note that the select query might return more than one value or rows. so you can write a select query that must return one row.

If you would like to add more columns to one variable(MS SQL), there is an option to use table defined variable

DECLARE @sampleTable TABLE(column1 type1)
INSERT INTO @sampleTable
SELECT columnsNumberEqualInsampleTable FROM .. WHERE ..

As table type variable do not exist in Oracle and others, you would have to define it:

DECLARE TYPE type_name IS TABLE OF (column_type | variable%TYPE | table.column%TYPE [NOT NULL] INDEX BY BINARY INTEGER;

-- Then to declare a TABLE variable of this type: variable_name type_name;

-- Assigning values to a TABLE variable: variable_name(n).field_name := 'some text';

-- Where 'n' is the index value

How to declare or mark a Java method as deprecated?

since some minor explanations were missing

Use @Deprecated annotation on the method like this

 /**
 * @param basePrice
 * 
 * @deprecated  reason this method is deprecated <br/>
 *              {will be removed in next version} <br/>
 *              use {@link #setPurchasePrice()} instead like this: 
 * 
 * 
 * <blockquote><pre>
 * getProduct().setPurchasePrice(200) 
 * </pre></blockquote>
 * 
 */
@Deprecated
public void setBaseprice(int basePrice) {
}

remember to explain:

  1. Why is this method no longer recommended. What problems arise when using it. Provide a link to the discussion on the matter if any. (remember to separate lines for readability <br/>
  2. When it will be removed. (let your users know how much they can still rely on this method if they decide to stick to the old way)
  3. Provide a solution or link to the method you recommend {@link #setPurchasePrice()}

What are best practices that you use when writing Objective-C and Cocoa?

Variables and properties

1/ Keeping your headers clean, hiding implementation
Don't include instance variables in your header. Private variables put into class continuation as properties. Public variables declare as public properties in your header. If it should be only read, declare it as readonly and overwrite it as readwrite in class continutation. Basically I am not using variables at all, only properties.

2/ Give your properties a non-default variable name, example:


@synthesize property = property_;

Reason 1: You will catch errors caused by forgetting "self." when assigning the property. Reason 2: From my experiments, Leak Analyzer in Instruments has problems to detect leaking property with default name.

3/ Never use retain or release directly on properties (or only in very exceptional situations). In your dealloc just assign them a nil. Retain properties are meant to handle retain/release by themselves. You never know if a setter is not, for example, adding or removing observers. You should use the variable directly only inside its setter and getter.

Views

1/ Put every view definition into a xib, if you can (the exception is usually dynamic content and layer settings). It saves time (it's easier than writing code), it's easy to change and it keeps your code clean.

2/ Don't try to optimize views by decreasing the number of views. Don't create UIImageView in your code instead of xib just because you want to add subviews into it. Use UIImageView as background instead. The view framework can handle hundreds of views without problems.

3/ IBOutlets don't have to be always retained (or strong). Note that most of your IBOutlets are part of your view hierarchy and thus implicitly retained.

4/ Release all IBOutlets in viewDidUnload

5/ Call viewDidUnload from your dealloc method. It is not implicitly called.

Memory

1/ Autorelease objects when you create them. Many bugs are caused by moving your release call into one if-else branch or after a return statement. Release instead of autorelease should be used only in exceptional situations - e.g. when you are waiting for a runloop and you don't want your object to be autoreleased too early.

2/ Even if you are using Authomatic Reference Counting, you have to understand perfectly how retain-release methods work. Using retain-release manually is not more complicated than ARC, in both cases you have to thing about leaks and retain-cycles. Consider using retain-release manually on big projects or complicated object hierarchies.

Comments

1/ Make your code autodocumented. Every variable name and method name should tell what it is doing. If code is written correctly (you need a lot of practice in this), you won't need any code comments (not the same as documentation comments). Algorithms can be complicated but the code should be always simple.

2/ Sometimes, you'll need a comment. Usually to describe a non apparent code behavior or hack. If you feel you have to write a comment, first try to rewrite the code to be simpler and without the need of comments.

Indentation

1/ Don't increase indentation too much. Most of your method code should be indented on the method level. Nested blocks (if, for etc.) decrease readability. If you have three nested blocks, you should try to put the inner blocks into a separate method. Four or more nested blocks should be never used. If most of your method code is inside of an if, negate the if condition, example:


if (self) {
   //... long initialization code ...
}

return self;


if (!self) {
   return nil;
}

//... long initialization code ...

return self;

Understand C code, mainly C structs

Note that Obj-C is only a light OOP layer over C language. You should understand how basic code structures in C work (enums, structs, arrays, pointers etc). Example:


view.frame = CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, view.frame.size.height + 20);

is the same as:


CGRect frame = view.frame;
frame.size.height += 20;
view.frame = frame;

And many more

Mantain your own coding standards document and update it often. Try to learn from your bugs. Understand why a bug was created and try to avoid it using coding standards.

Our coding standards have currently about 20 pages, a mix of Java Coding Standards, Google Obj-C/C++ Standards and our own addings. Document your code, use standard standard indentation, white spaces and blank lines on the right places etc.

Change the Textbox height?

The Simplest Way to do that

  1. Right click on the TextBox.
  2. Go to properties.
  3. Set Multiline = True.

Now you will be able to resize the TextBox vertically as you wish.

getting the ng-object selected with ng-change

Instead of setting the ng-model to item.size.code, how about setting it to size:

<select ng-options="size as size.name for size in sizes" 
   ng-model="item" ng-change="update()"></select>

Then in your update() method, $scope.item will be set to the currently selected item.

And whatever code needed item.size.code, can get that property via $scope.item.code.

Fiddle.

Update based on more info in comments:

Use some other $scope property for your select ng-model then:

<select ng-options="size as size.name for size in sizes" 
   ng-model="selectedItem" ng-change="update()"></select>

Controller:

$scope.update = function() {
   $scope.item.size.code = $scope.selectedItem.code
   // use $scope.selectedItem.code and $scope.selectedItem.name here
   // for other stuff ...
}

How to enable PHP's openssl extension to install Composer?

I faced the same problem, but when i was lokking for php.ini and php.exe i found php.exe at C:\UwAmp\bin\php\php-5.4.15 when php.ini at C:\UwAmp\bin\apache. I just copy php.ini at C:\UwAmp\bin\php\php-5.4.15 and Uncomment the line extension=php_openssl.dll and it fixed.

show icon in actionbar/toolbar with AppCompat-v7 21

If you dont want to set your toolbar as action bar using setSupportActionBar, you can add a logo next to your navigation icon (if you have a back button for example) like this:

toolbar.setLogo();

or in xml

<android.support.v7.widget.Toolbar 
    ....
    android:logo="@drawable/logo"
    app:logo="@drawable/logo"/>

And even if you have a title set on the Toolbar, the the title will still show.

Ex: The green check in the image below is the logo

Toolbar with navigation icon, logo and title

Why can't a text column have a default value in MySQL?

As the main question:

Anybody know why this is not allowed?

is still not answered, I did a quick search and found a relatively new addition from a MySQL developer at MySQL Bugs:

[17 Mar 2017 15:11] Ståle Deraas

Posted by developer:

This is indeed a valid feature request, and at first glance it might seem trivial to add. But TEXT/BLOBS values are not stored directly in the record buffer used for reading/updating tables. So it is a bit more complex to assign default values for them.

This is no definite answer, but at least a starting point for the why question.

In the mean time, I'll just code around it and either make the column nullable or explicitly assign a (default '') value for each insert from the application code...

Eclipse add Tomcat 7 blank server name

It is a bug in Eclipse. I had exactly the same problem, also on Ubuntu with Eclipse Java EE Juno.

Here is the workaround that worked for me:

  1. Close Eclipse
  2. In {workspace-directory}/.metadata/.plugins/org.eclipse.core.runtime/.settings delete the following two files:
    • org.eclipse.wst.server.core.prefs
    • org.eclipse.jst.server.tomcat.core.prefs
  3. Restart Eclipse

Source: eclipse.org Forum

Hex-encoded String to Byte Array

I know it's late but hope it will help someone else...

This is my code: It takes two by two hex representations contained in String and add those into byte array. It works perfectly for me.

public byte[] stringToByteArray (String s) {
    byte[] byteArray = new byte[s.length()/2];
    String[] strBytes = new String[s.length()/2];
    int k = 0;
    for (int i = 0; i < s.length(); i=i+2) {
        int j = i+2;
        strBytes[k] = s.substring(i,j);
        byteArray[k] = (byte)Integer.parseInt(strBytes[k], 16);
        k++;
    }
    return byteArray;
}

In Bash, how can I check if a string begins with some value?

if [ [[ $HOST == user1 ]] -o [[ $HOST == node* ]] ];
then
echo yes
fi

doesn't work, because all of [, [[, and test recognize the same nonrecursive grammar. See section CONDITIONAL EXPRESSIONS on your Bash man page.

As an aside, the SUSv3 says

The KornShell-derived conditional command (double bracket [[]]) was removed from the shell command language description in an early proposal. Objections were raised that the real problem is misuse of the test command ([), and putting it into the shell is the wrong way to fix the problem. Instead, proper documentation and a new shell reserved word (!) are sufficient.

Tests that require multiple test operations can be done at the shell level using individual invocations of the test command and shell logicals, rather than using the error-prone -o flag of test.

You'd need to write it this way, but test doesn't support it:

if [ $HOST == user1 -o $HOST == node* ];
then
echo yes
fi

test uses = for string equality, and more importantly it doesn't support pattern matching.

case / esac has good support for pattern matching:

case $HOST in
user1|node*) echo yes ;;
esac

It has the added benefit that it doesn't depend on Bash, and the syntax is portable. From the Single Unix Specification, The Shell Command Language:

case word in
    [(]pattern1) compound-list;;
    [[(]pattern[ | pattern] ... ) compound-list;;] ...
    [[(]pattern[ | pattern] ... ) compound-list]
esac

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

To make any CORS protocol to work, you need to have a OPTIONS method on every endpoint (or a global filter with this method) that will return those headers :

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: content-type

The reason is that the browser will send first an OPTIONS request to 'test' your server and see the authorizations

Storyboard doesn't contain a view controller with identifier

While entering the identifier u have not selected proper view controller, just check once if done repeat the procedure once more.

What Does 'zoom' do in CSS?

Surprised that nobody mentioned that zoom: 1; is useful for IE6-7, to solve most IE-only bugs by triggering hasLayout.

Center Div inside another (100% width) div

The key is the margin: 0 auto; on the inner div. A proof-of-concept example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<body>
    <div style="background-color: blue; width: 100%;">
        <div style="background-color: yellow; width: 940px; margin: 0 auto;">
            Test
        </div>
    </div>
</body>
</html>

List all environment variables from the command line

As mentioned in other answers, you can use set to list all the environment variables or use

set [environment_variable] to get a specific variable with its value.

set [environment_variable]= can be used to remove a variable from the workspace.

D3.js: How to get the computed width and height for an arbitrary element?

.getBoundingClientRect() returns the size of an element and its position relative to the viewport.We can easily get following

  • left, right
  • top, bottom
  • height, width

Example :

var element = d3.select('.elementClassName').node();
element.getBoundingClientRect().width;

Submit form and stay on same page?

99% of the time I would use XMLHttpRequest or fetch for something like this. However, there's an alternative solution which doesn't require javascript...

You could include a hidden iframe on your page and set the target attribute of your form to point to that iframe.

<style>
  .hide { position:absolute; top:-1px; left:-1px; width:1px; height:1px; }
</style>

<iframe name="hiddenFrame" class="hide"></iframe>

<form action="receiver.pl" method="post" target="hiddenFrame">
  <input name="signed" type="checkbox">
  <input value="Save" type="submit">
</form>

There are very few scenarios where I would choose this route. Generally handling it with javascript is better because, with javascript you can...

  • gracefully handle errors (e.g. retry)
  • provide UI indicators (e.g. loading, processing, success, failure)
  • run logic before the request is sent, or run logic after the response is received.

How can I remove non-ASCII characters but leave periods and spaces using Python?

You may use the following code to remove non-English letters:

import re
str = "123456790 ABC#%? .(???)"
result = re.sub(r'[^\x00-\x7f]',r'', str)
print(result)

This will return

123456790 ABC#%? .()

Does svn have a `revert-all` command?

Use the recursive switch --recursive (-R)

svn revert -R .

How do I use NSTimer?

The answers are missing a specific time of day timer here is on the next hour:

NSCalendarUnit allUnits = NSCalendarUnitYear   | NSCalendarUnitMonth |
                          NSCalendarUnitDay    | NSCalendarUnitHour  |
                          NSCalendarUnitMinute | NSCalendarUnitSecond;

NSCalendar *calendar = [[ NSCalendar alloc]  
                          initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *weekdayComponents = [calendar components: allUnits 
                                                  fromDate: [ NSDate date ] ];

[ weekdayComponents setHour: weekdayComponents.hour + 1 ];
[ weekdayComponents setMinute: 0 ];
[ weekdayComponents setSecond: 0 ];

NSDate *nextTime = [ calendar dateFromComponents: weekdayComponents ];

refreshTimer = [[ NSTimer alloc ] initWithFireDate: nextTime
                                          interval: 0.0
                                            target: self
                                          selector: @selector( doRefresh )
                                          userInfo: nil repeats: NO ];

[[NSRunLoop currentRunLoop] addTimer: refreshTimer forMode: NSDefaultRunLoopMode];

Of course, substitute "doRefresh" with your class's desired method

try to create the calendar object once and make the allUnits a static for efficiency.

adding one to hour component works just fine, no need for a midnight test (link)

how to increase java heap memory permanently?

This worked for me:

export _JAVA_OPTIONS="-Xmx1g"

It's important that you have no spaces because for me it did not work. I would suggest just copying and pasting. Then I ran:

java -XshowSettings:vm

and it will tell you:

Picked up _JAVA_OPTIONS: -Xmx1g

Uncaught TypeError: Cannot set property 'onclick' of null

So I was having a similar issue and I managed to solve it by putting the script tag with my JS file after the closing body tag.

I assume it's because it makes sure there's something to reference, but I am not entirely sure.

How can I check if my Element ID has focus?

Use document.activeElement

Should work.

P.S getElementById("myID") not getElementById("#myID")

How can I get the DateTime for the start of the week?

Use an extension method. They're the answer to everything, you know! ;)

public static class DateTimeExtensions
{
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
        return dt.AddDays(-1 * diff).Date;
    }
}

Which can be used as follows:

DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);

Why is the minidlna database not being refreshed?

In summary, the most reliable way to have MiniDLNA rescan all media files is by issuing the following set of commands:

$ sudo minidlnad -R
$ sudo service minidlna restart

Client-side script to rescan server

However, every so often MiniDLNA will be running on a server. Here is a client-side script to request a rescan on such a server:

#!/usr/bin/env bash
ssh -t server.on.lan 'sudo minidlnad -R && sudo service minidlna restart'

How to get child process from parent process

You can get the pids of all child processes of a given parent process <pid> by reading the /proc/<pid>/task/<tid>/children entry.

This file contain the pids of first level child processes.

For more information head over to https://lwn.net/Articles/475688/

TortoiseSVN icons not showing up under Windows 7

They display fine here. Are you using the 64-bit version of Windows 7 along with the 32-bit version of TortoiseSVN? If so, then they will only show up in the 32-bit Explorer (or in the CFDs of 32-bit applications). You can install both 32-bit and 64-bit versions side-by-side, though.

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

The code below works for me (thanks to Christopher Zimmermann for his blog post http://dev.magnolia-cms.com/blog/2012/05/strategies-for-the-iframe-on-the-ipad-problem/). The problems are:

  1. There are no scroll bars to let the user know that they can scroll
  2. Users have to use two-finger scrolling
  3. The PDF files are not centered (still working on it)

    <!DOCTYPE HTML>
    <html>
    <head>
      <title>Testing iFrames on iPad</title>
      <style>
      div {
        border: solid 1px green;
        height:100px;
      }
    
    .scroller{
        border:solid 1px #66AA66;
        height: 400px;
        width: 400px;
        overflow: auto;
        text-align:center;
    
    }
    </style>
    

    <table>
      <tr>
        <td><div class="scroller">
        <iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
    </div>
        </td>
        <td><div class="scroller">
        <iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
    </div>
        </td>
      </tr>
      <tr>
      <td><div class="scroller">
        <iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
    </div>
        </td>
        <td><div class="scroller">
        <iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
    </div>
        </td>
      </tr>
    </table>
    <div> Here are some additional contents.</div>
    

Use HTML5 to resize an image before upload

if any interested I've made a typescript version:

interface IResizeImageOptions {
  maxSize: number;
  file: File;
}
const resizeImage = (settings: IResizeImageOptions) => {
  const file = settings.file;
  const maxSize = settings.maxSize;
  const reader = new FileReader();
  const image = new Image();
  const canvas = document.createElement('canvas');
  const dataURItoBlob = (dataURI: string) => {
    const bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
        atob(dataURI.split(',')[1]) :
        unescape(dataURI.split(',')[1]);
    const mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
    const max = bytes.length;
    const ia = new Uint8Array(max);
    for (var i = 0; i < max; i++) ia[i] = bytes.charCodeAt(i);
    return new Blob([ia], {type:mime});
  };
  const resize = () => {
    let width = image.width;
    let height = image.height;

    if (width > height) {
        if (width > maxSize) {
            height *= maxSize / width;
            width = maxSize;
        }
    } else {
        if (height > maxSize) {
            width *= maxSize / height;
            height = maxSize;
        }
    }

    canvas.width = width;
    canvas.height = height;
    canvas.getContext('2d').drawImage(image, 0, 0, width, height);
    let dataUrl = canvas.toDataURL('image/jpeg');
    return dataURItoBlob(dataUrl);
  };

  return new Promise((ok, no) => {
      if (!file.type.match(/image.*/)) {
        no(new Error("Not an image"));
        return;
      }

      reader.onload = (readerEvent: any) => {
        image.onload = () => ok(resize());
        image.src = readerEvent.target.result;
      };
      reader.readAsDataURL(file);
  })    
};

and here's the javascript result:

var resizeImage = function (settings) {
    var file = settings.file;
    var maxSize = settings.maxSize;
    var reader = new FileReader();
    var image = new Image();
    var canvas = document.createElement('canvas');
    var dataURItoBlob = function (dataURI) {
        var bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
            atob(dataURI.split(',')[1]) :
            unescape(dataURI.split(',')[1]);
        var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
        var max = bytes.length;
        var ia = new Uint8Array(max);
        for (var i = 0; i < max; i++)
            ia[i] = bytes.charCodeAt(i);
        return new Blob([ia], { type: mime });
    };
    var resize = function () {
        var width = image.width;
        var height = image.height;
        if (width > height) {
            if (width > maxSize) {
                height *= maxSize / width;
                width = maxSize;
            }
        } else {
            if (height > maxSize) {
                width *= maxSize / height;
                height = maxSize;
            }
        }
        canvas.width = width;
        canvas.height = height;
        canvas.getContext('2d').drawImage(image, 0, 0, width, height);
        var dataUrl = canvas.toDataURL('image/jpeg');
        return dataURItoBlob(dataUrl);
    };
    return new Promise(function (ok, no) {
        if (!file.type.match(/image.*/)) {
            no(new Error("Not an image"));
            return;
        }
        reader.onload = function (readerEvent) {
            image.onload = function () { return ok(resize()); };
            image.src = readerEvent.target.result;
        };
        reader.readAsDataURL(file);
    });
};

usage is like:

resizeImage({
    file: $image.files[0],
    maxSize: 500
}).then(function (resizedImage) {
    console.log("upload resized image")
}).catch(function (err) {
    console.error(err);
});

or (async/await):

const config = {
    file: $image.files[0],
    maxSize: 500
};
const resizedImage = await resizeImage(config)
console.log("upload resized image")

Difference between "process.stdout.write" and "console.log" in node.js?

console.log() calls process.stdout.write with formatted output. See format() in console.js for the implementation.

Currently (v0.10.ish):

Console.prototype.log = function() {
  this._stdout.write(util.format.apply(this, arguments) + '\n');
};

Where are SQL Server connection attempts logged?

You can enable connection logging. For SQL Server 2008, you can enable Login Auditing. In SQL Server Management Studio, open SQL Server Properties > Security > Login Auditing select "Both failed and successful logins".

Make sure to restart the SQL Server service.

Once you've done that, connection attempts should be logged into SQL's error log. The physical logs location can be determined here.

ERROR in Cannot find module 'node-sass'

npm install node-sass will do the job in most of the cases, as it will add missing sass npm dependency module doesn't exist or it will overwrite previous crashed version.

For Mac Users use sudo in front of above commands.

On Windows machines npm rebuild node-sass --force may not work for some users because it's essentially saying, "please force npm to rebuild the sass node module for me". It will not work because that module doesn't exist.

Whenever you did npm install to the initial installation, the sass module did not get installed, which is why this problem occurs.

What is the point of "Initial Catalog" in a SQL Server connection string?

Setting an Initial Catalog allows you to set the database that queries run on that connection will use by default. If you do not set this for a connection to a server in which multiple databases are present, in many cases you will be required to have a USE statement in every query in order to explicitly declare which database you are trying to run the query on. The Initial Catalog setting is a good way of explicitly declaring a default database.

npm command to uninstall or prune unused packages in Node.js

If you're not worried about a couple minutes time to do so, a solution would be to rm -rf node_modules and npm install again to rebuild the local modules.

How do you create a temporary table in an Oracle database?

CREATE TABLE table_temp_list_objects AS
SELECT o.owner, o.object_name FROM sys.all_objects o WHERE o.object_type ='TABLE';

Access-Control-Allow-Origin wildcard subdomains, ports and protocols

We were having similar issues with Font Awesome on a static "cookie-less" domain when reading fonts from the "cookie domain" (www.domain.tld) and this post was our hero. See here: How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

For the copy/paste-r types (and to give some props) I pieced this together from all the contributions and added it to the top of the .htaccess file of the site root:

<IfModule mod_headers.c>
 <IfModule mod_rewrite.c>
    SetEnvIf Origin "http(s)?://(.+\.)?(othersite\.com|mywebsite\.com)(:\d{1,5})?$" CORS=$0
    Header set Access-Control-Allow-Origin "%{CORS}e" env=CORS
    Header merge  Vary "Origin"
 </IfModule>
</IfModule>

Super Secure, Super Elegant. Love it: You don't have to open up your servers bandwidth to resource thieves / hot-link-er types.

Props to:@Noyo @DaveRandom @pratap-koritala

(I tried to leave this as a comment to the accepted answer, but I can't do that yet)

Return a 2d array from a function

The function returns a static 2D array

const int N = 6;
int (*(MakeGridOfCounts)())[N] {
 static int cGrid[N][N] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};
 return cGrid;
}

int main() {
int (*arr)[N];
arr = MakeGridOfCounts();
}

You need to make the array static since it will be having a block scope, when the function call ends, the array will be created and destroyed. Static scope variables last till the end of program.

Is there a way to programmatically minimize a window

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
     if(e.KeyChar == 'm')
         this.WindowState = FormWindowState.Minimized;
}

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

By default, IUSR account is used for anonymous user.

All you need to do is:

IIS -> Authentication --> Set Anonymous Authentication to Application Pool Identity.

Problem solved :)

How do I run a simple bit of code in a new thread?

Here how can use threads with a progressBar , its just for understing how the threads works, in the form there are three progressBar and 4 button:

 public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    Thread t, t2, t3;
    private void Form1_Load(object sender, EventArgs e)
    {

        CheckForIllegalCrossThreadCalls = false;

         t = new Thread(birinicBar); //evry thread workes with a new progressBar


         t2 = new Thread(ikinciBar);


         t3 = new Thread(ucuncuBar);

    }

    public void birinicBar() //to make progressBar work
    {
        for (int i = 0; i < 100; i++) {
            progressBar1.Value++;
            Thread.Sleep(100); // this progressBar gonna work faster
        }
    }

    public void ikinciBar()
    {
        for (int i = 0; i < 100; i++)
        {
            progressBar2.Value++;
            Thread.Sleep(200);
        }


    }

    public void ucuncuBar()
    {
        for (int i = 0; i < 100; i++)
        {
            progressBar3.Value++;
            Thread.Sleep(300);
        }
    }

    private void button1_Click(object sender, EventArgs e) //that button to start the threads
    {
        t.Start();
        t2.Start(); t3.Start();

    }

    private void button4_Click(object sender, EventArgs e)//that button to stup the threads with the progressBar
    {
        t.Suspend();
        t2.Suspend();
        t3.Suspend();
    }

    private void button2_Click(object sender, EventArgs e)// that is for contuniue after stuping
    {
        t.Resume();
        t2.Resume();
        t3.Resume();
    }

    private void button3_Click(object sender, EventArgs e) // finally with that button you can remove all of the threads
    {
        t.Abort();
        t2.Abort();
        t3.Abort();
    }
}

Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

I use Windows Server 2012 for hosting for a long time and it just stop working after a more than years without any problem. My solution was to add public IP address of the server to list of relays and enabled Windows Integrated Authentication.

I just made two changes and I don't which help.

Go to IIS 6 Manager

Go to IIS 6 Manager

Select properties of SMTP server

Select properties of SMTP server

On tab Access, select Relays

On tab Access, select Relays

Add your public IP address

Add your public IP address

Close the dialog and on the same tab click to Authentication button.

Add Integrated Windows Authentication

Add Integrated Windows Authentication

Maybe some step is not needed, but it works.

Limiting the number of characters per line with CSS

You could do this:
(Note! This is CSS3 and the browser support = good!! )

   p {
    text-overflow: ellipsis; /* will make [...] at the end */
    width: 370px; /* change to your preferences */
    white-space: nowrap; /* paragraph to one line */
    overflow:hidden; /* older browsers */
    }

Testing the type of a DOM element in JavaScript

Perhaps you'll have to check the nodetype too:

if(element.nodeType == 1){//element of type html-object/tag
  if(element.tagName=="a"){
    //this is an a-element
  }
  if(element.tagName=="div"){
    //this is a div-element
  }
}

Edit: Corrected the nodeType-value

MVC3 EditorFor readOnly

Here's how I do it:

Model:

[ReadOnly(true)]
public string Email { get { return DbUser.Email; } }

View:

@Html.TheEditorFor(x => x.Email)

Extension:

namespace System.Web.Mvc
{
    public static class CustomExtensions
    {
        public static MvcHtmlString TheEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null)
        {
            return iEREditorForInternal(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
        }

        private static MvcHtmlString iEREditorForInternal<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
        {
            if (htmlAttributes == null) htmlAttributes = new Dictionary<string, object>();

            TagBuilder builder = new TagBuilder("div");
            builder.MergeAttributes(htmlAttributes);

            var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);


            string labelHtml = labelHtml = Html.LabelExtensions.LabelFor(htmlHelper, expression).ToHtmlString();

            if (metadata.IsRequired)
                labelHtml = Html.LabelExtensions.LabelFor(htmlHelper, expression, new { @class = "required" }).ToHtmlString();


            string editorHtml = Html.EditorExtensions.EditorFor(htmlHelper, expression).ToHtmlString();

            if (metadata.IsReadOnly)
                editorHtml = Html.DisplayExtensions.DisplayFor(htmlHelper, expression).ToHtmlString();


            string validationHtml = Html.ValidationExtensions.ValidationMessageFor(htmlHelper, expression).ToHtmlString();

            builder.InnerHtml = labelHtml + editorHtml + validationHtml;

            return new MvcHtmlString(builder.ToString(TagRenderMode.Normal));
        }
    }
}

Of course my editor is doing a bunch more stuff, like adding a label, adding a required class to that label as necessary, adding a DisplayFor if the property is ReadOnly EditorFor if its not, adding a ValidateMessageFor and finally wrapping all of that in a Div that can have Html Attributes assigned to it... my Views are super clean.

JavaScript backslash (\) in variables is causing an error

You have to escape each \ to be \\:

var ttt = "aa ///\\\\\\";

Updated: I think this question is not about the escape character in string at all. The asker doesn't seem to explain the problem correctly.

because you had to show a message to user that user can't give a name which has (\) character.

I think the scenario is like:

var user_input_name = document.getElementById('the_name').value;

Then the asker wants to check if user_input_name contains any [\]. If so, then alert the user.

If user enters [aa ///\] in HTML input box, then if you alert(user_input_name), you will see [aaa ///\]. You don't need to escape, i.e. replace [\] to be [\\] in JavaScript code. When you do escaping, that is because you are trying to make of a string which contain special characters in JavaScript source code. If you don't do it, it won't be parsed correct. Since you already get a string, you don't need to pass it into an escaping function. If you do so, I am guessing you are generating another JavaScript code from a JavaScript code, but it's not the case here.

I am guessing asker wants to simulate the input, so we can understand the problem. Unfortunately, asker doesn't understand JavaScript well. Therefore, a syntax error code being supplied to us:

var ttt = "aa ///\";

Hence, we assume the asker having problem with escaping.

If you want to simulate, you code must be valid at first place.

var ttt = "aa ///\\"; // <- This is correct
// var ttt = "aa ///\"; // <- This is not.

alert(ttt); // You will see [aa ///\] in dialog, which is what you expect, right?

Now, you only need to do is

var user_input_name = document.getElementById('the_name').value;
if (user_input_name.indexOf("\\") >= 0) { // There is a [\] in the string
  alert("\\ is not allowed to be used!"); // User reads [\ is not allowed to be used]
  do_something_else();
  }

Edit: I used [] to quote text to be shown, so it would be less confused than using "".

Testing Private method using mockito

Not possible through mockito. From their wiki

Why Mockito doesn't mock private methods?

Firstly, we are not dogmatic about mocking private methods. We just don't care about private methods because from the standpoint of testing private methods don't exist. Here are a couple of reasons Mockito doesn't mock private methods:

It requires hacking of classloaders that is never bullet proof and it changes the api (you must use custom test runner, annotate the class, etc.).

It is very easy to work around - just change the visibility of method from private to package-protected (or protected).

It requires me to spend time implementing & maintaining it. And it does not make sense given point #2 and a fact that it is already implemented in different tool (powermock).

Finally... Mocking private methods is a hint that there is something wrong with OO understanding. In OO you want objects (or roles) to collaborate, not methods. Forget about pascal & procedural code. Think in objects.

How to make execution pause, sleep, wait for X seconds in R?

See help(Sys.sleep).

For example, from ?Sys.sleep

testit <- function(x)
{
    p1 <- proc.time()
    Sys.sleep(x)
    proc.time() - p1 # The cpu usage should be negligible
}
testit(3.7)

Yielding

> testit(3.7)
   user  system elapsed 
  0.000   0.000   3.704 

Firebug-like debugger for Google Chrome

jQuerify is the perfect extension to embed jQuery into Chrome Console and is as simple as you can imagine. This extension also indicates if jQuery has been already embedded into a page.

This extension is used to embed jQuery into any page you want. It allows to use jQuery in the console shell (You can invoke Chrome console by Ctrl + Shift + j".).

To embed jQuery into the selected tab click on extension button.

Change IPython/Jupyter notebook working directory

For Windows 10

  1. Look for the jupyter_notebook_config.py in C:\Users\your_user_name\.jupyter or look it up with cortana.

  2. If you don't have it, then go to the cmd line and type:

    jupyter notebook --generate-config

  3. Open the jupyter_notebook_config.py and do a ctrl-f search for:

    c.NotebookApp.notebook_dir

  4. Uncomment it by removing the #.

  5. Change it to:

    c.NotebookApp.notebook_dir = 'C:/your/new/path'

    Note: You can put a u in front of the first ', change \\\\ to /, or change the ' to ". I don't think it matters.

  6. Go to your Jupyter Notebook link and right click it. Select properties. Go to the Shortcut menu and click Target. Look for %USERPROFILE%. Delete it. Save. Restart Jupyter.

How to set cache: false in jQuery.get call

To me, the correct way of doing it would be the ones listed. Either ajax or ajaxSetup. If you really want to use get and not use ajaxSetup then you could create your own parameter and give it the value of the the current date/time.

I would however question your motives in not using one of the other methods.

Android JSONObject - How can I loop through a flat JSON object to get each key and value

Use the keys() iterator to iterate over all the properties, and call get() for each.

Iterator<String> iter = json.keys();
while (iter.hasNext()) {
    String key = iter.next();
    try {
        Object value = json.get(key);
    } catch (JSONException e) {
        // Something went wrong!
    }
}

.keyCode vs. .which

I'd recommend event.key currently. MDN docs: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

event.KeyCode and event.which both have nasty deprecated warnings at the top of their MDN pages:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which

For alphanumeric keys, event.key appears to be implemented identically across all browsers. For control keys (tab, enter, escape, etc), event.key has the same value across Chrome/FF/Safari/Opera but a different value in IE10/11/Edge (IEs apparently use an older version of the spec but match each other as of Jan 14 2018).

For alphanumeric keys a check would look something like:

event.key === 'a'

For control characters you'd need to do something like:

event.key === 'Esc' || event.key === 'Escape'

I used the example here to test on multiple browsers (I had to open in codepen and edit to get it to work with IE10): https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code

event.code is mentioned in a different answer as a possibility, but IE10/11/Edge don't implement it, so it's out if you want IE support.

find -mtime files older than 1 hour

What about -mmin?

find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
    -exec rm -f {} \;

From man find:

-mmin n
        File's data was last modified n minutes ago.

Also, make sure to test this first!

... -exec echo rm -f '{}' \;
          ^^^^ Add the 'echo' so you just see the commands that are going to get
               run instead of actual trying them first.

Request Monitoring in Chrome

You can also just right click on the page in the browser and select "Inspect Element" to bring up the developer tools.

https://developer.chrome.com/devtools

How to display the value of the bar on each bar with pyplot.barh()?

I needed the bar labels too, note that my y-axis is having a zoomed view using limits on y axis. The default calculations for putting the labels on top of the bar still works using height (use_global_coordinate=False in the example). But I wanted to show that the labels can be put in the bottom of the graph too in zoomed view using global coordinates in matplotlib 3.0.2. Hope it help someone.

def autolabel(rects,data):
"""
Attach a text label above each bar displaying its height
"""
c = 0
initial = 0.091
offset = 0.205
use_global_coordinate = True

if use_global_coordinate:
    for i in data:        
        ax.text(initial+offset*c, 0.05, str(i), horizontalalignment='center',
                verticalalignment='center', transform=ax.transAxes,fontsize=8)
        c=c+1
else:
    for rect,i in zip(rects,data):
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., height,str(i),ha='center', va='bottom')

Example output

Python: json.loads returns items prefixing with 'u'

The d3 print below is the one you are looking for (which is the combination of dumps and loads) :)

Having:

import json

d = """{"Aa": 1, "BB": "blabla", "cc": "False"}"""

d1 = json.loads(d)              # Produces a dictionary out of the given string
d2 = json.dumps(d)              # Produces a string out of a given dict or string
d3 = json.dumps(json.loads(d))  # 'dumps' gets the dict from 'loads' this time

print "d1:  " + str(d1)
print "d2:  " + d2
print "d3:  " + d3

Prints:

d1:  {u'Aa': 1, u'cc': u'False', u'BB': u'blabla'}
d2:  "{\"Aa\": 1, \"BB\": \"blabla\", \"cc\": \"False\"}"
d3:  {"Aa": 1, "cc": "False", "BB": "blabla"}

What process is listening on a certain port on Solaris?

I found this script somewhere. I don't remember where, but it works for me:

#!/bin/ksh

line='---------------------------------------------'
pids=$(/usr/bin/ps -ef | sed 1d | awk '{print $2}')

if [ $# -eq 0 ]; then
   read ans?"Enter port you would like to know pid for: "
else
   ans=$1
fi

for f in $pids
do
   /usr/proc/bin/pfiles $f 2>/dev/null | /usr/xpg4/bin/grep -q "port: $ans"
   if [ $? -eq 0 ]; then
      echo $line
      echo "Port: $ans is being used by PID:\c"
      /usr/bin/ps -ef -o pid -o args | egrep -v "grep|pfiles" | grep $f
   fi
done
exit 0

Edit: Here is the original source: [Solaris] Which process is bound to a given port ?

Rounding a number to the nearest 5 or 10 or X

It's simple math. Given a number X and a rounding factor N, the formula would be:

round(X / N)*N

How to create Android Facebook Key Hash?

Download open ssl:

Then add openssl\bin to the path system variables:

My computer -> properties -> Advanced configurations -> Advanced -> System variables -> under system variables find path, and add this to its endings: ;yourFullOpenSSLDir\bin

Now open a command line on your jdk\bin folder C:\Program Files\Java\jdk1.8.0_40\bin (on windows hold shift and right click -> open command line here) and use:

keytool -exportcert -alias keystorealias -keystore C:\yourkeystore\folder\keystore.jks | openssl sha1 -binary | openssl base64

And copy the 28 lenght number it generates after giving the password.

Save current directory in variable using Bash?

current working directory variable ie full path /home/dev/other

dir=$PWD

print the full path

echo $dir

data type not understood

Try:

mmatrix = np.zeros((nrows, ncols))

Since the shape parameter has to be an int or sequence of ints

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

Otherwise you are passing ncols to np.zeros as the dtype.

Django - how to create a file and save it to a model's FileField?

It's good practice to use a context manager or call close() in case of exceptions during the file saving process. Could happen if your storage backend is down, etc.

Any overwrite behavior should be configured in your storage backend. For example S3Boto3Storage has a setting AWS_S3_FILE_OVERWRITE. If you're using FileSystemStorage you can write a custom mixin.

You might also want to call the model's save method instead of the FileField's save method if you want any custom side-effects to happen, like last-updated timestamps. If that's the case, you can also set the name attribute of the file to the name of the file - which is relative to MEDIA_ROOT. It defaults to the full path of the file which can cause problems if you don't set it - see File.__init__() and File.name.

Here's an example where self is the model instance where my_file is the FileField / ImageFile, calling save() on the whole model instance instead of just FileField:

import os
from django.core.files import File

with open(filepath, 'rb') as fi:
    self.my_file = File(fi, name=os.path.basename(fi.name))
    self.save()

What's the best way to cancel event propagation between nested ng-click calls?

If you don't want to have to add the stop propagation to all links this works as well. A bit more scalable.

$scope.hideOverlay( $event ){

   // only hide the overlay if we click on the actual div
   if( $event.target.className.indexOf('overlay') ) 
      // hide overlay logic

}

How to determine the number of days in a month in SQL Server?

select  datediff(day, 
        dateadd(day, 0, dateadd(month, ((2013 - 1900) * 12) + 3 - 1, 0)),
        dateadd(day, 0, dateadd(month, ((2013  - 1900) * 12) + 3, 0))
        )

Nice Simple and does not require creating any functions Work Fine

CodeIgniter: How to use WHERE clause and OR clause

$where = "name='Joe' AND status='boss' OR status='active'";

$this->db->where($where);

What does 'super' do in Python?

class Child(SomeBaseClass):
    def __init__(self):
        SomeBaseClass.__init__(self)

This is fairly easy to understand.

class Child(SomeBaseClass):
    def __init__(self):
        super(Child, self).__init__()

Ok, what happens now if you use super(Child,self)?

When a Child instance is created, its MRO(Method Resolution Order) is in the order of (Child, SomeBaseClass, object) based on the inheritance. (assume SomeBaseClass doesn't have other parents except for the default object)

By passing Child, self, super searches in the MRO of the self instance, and return the proxy object next of Child, in this case it's SomeBaseClass, this object then invokes the __init__ method of SomeBaseClass. In other word, if it's super(SomeBaseClass,self), the proxy object that super returns would be object

For multi inheritance, the MRO could contain many classes, so basically super lets you decide where you want to start searching in the MRO.

XAMPP MySQL password setting (Can not enter in PHPMYADMIN)

Find the below code in xampp/phpmyadmin/config.inc.php

$cfg['Servers'][$i]['controluser']  = 'user_name/root';   
$cfg['Servers'][$i]['controlpass']  = 'passwaord';
$cfg['Servers'][$i]['auth_type']    = 'config';
$cfg['Servers'][$i]['user']         = 'user_name/root';
$cfg['Servers'][$i]['password']     = 'password';

Replace each statement above with the corresponding entry below:

$cfg['Servers'][$i]['controluser']  = 'root';   
$cfg['Servers'][$i]['controlpass']  = 'xxxx';
$cfg['Servers'][$i]['auth_type']    = 'config';
$cfg['Servers'][$i]['user']         = 'root';
$cfg['Servers'][$i]['password']     = 'xxxx';

Doing this caused localhost/phpmyadmin in the browser and the MySQL command prompt to work properly.

String to LocalDate

Datetime formatting is performed by the org.joda.time.format.DateTimeFormatter class. Three classes provide factory methods to create formatters, and this is one. The others are ISODateTimeFormat and DateTimeFormatterBuilder.

DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MMM-dd");
LocalDate lDate = new LocalDate().parse("2005-nov-12",format);

final org.joda.time.LocalDate class is an immutable datetime class representing a date without a time zone. LocalDate is thread-safe and immutable, provided that the Chronology is as well. All standard Chronology classes supplied are thread-safe and immutable.

Changing the interval of SetInterval while it's running

I had the same question as the original poster, did this as a solution. Not sure how efficient this is ....

interval = 5000; // initial condition
var run = setInterval(request , interval); // start setInterval as "run"

    function request() { 

        console.log(interval); // firebug or chrome log
        clearInterval(run); // stop the setInterval()

         // dynamically change the run interval
        if(interval>200 ){
          interval = interval*.8;
        }else{
          interval = interval*1.2;
        }

        run = setInterval(request, interval); // start the setInterval()

    }

ASP.NET Display "Loading..." message while update panel is updating

You can use code as below when

using Image as Loading

<asp:UpdateProgress id="updateProgress" runat="server">
    <ProgressTemplate>
        <div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
            <asp:Image ID="imgUpdateProgress" runat="server" ImageUrl="~/images/ajax-loader.gif" AlternateText="Loading ..." ToolTip="Loading ..." style="padding: 10px;position:fixed;top:45%;left:50%;" />
        </div>
    </ProgressTemplate>
</asp:UpdateProgress>

using Text as Loading

<asp:UpdateProgress id="updateProgress" runat="server">
    <ProgressTemplate>
        <div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
            <span style="border-width: 0px; position: fixed; padding: 50px; background-color: #FFFFFF; font-size: 36px; left: 40%; top: 40%;">Loading ...</span>
        </div>
    </ProgressTemplate>
</asp:UpdateProgress>

Recursive Fibonacci

Why not use iterative algorithm?

int fib(int n)
{
    int a = 1, b = 1;
    for (int i = 3; i <= n; i++) {
        int c = a + b;
        a = b;
        b = c;
    }           
    return b;
}

Fixed page header overlaps in-page anchors

The best way that I found to handle this issue is (replace 65px with your fixed element height):

div:target {
  padding-top: 65px; 
  margin-top: -65px;
}

If you do not like to use the target selector you can also do it in this way:

.my-target {
    padding-top: 65px;
    margin-top: -65px;
}

Note: this example will not work if the target element have a backgound color that differant from his parent. for example:

<div style="background-color:red;height:100px;"></div>
<div class="my-target" style="background-color:green;height:100px;"></div>

in this case the green color of my-target element will overwrite his parent red element in 65px. I did not find any pure CSS solution to handle this issue but if you do not have another background color this solution is the best.

Setting a minimum/maximum character count for any character using a regular expression

If you also want to match newlines, then you might want to use "^[\s\S]{1,35}$" (depending on the regex engine). Otherwise, as others have said, you should used "^.{1,35}$"

How do you import classes in JSP?

Use Page Directive to import a Class in JSP page. Page Directive Uses 11 Different types of Attributes , One of them is "import". Page Directive with import Attribute Allows you to Mention more than one package at the same place separated by Commas(,). Alternatively you can have multiple instances of page element each one with Different package .

For Example:

 <%@ page import = "java.io.*" %>
 <%@ page import = "java.io.*", "java.util.*"%>

Note : the import attribute should be placed before the element that calls the importd class .

How can I run Tensorboard on a remote server?

While running the tensorboard give one more option --host=ip of your system and then you can access it from other system using http://ip of your host system:6006

Can I serve multiple clients using just Flask app.run() as standalone?

Tips from 2020:

From Flask 1.0, it defaults to enable multiple threads (source), you don't need to do anything, just upgrade it with:

$ pip install -U flask

If you are using flask run instead of app.run() with older versions, you can control the threaded behavior with a command option (--with-threads/--without-threads):

$ flask run --with-threads

It's same as app.run(threaded=True)

What is the difference between C# and .NET?

Here I provided you a link where explain what is C# Language and the .NET Framework Platform Architecture. Remember that C# is a general-purpose, object-oriented programming language, and it runs on the .NET Framework.

.NET Framework includes a large class library named Framework Class Library (FCL) and provides user interface, data access, database connectivity, cryptography, web application development, numeric algorithms, and network communications.

.NET Framework was developed by Microsoft that runs primarily on Microsoft Windows.

Introduction to the C# Language and the .NET Framework from Microsoft Docs

Print values for multiple variables on the same line from within a for-loop

Try out cat and sprintf in your for loop.

eg.

cat(sprintf("\"%f\" \"%f\"\n", df$r, df$interest))

See here

UnicodeEncodeError: 'ascii' codec can't encode character at special name

You really want to do this

flog.write("\nCompany Name: "+ pCompanyName.encode('utf-8'))

This is the "encode late" strategy described in this unicode presentation (slides 32 through 35).

Close window automatically after printing dialog closes

I tried many things that didn't work. The only thing that worked for me was:

window.print();
window.onafterprint = function () {
    window.close();
}

tested on chrome.

How can I use numpy.correlate to do autocorrelation?

To answer your first question, numpy.correlate(a, v, mode) is performing the convolution of a with the reverse of v and giving the results clipped by the specified mode. The definition of convolution, C(t)=? -8 < i < 8 aivt+i where -8 < t < 8, allows for results from -8 to 8, but you obviously can't store an infinitely long array. So it has to be clipped, and that is where the mode comes in. There are 3 different modes: full, same, & valid:

  • "full" mode returns results for every t where both a and v have some overlap.
  • "same" mode returns a result with the same length as the shortest vector (a or v).
  • "valid" mode returns results only when a and v completely overlap each other. The documentation for numpy.convolve gives more detail on the modes.

For your second question, I think numpy.correlate is giving you the autocorrelation, it is just giving you a little more as well. The autocorrelation is used to find how similar a signal, or function, is to itself at a certain time difference. At a time difference of 0, the auto-correlation should be the highest because the signal is identical to itself, so you expected that the first element in the autocorrelation result array would be the greatest. However, the correlation is not starting at a time difference of 0. It starts at a negative time difference, closes to 0, and then goes positive. That is, you were expecting:

autocorrelation(a) = ? -8 < i < 8 aivt+i where 0 <= t < 8

But what you got was:

autocorrelation(a) = ? -8 < i < 8 aivt+i where -8 < t < 8

What you need to do is take the last half of your correlation result, and that should be the autocorrelation you are looking for. A simple python function to do that would be:

def autocorr(x):
    result = numpy.correlate(x, x, mode='full')
    return result[result.size/2:]

You will, of course, need error checking to make sure that x is actually a 1-d array. Also, this explanation probably isn't the most mathematically rigorous. I've been throwing around infinities because the definition of convolution uses them, but that doesn't necessarily apply for autocorrelation. So, the theoretical portion of this explanation may be slightly wonky, but hopefully the practical results are helpful. These pages on autocorrelation are pretty helpful, and can give you a much better theoretical background if you don't mind wading through the notation and heavy concepts.

Validate that end date is greater than start date with jQuery

jQuery('#from_date').on('change', function(){
    var date = $(this).val();
    jQuery('#to_date').datetimepicker({minDate: date});  
});

How to measure the a time-span in seconds using System.currentTimeMillis()?

I have written the following code in my last assignment, it may help you:

// A method that converts the nano-seconds to Seconds-Minutes-Hours form
private static String formatTime(long nanoSeconds)
{
    int hours, minutes, remainder, totalSecondsNoFraction;
    double totalSeconds, seconds;


    // Calculating hours, minutes and seconds
    totalSeconds = (double) nanoSeconds / 1000000000.0;
    String s = Double.toString(totalSeconds);
    String [] arr = s.split("\\.");
    totalSecondsNoFraction = Integer.parseInt(arr[0]);
    hours = totalSecondsNoFraction / 3600;
    remainder = totalSecondsNoFraction % 3600;
    minutes = remainder / 60;
    seconds = remainder % 60;
    if(arr[1].contains("E")) seconds = Double.parseDouble("." + arr[1]);
    else seconds += Double.parseDouble("." + arr[1]);


    // Formatting the string that conatins hours, minutes and seconds
    StringBuilder result = new StringBuilder(".");
    String sep = "", nextSep = " and ";
    if(seconds > 0)
    {
        result.insert(0, " seconds").insert(0, seconds);
        sep = nextSep;
        nextSep = ", ";
    }
    if(minutes > 0)
    {
        if(minutes > 1) result.insert(0, sep).insert(0, " minutes").insert(0, minutes);
        else result.insert(0, sep).insert(0, " minute").insert(0, minutes);
        sep = nextSep;
        nextSep = ", ";
    }
    if(hours > 0)
    {
        if(hours > 1) result.insert(0, sep).insert(0, " hours").insert(0, hours);
        else result.insert(0, sep).insert(0, " hour").insert(0, hours);
    }
    return result.toString();
}

Just convert nano-seconds to milli-seconds.

How to exclude file only from root folder in Git

Older versions of git require you first define an ignore pattern and immediately (on the next line) define the exclusion. [tested on version 1.9.3 (Apple Git-50)]

/config.php
!/*/config.php

Later versions only require the following [tested on version 2.2.1]

/config.php

How to upload file to server with HTTP POST multipart/form-data?

hi guys after one day searching on web finally i solve problem with below source code hope to help you

    public UploadResult UploadFile(string  fileAddress)
    {
        HttpClient client = new HttpClient();

        MultipartFormDataContent form = new MultipartFormDataContent();
        HttpContent content = new StringContent("fileToUpload");
        form.Add(content, "fileToUpload");       
        var stream = new FileStream(fileAddress, FileMode.Open);            
        content = new StreamContent(stream);
        var fileName = 
        content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
        {
            Name = "name",
            FileName = Path.GetFileName(fileAddress),                 
        };
        form.Add(content);
        HttpResponseMessage response = null;          

        var url = new Uri("http://192.168.10.236:2000/api/Upload2");
        response = (client.PostAsync(url, form)).Result;          

    }

AngularJS - Create a directive that uses ng-model

Since Angular 1.5 it's possible to use Components. Components are the-way-to-go and solves this problem easy.

<myComponent data-ng-model="$ctrl.result"></myComponent>

app.component("myComponent", {
    templateUrl: "yourTemplate.html",
    controller: YourController,
    bindings: {
        ngModel: "="
    }
});

Inside YourController all you need to do is:

this.ngModel = "x"; //$scope.$apply("$ctrl.ngModel"); if needed

KeyListener, keyPressed versus keyTyped

private String message;
private ScreenManager s;


//Here is an example of code to add the keyListener() as suggested; modify 
public void init(){
Window w = s.getFullScreenWindow();
w.addKeyListener(this);

public void keyPressed(KeyEvent e){
    int keyCode = e.getKeyCode();
        if(keyCode == KeyEvent.VK_F5)
            message = "Pressed: " + KeyEvent.getKeyText(keyCode);
}

What is the easiest way to encrypt a password when I save it to the registry?

One option would be to store the hash (SHA1, MD5) of the password instead of the clear-text password, and whenever you want to see if the password is good, just compare it to that hash.

If you need secure storage (for example for a password that you will use to connect to a service), then the problem is more complicated.

If it is just for authentication, then it would be enough to use the hash.

Conversion failed when converting from a character string to uniqueidentifier

this fails:

 DECLARE @vPortalUID NVARCHAR(32)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
 PRINT @nPortalUID

this works

 DECLARE @vPortalUID NVARCHAR(36)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
 PRINT @nPortalUID

the difference is NVARCHAR(36), your input parameter is too small!

How to extract extension from filename string in Javascript?

I use code below:

var fileSplit = filename.split('.');
var fileExt = '';
if (fileSplit.length > 1) {
fileExt = fileSplit[fileSplit.length - 1];
} 
return fileExt;

TypeError: '<=' not supported between instances of 'str' and 'int'

When you use the input function it automatically turns it into a string. You need to go:

vote = int(input('Enter the name of the player you wish to vote for'))

which turns the input into a int type value

Catch browser's "zoom" event in JavaScript

Good news everyone some people! Newer browsers will trigger a window resize event when the zoom is changed.

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

After all the Jquery script tag's add

<script>jQuery.noConflict();</script>

to avoid the conflict between Prototype and Jquery.

What is the difference between Sublime text and Github's Atom

Atom is open source (has been for a few hours by now), whereas Sublime Text is not.

Inserting HTML elements with JavaScript

Instead of directly messing with innerHTML it might be better to create a fragment and then insert that:

function create(htmlStr) {
    var frag = document.createDocumentFragment(),
        temp = document.createElement('div');
    temp.innerHTML = htmlStr;
    while (temp.firstChild) {
        frag.appendChild(temp.firstChild);
    }
    return frag;
}

var fragment = create('<div>Hello!</div><p>...</p>');
// You can use native DOM methods to insert the fragment:
document.body.insertBefore(fragment, document.body.childNodes[0]);

Benefits:

  1. You can use native DOM methods for insertion such as insertBefore, appendChild etc.
  2. You have access to the actual DOM nodes before they're inserted; you can access the fragment's childNodes object.
  3. Using document fragments is very quick; faster than creating elements outside of the DOM and in certain situations faster than innerHTML.

Even though innerHTML is used within the function, it's all happening outside of the DOM so it's much faster than you'd think...

Get the value of input text when enter key pressed

Listen the change event.

document.querySelector("input")
  .addEventListener('change', (e) => {
    console.log(e.currentTarget.value);
 });

Where is GACUTIL for .net Framework 4.0 in windows 7?

If you've got VS2010 installed, you ought to find a .NET 4.0 gacutil at

C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools

The 7.0A Windows SDK should have been installed alongside VS2010 - 6.0A will have been installed with VS2008, and hence won't have .NET 4.0 support.

How to run sql script using SQL Server Management Studio?

Found this in another thread that helped me: Use xp_cmdshell and sqlcmd Is it possible to execute a text file from SQL query? - by Gulzar Nazim

EXEC xp_cmdshell  'sqlcmd -S ' + @DBServerName + ' -d  ' + @DBName + ' -i ' + @FilePathName

delete a column with awk or sed

try this short thing:

awk '!($3="")' file

VB.NET: Clear DataGridView

My DataGridView is also bound to a DataSource and myDataGridView.Columns.Clear() worked fine but myDataGridView.Rows.Clear() did NOT. Just an FYI for those who have tried .Rows.

Enable/Disable a dropdownbox in jquery

$("#chkdwn2").change(function() { 
    if (this.checked) $("#dropdown").prop("disabled",'disabled');
}) 

How to perform case-insensitive sorting in JavaScript?

ES6 version:

["Foo", "bar"].sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }))

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

angular 4: *ngIf with multiple conditions

Besides the redundant ) this expression will always be true because currentStatus will always match one of these two conditions:

currentStatus !== 'open' || currentStatus !== 'reopen'

perhaps you mean one of

!(currentStatus === 'open' || currentStatus === 'reopen')
(currentStatus !== 'open' && currentStatus !== 'reopen')

Is it possible to specify condition in Count()?

SELECT COUNT(*) FROM bla WHERE Position = 'Manager'

How to remove close button on the jQuery UI dialog?

Robert MacLean's answer did not work for me.

This however does work for me:

$("#div").dialog({
   open: function() { $(".ui-dialog-titlebar-close").hide(); }
});

Accessing Session Using ASP.NET Web API

To fix the issue:

protected void Application_PostAuthorizeRequest()
{
    System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}

in Global.asax.cs

How do I copy SQL Azure database to my local development server?

The accepted answer is out of date. I found a better answer: Use Import Data-tier Application

More detailed information please see this article: Restoring Azure SQL Database to a Local Server

What is the 'instanceof' operator used for in Java?

The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

http://download.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

What are .tpl files? PHP, web design

Other possibilities for .tpl: HTML::SimpleTemplate, example:

Hello $name

, and Template Toolkit, example:

Hello [% world %]!

How do I remove an item from a stl vector with a certain value?

If you want to remove an item, the following will be a bit more efficient.

std::vector<int> v;


auto it = std::find(v.begin(), v.end(), 5);
if(it != v.end())
    v.erase(it);

or you may avoid overhead of moving the items if the order does not matter to you:

std::vector<int> v;

auto it = std::find(v.begin(), v.end(), 5);

if (it != v.end()) {
  using std::swap;

  // swap the one to be removed with the last element
  // and remove the item at the end of the container
  // to prevent moving all items after '5' by one
  swap(*it, v.back());
  v.pop_back();
}

Email address validation using ASP.NET MVC data type attributes

Used the above code in MVC5 project and it works completely fine with the validation error. Just try this code:

   [Required]
   [Display(Name = "Email")]
   [EmailAddress]

   [RegularExpression(@"^([A-Za-z0-9][^'!&\\#*$%^?<>()+=:;`~\[\]{}|/,?€@ ][a-zA-z0- 
    9-._][^!&\\#*$%^?<>()+=:;`~\[\]{}|/,?€@ ]*\@[a-zA-Z0-9][^!&@\\#*$%^?<> 
        ()+=':;~`.\[\]{}|/,?€ ]*\.[a-zA-Z]{2,6})$", ErrorMessage = "Please enter a 
   valid Email")]


   public string ReceiverMail { get; set; }

How to use jQuery to show/hide divs based on radio button selection?

<script type="text/javascript">
$(function() {
    $("[name=toggler]").click(function(){
            $('.toHide').hide();
            $("#blk-"+$(this).val()).show('slow');
    });
 });
</script>
</head>
<body>
<label><input id="rdb1" type="radio" name="toggler" value="1" />Book</label>
<label><input id="rdb2" type="radio" name="toggler" value="2" />Non-Book</label>

<div id="blk-1" class="toHide" style="display:none">

    <form action="success1.html">

        Name1:<input type="text" name="name">
             <input type="submit" name="submit">

    </form>

</div>
<div id="blk-2" class="toHide" style="display:none">

    <form action="success1.html">

        Name2:<input type="text" name="name">
             <input type="submit" name="submit">

    </form>
</div>

.trim() in JavaScript not working in IE

This is because of typo error getElementByID. Change it to getElementById

How do I extract Month and Year in a MySQL date and compare them?

If you are comparing between dates, extract the full date for comparison. If you are comparing the years and months only, use

SELECT YEAR(date) AS 'year', MONTH(date) AS 'month'
 FROM Table Where Condition = 'Condition';

How to find a hash key containing a matching value

You could use Enumerable#select:

clients.select{|key, hash| hash["client_id"] == "2180" }
#=> [["orange", {"client_id"=>"2180"}]]

Note that the result will be an array of all the matching values, where each is an array of the key and value.

Why does Oracle not find oci.dll?

I had this issue, I run 64 bit Windows and had downloaded the 64 bit TOAD package. I finally arrived at the conclusion that it was because I unzipped the package in a windows share using cygwin command line unzip. Turned out TOAD wasn't liking the permissions on some files. When I unzipped using windows File Explorer everything worked as expected.

Changing text color onclick

A rewrite of the answer by Sarfraz would be something like this, I think:

<script>

    document.getElementById('change').onclick = changeColor;   

    function changeColor() {
        document.body.style.color = "purple";
        return false;
    }   

</script>

You'd either have to put this script at the bottom of your page, right before the closing body tag, or put the handler assignment in a function called onload - or if you're using jQuery there's the very elegant $(document).ready(function() { ... } );

Note that when you assign event handlers this way, it takes the functionality out of your HTML. Also note you set it equal to the function name -- no (). If you did onclick = myFunc(); the function would actually execute when the handler is being set.

And I'm curious -- you knew enough to script changing the background color, but not the text color? strange:)

How to read all rows from huge table?

So it turns out that the crux of the problem is that by default, Postgres starts in "autoCommit" mode, and also it needs/uses cursors to be able to "page" through data (ex: read the first 10K results, then the next, then the next), however cursors can only exist within a transaction. So the default is to read all rows, always, into RAM, and then allow your program to start processing "the first result row, then the second" after it has all arrived, for two reasons, it's not in a transaction (so cursors don't work), and also a fetch size hasn't been set.

So how the psql command line tool achieves batched response (its FETCH_COUNT setting) for queries, is to "wrap" its select queries within a short-term transaction (if a transaction isn't yet open), so that cursors can work. You can do something like that also with JDBC:

  static void readLargeQueryInChunksJdbcWay(Connection conn, String originalQuery, int fetchCount, ConsumerWithException<ResultSet, SQLException> consumer) throws SQLException {
    boolean originalAutoCommit = conn.getAutoCommit();
    if (originalAutoCommit) {
      conn.setAutoCommit(false); // start temp transaction
    }
    try (Statement statement = conn.createStatement()) {
      statement.setFetchSize(fetchCount);
      ResultSet rs = statement.executeQuery(originalQuery);
      while (rs.next()) {
        consumer.accept(rs); // or just do you work here
      }
    } finally {
      if (originalAutoCommit) {
        conn.setAutoCommit(true); // reset it, also ends (commits) temp transaction
      }
    }
  }
  @FunctionalInterface
  public interface ConsumerWithException<T, E extends Exception> {
    void accept(T t) throws E;
  }

This gives the benefit of requiring less RAM, and, in my results, seemed to run overall faster, even if you don't need to save the RAM. Weird. It also gives the benefit that your processing of the first row "starts faster" (since it process it a page at a time).

And here's how to do it the "raw postgres cursor" way, along with full demo code, though in my experiments it seemed the JDBC way, above, was slightly faster for whatever reason.

Another option would be to have autoCommit mode off, everywhere, though you still have to always manually specify a fetchSize for each new Statement (or you can set a default fetch size in the URL string).

'sprintf': double precision in C

You need to write it like sprintf(aa, "%9.7lf", a)

Check out http://en.wikipedia.org/wiki/Printf for some more details on format codes.

How can I merge two commits into one if I already started rebase?

you can cancel the rebase with

git rebase --abort

and when you run the interactive rebase command again the 'squash; commit must be below the pick commit in the list

How to trigger the window resize event in JavaScript?

A pure JS that also works on IE (from @Manfred comment)

var evt = window.document.createEvent('UIEvents'); 
evt.initUIEvent('resize', true, false, window, 0); 
window.dispatchEvent(evt);

Or for angular:

$timeout(function() {
    var evt = $window.document.createEvent('UIEvents'); 
    evt.initUIEvent('resize', true, false, $window, 0); 
    $window.dispatchEvent(evt);
});

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

You probably have one .OBJ or .LIB file that's targeted for x64 (that's the module machine type) while you're linking for x86 (that's the target machine type).

Use DUMPBIN /HEADERS on your .OBJ files and check for the machine entry in the FILE HEADER VALUES block.

How to set opacity in parent div and not affect in child div?

As mentioned by Tom, background-color: rgba(229,229,229, 0.85) can do the trick. Place that on the style of the parent element and child wont be affected.

How can I send a file document to the printer and have it print?

This is a slightly modified solution. The Process will be killed when it was idle for at least 1 second. Maybe you should add a timeof of X seconds and call the function from a separate thread.

private void SendToPrinter()
{
  ProcessStartInfo info = new ProcessStartInfo();
  info.Verb = "print";
  info.FileName = @"c:\output.pdf";
  info.CreateNoWindow = true;
  info.WindowStyle = ProcessWindowStyle.Hidden;

  Process p = new Process();
  p.StartInfo = info;
  p.Start();

  long ticks = -1;
  while (ticks != p.TotalProcessorTime.Ticks)
  {
    ticks = p.TotalProcessorTime.Ticks;
    Thread.Sleep(1000);
  }

  if (false == p.CloseMainWindow())
    p.Kill();
}

How to set image to UIImage

Just Follow This

UIImageView *imgview = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)];
[imgview setImage:[UIImage imageNamed:@"YourImageName"]];
[imgview setContentMode:UIViewContentModeScaleAspectFit];
[self.view addSubview:imgview];

"sed" command in bash

It reads Hello World (cat), replaces all (g) occurrences of % by $ and (over)writes it to /etc/init.d/dropbox as root.

Check if string contains only whitespace

I used following:

if str and not str.isspace():
  print('not null and not empty nor whitespace')
else:
  print('null or empty or whitespace')

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

I'm currently using this approach and it works like a charm. The trick is we get keyboard height from different methods on 21 above and below and then use it as the bottom padding of our root view in our activity. I assumed your layout does not need a top padding (goes below status bar) but in case you do, inform me to update my answer.

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RelativeLayout mainLayout = findViewById(R.id.main_layout);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ViewCompat.setOnApplyWindowInsetsListener(mainLayout , new OnApplyWindowInsetsListener() {
                @Override
                public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                    v.setPadding(0, 0, 0, insets.getSystemWindowInsetBottom());
                    return insets;
                }
            });
        } else {
            View decorView = getWindow().getDecorView();
            final View contentView = mainLayout;
            decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    Rect r = new Rect();
                    //r will be populated with the coordinates of your view that area still visible.
                    decorView.getWindowVisibleDisplayFrame(r);

                    //get screen height and calculate the difference with the useable area from the r
                    int height = decorView.getContext().getResources().getDisplayMetrics().heightPixels;
                    int diff = height - r.bottom;

                    //if it could be a keyboard add the padding to the view
                    if (diff != 0) {
                        // if the use-able screen height differs from the total screen height we assume that it shows a keyboard now
                        //check if the padding is 0 (if yes set the padding for the keyboard)
                        if (contentView.getPaddingBottom() != diff) {
                            //set the padding of the contentView for the keyboard
                            contentView.setPadding(0, 0, 0, diff);
                        }
                    } else {
                        //check if the padding is != 0 (if yes reset the padding)
                        if (contentView.getPaddingBottom() != 0) {
                            //reset the padding of the contentView
                            contentView.setPadding(0, 0, 0, 0);
                        }
                    }
                }
            });
        }
    }
...
}

Don't forget to address your root view with an id:

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

Hope it helps someone.

Executing command line programs from within python

If you're concerned about server performance then look at capping the number of running sox processes. If the cap has been hit you can always cache the request and inform the user when it's finished in whichever way suits your application.

Alternatively, have the n worker scripts on other machines that pull requests from the db and call sox, and then push the resulting output file to where it needs to be.

JS strings "+" vs concat method

MDN has the following to say about string.concat():

It is strongly recommended to use the string concatenation operators (+, +=) instead of this method for perfomance reasons

Also see the link by @Bergi.

What is secret key for JWT based authentication and how to generate it?

The algorithm (HS256) used to sign the JWT means that the secret is a symmetric key that is known by both the sender and the receiver. It is negotiated and distributed out of band. Hence, if you're the intended recipient of the token, the sender should have provided you with the secret out of band.

If you're the sender, you can use an arbitrary string of bytes as the secret, it can be generated or purposely chosen. You have to make sure that you provide the secret to the intended recipient out of band.

For the record, the 3 elements in the JWT are not base64-encoded but base64url-encoded, which is a variant of base64 encoding that results in a URL-safe value.

How do I set the selected item in a drop down box

You can use this method if you use a MySQL database:

include('sql_connect.php');
$result = mysql_query("SELECT * FROM users WHERE `id`!='".$user_id."'");
while ($row = mysql_fetch_array($result))
{
    if ($_GET['to'] == $row['id'])
    {
        $selected = 'selected="selected"';
    }
    else
    {
    $selected = '';
    }
    echo('<option value="'.$row['id'].' '.$selected.'">'.$row['username'].' ('.$row['fname'].' '.substr($row['lname'],0,1).'.)</option>');
}
mysql_close($con);

It will compare if the user in $_GET['to'] is the same as $row['id'] in table, if yes, the $selected will be created. This was for a private messaging system...

How do I bind a List<CustomObject> to a WPF DataGrid?

You dont need to give column names manually in xaml. Just set AutoGenerateColumns property to true and your list will be automatically binded to DataGrid. refer code. XAML Code:

<Grid>
    <DataGrid x:Name="MyDatagrid" AutoGenerateColumns="True" Height="447" HorizontalAlignment="Left" Margin="20,85,0,0" VerticalAlignment="Top" Width="799"  ItemsSource="{Binding Path=ListTest, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  CanUserAddRows="False"> </Grid>

C#

Public Class Test 
{
    public string m_field1_Test{get;set;}
    public string m_field2_Test { get; set; }
    public Test()
    {
        m_field1_Test = "field1";
        m_field2_Test = "field2";
    }
    public MainWindow()
    {

        listTest = new List<Test>();

        for (int i = 0; i < 10; i++)
        {
            obj = new Test();
            listTest.Add(obj);

        }

        this.MyDatagrid.ItemsSource = ListTest;

        InitializeComponent();

    }

SQL select * from column where year = 2010

If i understand that you want all rows in the year 2010, then:

select * 
  from mytable 
 where Columnx >= '2010-01-01 00:00:00' 
       and Columnx < '2011-01-01 00:00:00'

Get top first record from duplicate records having no unique identity

YOur best bet is to fix the datbase design and add the identioty column to the table. Why do you havea table without one in the first place? Especially one with duplicate records! Clearly the database itself needs redesigning.

And why do you have to have this in a view, why isn't your solution with the temp table a valid solution? Views are not usually a really good thing to do to a perfectly nice database.

OnItemCLickListener not working in listview

For my lists, my rows have other things that can be clicked, like buttons, so doing a blanket blocksDescendants doesn't work. Instead I add a line in the button's xml:

    android:focusable="false"

That keeps the buttons from blocking the clicks on the rows, but still lets the buttons take the clicks, too.