Programs & Examples On #Pyisapie

CFLAGS vs CPPFLAGS

The CPPFLAGS macro is the one to use to specify #include directories.

Both CPPFLAGS and CFLAGS work in your case because the make(1) rule combines both preprocessing and compiling in one command (so both macros are used in the command).

You don't need to specify . as an include-directory if you use the form #include "...". You also don't need to specify the standard compiler include directory. You do need to specify all other include-directories.

How to create and handle composite primary key in JPA

The MyKey class must implement Serializable if you are using @IdClass

How to convert string to datetime format in pandas python?

Approach: 1

Given original string format: 2019/03/04 00:08:48

you can use

updated_df = df['timestamp'].astype('datetime64[ns]')

The result will be in this datetime format: 2019-03-04 00:08:48

Approach: 2

updated_df = df.astype({'timestamp':'datetime64[ns]'})

What is The Rule of Three?

The law of the big three is as specified above.

An easy example, in plain English, of the kind of problem it solves:

Non default destructor

You allocated memory in your constructor and so you need to write a destructor to delete it. Otherwise you will cause a memory leak.

You might think that this is job done.

The problem will be, if a copy is made of your object, then the copy will point to the same memory as the original object.

Once, one of these deletes the memory in its destructor, the other will have a pointer to invalid memory (this is called a dangling pointer) when it tries to use it things are going to get hairy.

Therefore, you write a copy constructor so that it allocates new objects their own pieces of memory to destroy.

Assignment operator and copy constructor

You allocated memory in your constructor to a member pointer of your class. When you copy an object of this class the default assignment operator and copy constructor will copy the value of this member pointer to the new object.

This means that the new object and the old object will be pointing at the same piece of memory so when you change it in one object it will be changed for the other objerct too. If one object deletes this memory the other will carry on trying to use it - eek.

To resolve this you write your own version of the copy constructor and assignment operator. Your versions allocate separate memory to the new objects and copy across the values that the first pointer is pointing to rather than its address.

What is time_t ultimately a typedef to?

The answer is definitely implementation-specific. To find out definitively for your platform/compiler, just add this output somewhere in your code:

printf ("sizeof time_t is: %d\n", sizeof(time_t));

If the answer is 4 (32 bits) and your data is meant to go beyond 2038, then you have 25 years to migrate your code.

Your data will be fine if you store your data as a string, even if it's something simple like:

FILE *stream = [stream file pointer that you've opened correctly];
fprintf (stream, "%d\n", (int)time_t);

Then just read it back the same way (fread, fscanf, etc. into an int), and you have your epoch offset time. A similar workaround exists in .Net. I pass 64-bit epoch numbers between Win and Linux systems with no problem (over a communications channel). That brings up byte-ordering issues, but that's another subject.

To answer paxdiablo's query, I'd say that it printed "19100" because the program was written this way (and I admit I did this myself in the '80's):

time_t now;
struct tm local_date_time;
now = time(NULL);
// convert, then copy internal object to our object
memcpy (&local_date_time, localtime(&now), sizeof(local_date_time));
printf ("Year is: 19%02d\n", local_date_time.tm_year);

The printf statement prints the fixed string "Year is: 19" followed by a zero-padded string with the "years since 1900" (definition of tm->tm_year). In 2000, that value is 100, obviously. "%02d" pads with two zeros but does not truncate if longer than two digits.

The correct way is (change to last line only):

printf ("Year is: %d\n", local_date_time.tm_year + 1900);

New question: What's the rationale for that thinking?

SQL Server insert if not exists best practice

The answers above which talk about normalizing are great! But what if you find yourself in a position like me where you're not allowed to touch the database schema or structure as it stands? Eg, the DBA's are 'gods' and all suggested revisions go to /dev/null?

In that respect, I feel like this has been answered with this Stack Overflow posting too in regards to all the users above giving code samples.

I'm reposting the code from INSERT VALUES WHERE NOT EXISTS which helped me the most since I can't alter any underlying database tables:

INSERT INTO #table1 (Id, guidd, TimeAdded, ExtraData)
SELECT Id, guidd, TimeAdded, ExtraData
FROM #table2
WHERE NOT EXISTS (Select Id, guidd From #table1 WHERE #table1.id = #table2.id)
-----------------------------------
MERGE #table1 as [Target]
USING  (select Id, guidd, TimeAdded, ExtraData from #table2) as [Source]
(id, guidd, TimeAdded, ExtraData)
    on [Target].id =[Source].id
WHEN NOT MATCHED THEN
    INSERT (id, guidd, TimeAdded, ExtraData)
    VALUES ([Source].id, [Source].guidd, [Source].TimeAdded, [Source].ExtraData);
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT id, guidd, TimeAdded, ExtraData from #table2
EXCEPT
SELECT id, guidd, TimeAdded, ExtraData from #table1
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT #table2.id, #table2.guidd, #table2.TimeAdded, #table2.ExtraData
FROM #table2
LEFT JOIN #table1 on #table1.id = #table2.id
WHERE #table1.id is null

The above code uses different fields than what you have, but you get the general gist with the various techniques.

Note that as per the original answer on Stack Overflow, this code was copied from here.

Anyway my point is "best practice" often comes down to what you can and can't do as well as theory.

  • If you're able to normalize and generate indexes/keys -- great!
  • If not and you have the resort to code hacks like me, hopefully the above helps.

Good luck!

Prevent typing non-numeric in input type number

Try it:

document.querySelector("input").addEventListener("keyup", function () {
   this.value = this.value.replace(/\D/, "")
});

Broadcast receiver for checking internet connection in android app

Answer to your first question: Your broadcast receiver is being called two times because

You have added two <intent-filter>

  1. Change in network connection :
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />

  2. Change in WiFi state:
    <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />

Just use one:
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />.

It will respond to only one action instead of two. See here for more information.

Answer to your second question (you want receiver to call only one time if internet connection available):

Your code is perfect; you notify only when internet is available.

UPDATE

You can use this method to check your connectivity if you want just to check whether mobile is connected with the internet or not.

public boolean isOnline(Context context) {

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    //should check null because in airplane mode it will be null
    return (netInfo != null && netInfo.isConnected());
}

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

You may want to close open projects in your Project Explorer. You can do this by right-clicking an open project, and selecting "Close Project".

This is what worked for me after I noticed that I had to periodically increase the heap size in my_directory\eclipse\eclipse.ini.

Hope this helps! Peace!

Java Compare Two List's object values?

It's been about 5 years since then and luckily we have Kotlin now.
Comparing of two lists now looks is as simple as:

fun areListsEqual(list1 : List<Any>, list2 : List<Any>) : Boolean {
        return list1 == list2
}

Or just feel free to omit it at all and use equality operator.

vertical align middle in <div>

Use the translateY CSS property to vertically center your text in it's container

<style>
.centertext{

    position: relative;
    top: 50%;
    transform: translateY(40%);

}
</style>

And then apply it to your containing DIV

  <div class="centertext">
        <font style="color:white; font-size:20px;">   Your Text Here </font>
  </div>

Adjust the translateY percentage to suit your needs. Hope this helps

Ansible - Save registered variable to file

Thanks to tmoschou for adding this comment to an outdated accepted answer:

As of Ansible 2.10, The documentation for ansible.builtin.copy says: 

If you need variable interpolation in copied files, use the
ansible.builtin.template module. Using a variable in the content field will
result in unpredictable output.

For more details see this and an explanation


Original answer:

You can use the copy module, with the parameter content=.

I gave the exact same answer here: Write variable to a file in Ansible

In your case, it looks like you want this variable written to a local logfile, so you could combine it with the local_action notation:

- local_action: copy content={{ foo_result }} dest=/path/to/destination/file

How to show full height background image?

You can do it with the code you have, you just need to ensure that html and body are set to 100% height.

Demo: http://jsfiddle.net/kevinPHPkevin/a7eGN/

html, body {
    height:100%;
} 

body {
    background-color: white;
    background-image: url('http://www.canvaz.com/portrait/charcoal-1.jpg');
    background-size: auto 100%;
    background-repeat: no-repeat;
    background-position: left top;
}

PySpark: withColumn() with two conditions and three outcomes

You'll want to use a udf as below

from pyspark.sql.types import IntegerType
from pyspark.sql.functions import udf

def func(fruit1, fruit2):
    if fruit1 == None or fruit2 == None:
        return 3
    if fruit1 == fruit2:
        return 1
    return 0

func_udf = udf(func, IntegerType())
df = df.withColumn('new_column',func_udf(df['fruit1'], df['fruit2']))

How to parse a CSV in a Bash script?

Using awk:

export INDEX=2
export VALUE=bar

awk -F, '$'$INDEX' ~ /^'$VALUE'$/ {print}' inputfile.csv

Edit: As per Dennis Williamson's excellent comment, this could be much more cleanly (and safely) written by defining awk variables using the -v switch:

awk -F, -v index=$INDEX -v value=$VALUE '$index == value {print}' inputfile.csv

Jeez...with variables, and everything, awk is almost a real programming language...

belongs_to through associations

It sounds like what you want is a User who has many Questions.
The Question has many Answers, one of which is the User's Choice.

Is this what you are after?

I would model something like that along these lines:

class User
  has_many :questions
end

class Question
  belongs_to :user
  has_many   :answers
  has_one    :choice, :class_name => "Answer"

  validates_inclusion_of :choice, :in => lambda { answers }
end

class Answer
  belongs_to :question
end

How to split (chunk) a Ruby array into parts of X elements?

Take a look at Enumerable#each_slice:

foo.each_slice(3).to_a
#=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]

Artisan, creating tables in database

In order to give a value in the table, we need to give a command:

php artisan make:migration create_users_table

and after then this command line

php artisan migrate

......

Plotting a 2D heatmap with Matplotlib

The imshow() function with parameters interpolation='nearest' and cmap='hot' should do what you want.

import matplotlib.pyplot as plt
import numpy as np

a = np.random.random((16, 16))
plt.imshow(a, cmap='hot', interpolation='nearest')
plt.show()

enter image description here

Combine hover and click functions (jQuery)?

i think best approach is to make a common method and call in hover and click events.

Setting CSS pseudo-class rules from JavaScript

As already stated this is not something that browsers support.

If you aren't coming up with the styles dynamically (i.e. pulling them out of a database or something) you should be able to work around this by adding a class to the body of the page.

The css would look something like:

a:hover { background: red; }
.theme1 a:hover { background: blue; }

And the javascript to change this would be something like:

// Look up some good add/remove className code if you want to do this
// This is really simplified

document.body.className += " theme1";  

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

Step 1: Create a static class

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

Step2: Use this class to get both start and end day of the week

 DateTime dt =TIMEE.StartOfWeek(DateTime.Now ,DayOfWeek.Monday);
        DateTime dt1 = TIMEE.EndOfWeek(DateTime.Now, DayOfWeek.Sunday);

How to get the latest tag name in current branch in Git?

To get the most recent tag, you can do:

$ git for-each-ref refs/tags --sort=-taggerdate --format='%(refname)' --count=1

Of course, you can change the count argument or the sort field as desired. It appears that you may have meant to ask a slightly different question, but this does answer the question as I interpret it.

Attempted to read or write protected memory

In my case I had trouble with the "Environment variables" while adding reference to my COM DLL.

When I added the reference to my project, I was looking for P:\Core path, whereas I had added the c:\core path in past into path environment varaible.

So my code was attempting wrong path first. I removed that and un-registered the DLL reference and re-registered my DLL reference using (regsvr32). Hope this helps.

Set folder for classpath

Use the command as

java -classpath ".;C:\MyLibs\a\*;D:\MyLibs\b\*" <your-class-name>

The above command will set the mentioned paths to classpath only once for executing the class named TestClass.

If you want to execute more then one classes, then you can follow this

set classpath=".;C:\MyLibs\a\*;D:\MyLibs\b\*"

After this you can execute as many classes as you want just by simply typing

java <your-class-name>

The above command will work till you close the command prompt. But after closing the command prompt, if you will reopen the command prompt and try to execute some classes, then you have to again set the classpath with the help of any of the above two mentioned methods.(First method for executing one class and second one for executing more classes)

If you want to set the classpth only once so that it could work for everytime, then do as follows

1. Right click on "My Computer" icon
2. Go to the "properties"
3. Go to the "Advanced System Settings" or "Advance Settings"
4. Go to the "Environment Variable"
5. Create a new variable at the user variable by giving the information as below
    a.  Variable Name-     classpath
    b.  Variable Value-    .;C:\program files\jdk 1.6.0\bin;C:\MyLibs\a\';C:\MyLibs\b\*
6.Apply this and you are done.

Remember this will work every time. You don't need to explicitly set the classpath again and again.

NOTE: If you want to add some other libs after some day, then don't forget to add a semi-colon at the end of the "variable-value" of the "Environment Variable" and then type the path of your new libs after the semi-colon. Because semi-colon separates the paths of different directories.

Hope this will help you.

AddRange to a Collection

Since .NET4.5 if you want one-liner you can use System.Collections.Generic ForEach.

source.ForEach(o => destination.Add(o));

or even shorter as

source.ForEach(destination.Add);

Performance-wise it's the same as for each loop (syntactic sugar).

Also don't try assigning it like

var x = source.ForEach(destination.Add) 

cause ForEach is void.

Edit: Copied from comments, Lipert's opinion on ForEach

How to return images in flask response?

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

Vagrant stuck connection timeout retrying

I had the same issue when I was using x64 box(chef/ubuntu-14.04).

I changed to x32 and it worked(hashicorp/precise32).

How to kill an application with all its activities?

When you use the finish() method, it does not close the process completely , it is STILL working in background.

Please use this code in Main Activity (Please don't use in every activities or sub Activities):

@Override
public void onBackPressed() {

    android.os.Process.killProcess(android.os.Process.myPid());
    // This above line close correctly
}

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

import re
pattern = re.compile("<(\d{4,5})>")

for i, line in enumerate(open('test.txt')):
    for match in re.finditer(pattern, line):
        print 'Found on line %s: %s' % (i+1, match.group())

A couple of notes about the regex:

  • You don't need the ? at the end and the outer (...) if you don't want to match the number with the angle brackets, but only want the number itself
  • It matches either 4 or 5 digits between the angle brackets

Update: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.

More about regex in python can be found here : Regular Expression HOWTO

JTable won't show column headers

As said in previous answers the 'normal' way is to add it to a JScrollPane, but sometimes you don't want it to scroll (don't ask me when:)). Then you can add the TableHeader yourself. Like this:

JPanel tablePanel = new JPanel(new BorderLayout());
JTable table = new JTable();
tablePanel.add(table, BorderLayout.CENTER);
tablePanel.add(table.getTableHeader(), BorderLayout.NORTH);

Handling InterruptedException in Java

What is the difference between the following ways of handling InterruptedException? What is the best way to do it?

You've probably come to ask this question because you've called a method that throws InterruptedException.

First of all, you should see throws InterruptedException for what it is: A part of the method signature and a possible outcome of calling the method you're calling. So start by embracing the fact that an InterruptedException is a perfectly valid result of the method call.

Now, if the method you're calling throws such exception, what should your method do? You can figure out the answer by thinking about the following:

Does it make sense for the method you are implementing to throw an InterruptedException? Put differently, is an InterruptedException a sensible outcome when calling your method?

  • If yes, then throws InterruptedException should be part of your method signature, and you should let the exception propagate (i.e. don't catch it at all).

    Example: Your method waits for a value from the network to finish the computation and return a result. If the blocking network call throws an InterruptedException your method can not finish computation in a normal way. You let the InterruptedException propagate.

    int computeSum(Server server) throws InterruptedException {
        // Any InterruptedException thrown below is propagated
        int a = server.getValueA();
        int b = server.getValueB();
        return a + b;
    }
    
  • If no, then you should not declare your method with throws InterruptedException and you should (must!) catch the exception. Now two things are important to keep in mind in this situation:

    1. Someone interrupted your thread. That someone is probably eager to cancel the operation, terminate the program gracefully, or whatever. You should be polite to that someone and return from your method without further ado.

    2. Even though your method can manage to produce a sensible return value in case of an InterruptedException the fact that the thread has been interrupted may still be of importance. In particular, the code that calls your method may be interested in whether an interruption occurred during execution of your method. You should therefore log the fact an interruption took place by setting the interrupted flag: Thread.currentThread().interrupt()

    Example: The user has asked to print a sum of two values. Printing "Failed to compute sum" is acceptable if the sum can't be computed (and much better than letting the program crash with a stack trace due to an InterruptedException). In other words, it does not make sense to declare this method with throws InterruptedException.

    void printSum(Server server) {
         try {
             int sum = computeSum(server);
             System.out.println("Sum: " + sum);
         } catch (InterruptedException e) {
             Thread.currentThread().interrupt();  // set interrupt flag
             System.out.println("Failed to compute sum");
         }
    }
    

By now it should be clear that just doing throw new RuntimeException(e) is a bad idea. It isn't very polite to the caller. You could invent a new runtime exception but the root cause (someone wants the thread to stop execution) might get lost.

Other examples:

Implementing Runnable: As you may have discovered, the signature of Runnable.run does not allow for rethrowing InterruptedExceptions. Well, you signed up on implementing Runnable, which means that you signed up to deal with possible InterruptedExceptions. Either choose a different interface, such as Callable, or follow the second approach above.

 

Calling Thread.sleep: You're attempting to read a file and the spec says you should try 10 times with 1 second in between. You call Thread.sleep(1000). So, you need to deal with InterruptedException. For a method such as tryToReadFile it makes perfect sense to say, "If I'm interrupted, I can't complete my action of trying to read the file". In other words, it makes perfect sense for the method to throw InterruptedExceptions.

String tryToReadFile(File f) throws InterruptedException {
    for (int i = 0; i < 10; i++) {
        if (f.exists())
            return readFile(f);
        Thread.sleep(1000);
    }
    return null;
}

This post has been rewritten as an article here.

Reload content in modal (twitter bootstrap)

To unload the data when the modal is closed you can use this with Bootstrap 2.x:

$('#myModal').on('hidden', function() {
    $(this).removeData('modal');
});

And in Bootstrap 3 (https://github.com/twbs/bootstrap/pull/7935#issuecomment-18513516):

$(document.body).on('hidden.bs.modal', function () {
    $('#myModal').removeData('bs.modal')
});

//Edit SL: more universal
$(document).on('hidden.bs.modal', function (e) {
    $(e.target).removeData('bs.modal');
});

What is System, out, println in System.out.println() in Java

The first answer you posted (System is a built-in class...) is pretty spot on.

You can add that the System class contains large portions which are native and that is set up by the JVM during startup, like connecting the System.out printstream to the native output stream associated with the "standard out" (console).

Android: Share plain text using intent (to all messaging apps)

New way of doing this would be using ShareCompat.IntentBuilder like so:

// Create and fire off our Intent in one fell swoop
ShareCompat.IntentBuilder
        // getActivity() or activity field if within Fragment
        .from(this) 
        // The text that will be shared
        .setText(textToShare)
        // most general text sharing MIME type
        .setType("text/plain") 
        .setStream(uriToContentThatMatchesTheArgumentOfSetType)
        /*
         * [OPTIONAL] Designate a URI to share. Your type that 
         * is set above will have to match the type of data
         * that your designating with this URI. Not sure
         * exactly what happens if you don't do that, but 
         * let's not find out.
         * 
         * For example, to share an image, you'd do the following:
         *     File imageFile = ...;
         *     Uri uriToImage = ...; // Convert the File to URI
         *     Intent shareImage = ShareCompat.IntentBuilder.from(activity)
         *       .setType("image/png")
         *       .setStream(uriToImage)
         *       .getIntent();
         */
        .setEmailTo(arrayOfStringEmailAddresses)
        .setEmailTo(singleStringEmailAddress)
        /*
         * [OPTIONAL] Designate the email recipients as an array
         * of Strings or a single String
         */ 
        .setEmailTo(arrayOfStringEmailAddresses)
        .setEmailTo(singleStringEmailAddress)
        /*
         * [OPTIONAL] Designate the email addresses that will be 
         * BCC'd on an email as an array of Strings or a single String
         */ 
        .addEmailBcc(arrayOfStringEmailAddresses)
        .addEmailBcc(singleStringEmailAddress)
        /* 
         * The title of the chooser that the system will show
         * to allow the user to select an app
         */
        .setChooserTitle(yourChooserTitle)
        .startChooser();

If you have any more questions about using ShareCompat, I highly recommend this great article from Ian Lake, an Android Developer Advocate at Google, for a more complete breakdown of the API. As you'll notice, I borrowed some of this example from that article.

If that article doesn't answer all of your questions, there is always the Javadoc itself for ShareCompat.IntentBuilder on the Android Developers website. I added more to this example of the API's usage on the basis of clemantiano's comment.

Location of sqlite database on the device

well this might be late but it will help. You can access the database without rooting your device through adb

start the adb using cmd and type the following commands

-run-as com.your.package  
-shell@android:/data/data/com.your.package $ ls  
cache  
databases  
lib  
shared_prefs  

Now you can open from here on.

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

Prior to standardization there was ioctl(...FIONBIO...) and fcntl(...O_NDELAY...), but these behaved inconsistently between systems, and even within the same system. For example, it was common for FIONBIO to work on sockets and O_NDELAY to work on ttys, with a lot of inconsistency for things like pipes, fifos, and devices. And if you didn't know what kind of file descriptor you had, you'd have to set both to be sure. But in addition, a non-blocking read with no data available was also indicated inconsistently; depending on the OS and the type of file descriptor the read may return 0, or -1 with errno EAGAIN, or -1 with errno EWOULDBLOCK. Even today, setting FIONBIO or O_NDELAY on Solaris causes a read with no data to return 0 on a tty or pipe, or -1 with errno EAGAIN on a socket. However 0 is ambiguous since it is also returned for EOF.

POSIX addressed this with the introduction of O_NONBLOCK, which has standardized behavior across different systems and file descriptor types. Because existing systems usually want to avoid any changes to behavior which might break backward compatibility, POSIX defined a new flag rather than mandating specific behavior for one of the others. Some systems like Linux treat all 3 the same, and also define EAGAIN and EWOULDBLOCK to the same value, but systems wishing to maintain some other legacy behavior for backward compatibility can do so when the older mechanisms are used.

New programs should use fcntl(...O_NONBLOCK...), as standardized by POSIX.

How to get dictionary values as a generic list

Going further on the answer of Slaks, if one or more lists in your dictionary is null, a System.NullReferenceException will be thrown when calling ToList(), play safe:

List<MyType> allItems = myDico.Values.Where(x => x != null).SelectMany(x => x).ToList();

Setting session variable using javascript

You could better use the localStorage of the web browser.

You can find a reference here

Deleting elements from std::set while iterating

This behaviour is implementation specific. To guarantee the correctness of the iterator you should use "it = numbers.erase(it);" statement if you need to delete the element and simply incerement iterator in other case.

Difference between os.getenv and os.environ.get

See this related thread. Basically, os.environ is found on import, and os.getenv is a wrapper to os.environ.get, at least in CPython.

EDIT: To respond to a comment, in CPython, os.getenv is basically a shortcut to os.environ.get ; since os.environ is loaded at import of os, and only then, the same holds for os.getenv.

Clear text in EditText when entered

i don't know what mistakes i did while implementing the above solutions, bt they were unsuccessful for me

txtDeck.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override       
    public void onFocusChange(View v, boolean hasFocus) {
        txtDeck.setText("");
    }
});

This works for me,

Process all arguments except the first one (in a bash script)

Came across this looking for something else. While the post looks fairly old, the easiest solution in bash is illustrated below (at least bash 4) using set -- "${@:#}" where # is the starting number of the array element we want to preserve forward:

    #!/bin/bash

    someVar="${1}"
    someOtherVar="${2}"
    set -- "${@:3}"
    input=${@}

    [[ "${input[*],,}" == *"someword"* ]] && someNewVar="trigger"

    echo -e "${someVar}\n${someOtherVar}\n${someNewVar}\n\n${@}"

Basically, the set -- "${@:3}" just pops off the first two elements in the array like perl's shift and preserves all remaining elements including the third. I suspect there's a way to pop off the last elements as well.

python: after installing anaconda, how to import pandas

You should first create a new environment in conda. From the terminal, type:

$ conda create --name my_env pandas ipython

Python will be installed automatically as part of this installation. After selecting [y] to confirm, you now need to activate this environment:

$ source activate my_env

On Windows I believe it is just:

$ activate my_env

Now, confirm installed packages:

$ conda list

Finally, start python and run your session.

$ ipython

What's the difference between xsd:include and xsd:import?

The fundamental difference between include and import is that you must use import to refer to declarations or definitions that are in a different target namespace and you must use include to refer to declarations or definitions that are (or will be) in the same target namespace.

Source: https://web.archive.org/web/20070804031046/http://xsd.stylusstudio.com/2002Jun/post08016.htm

Prevent any form of page refresh using jQuery/Javascript

Issue #2 now can be solved using BroadcastAPI.

At the moment it's only available in Chrome, Firefox, and Opera.

var bc = new BroadcastChannel('test_channel');

bc.onmessage = function (ev) { 
    if(ev.data && ev.data.url===window.location.href){
       alert('You cannot open the same page in 2 tabs');
    }
}

bc.postMessage(window.location.href);

Is there a way to add a gif to a Markdown file?

  1. have gif file.
  2. push gif file to your github repo
  3. click on that file on the github repo to get github address of the gif
  4. in your README file: ![alt-text](link)

example below: ![grab-landing-page](https://github.com/winnie1312/grab/blob/master/grab-landingpage-winnie.gif)

How can I change the Bootstrap default font family using font from Google?

This is the best and easy way to import font from google and
this is also a standard method to import font

Paste this code on your index page or on header

<link href='http://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'>

other method is to import on css like this:

@import url(http://fonts.googleapis.com/css?family=Oswald:400,300,700);

on your Css file as this code

body {
  font-family: 'Oswald', sans-serif !important;
}

Note : The @import code line will be the first lines in your css file (style.css, etc.css). They can be used in any of the .css files and should always be the first line in these files. The following is an example:

pandas dataframe groupby datetime month

(update: 2018)

Note that pd.Timegrouper is depreciated and will be removed. Use instead:

 df.groupby(pd.Grouper(freq='M'))

<> And Not In VB.NET

Is is not the same as = -- Is compares the references, whilst = will compare the values.

If you're using v2 of the .Net Framework (or later), there is the IsNot operator which will do the right thing, and read more naturally.

Simulate a specific CURL in PostMan

As per the above answers, it works well.

If we paste curl requests with Authorization data in import, Postman will set all headers automatically. We only just pass row JSON data in the request body if needed or Upload images through form-data in the body.

This is just an example. Your API should be a different one (if your API allows)

curl -X POST 'https://verifyUser.abc.com/api/v1/verification' \
    -H 'secret: secret' \
    -H 'email: [email protected]' \
    -H 'accept: application/json, text/plain, */*' \
    -H 'authorizationtoken: bearer' \
    -F 'referenceFilePath= Add file path' \
    --compressed

How To Add An "a href" Link To A "div"?

I'd say:

 <a href="#"id="buttonOne">
            <div id="linkedinB">
                <img src="img/linkedinB.png" width="40" height="40">
            </div>
      </div> 

However, it will still be a link. If you want to change your link into a button, you should rename the #buttonone to #buttonone a { your css here }.

How to tell PowerShell to wait for each command to end before starting the next?

Taking it further you could even parse on the fly

e.g.

& "my.exe" | %{
    if ($_ -match 'OK')
    { Write-Host $_ -f Green }
    else if ($_ -match 'FAIL|ERROR')
    { Write-Host $_ -f Red }
    else 
    { Write-Host $_ }
}

How to iterate over a column vector in Matlab?

In Matlab, you can iterate over the elements in the list directly. This can be useful if you don't need to know which element you're currently working on.

Thus you can write

for elm = list
%# do something with the element
end

Note that Matlab iterates through the columns of list, so if list is a nx1 vector, you may want to transpose it.

Plotting a python dict in order of key values

Simply pass the sorted items from the dictionary to the plot() function. concentration.items() returns a list of tuples where each tuple contains a key from the dictionary and its corresponding value.

You can take advantage of list unpacking (with *) to pass the sorted data directly to zip, and then again to pass it into plot():

import matplotlib.pyplot as plt

concentration = {
    0: 0.19849878712984576,
    5000: 0.093917341754771386,
    10000: 0.075060643507712022,
    20000: 0.06673074282575861,
    30000: 0.057119318961966224,
    50000: 0.046134834546203485,
    100000: 0.032495766396631424,
    200000: 0.018536317451599615,
    500000: 0.0059499290585381479}

plt.plot(*zip(*sorted(concentration.items())))
plt.show()

sorted() sorts tuples in the order of the tuple's items so you don't need to specify a key function because the tuples returned by dict.item() already begin with the key value.

Node.js/Express routing with get params

Your route isn't ok, it should be like this (with ':')

app.get('/documents/:format/:type', function (req, res) {
   var format = req.params.format,
       type = req.params.type;
});

Also you cannot interchange parameter order unfortunately. For more information on req.params (and req.query) check out the api reference here.

How can I join elements of an array in Bash?

If you build the array in a loop, here is a simple way:

arr=()
for x in $(some_cmd); do
   arr+=($x,)
done
arr[-1]=${arr[-1]%,}
echo ${arr[*]}

Insert into ... values ( SELECT ... FROM ... )

Two approaches for insert into with select sub-query.

  1. With SELECT subquery returning results with One row.
  2. With SELECT subquery returning results with Multiple rows.

1. Approach for With SELECT subquery returning results with one row.

INSERT INTO <table_name> (<field1>, <field2>, <field3>) 
VALUES ('DUMMY1', (SELECT <field> FROM <table_name> ),'DUMMY2');

In this case, it assumes SELECT Sub-query returns only one row of result based on WHERE condition or SQL aggregate functions like SUM, MAX, AVG etc. Otherwise it will throw error

2. Approach for With SELECT subquery returning results with multiple rows.

INSERT INTO <table_name> (<field1>, <field2>, <field3>) 
SELECT 'DUMMY1', <field>, 'DUMMY2' FROM <table_name>;

The second approach will work for both the cases.

How can I show a hidden div when a select option is selected?

<select id="test" name="form_select" onchange="showDiv()">
   <option value="0">No</option>
   <option value ="1">Yes</option>
</select>
<div id="hidden_div" style="display: none;">Hello hidden content</div>
<script>
    function showDiv(){
        getSelectValue = document.getElementById("test").value;
        if(getSelectValue == "1"){
            document.getElementById("hidden_div").style.display="block";
        }else{
            document.getElementById("hidden_div").style.display="none";
        }
    }
</script>

How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug?

Chrome

This can be achieved by three different approaches (see my blog article here for more details):

  • Search in Elements panel like below
  • Execute $x() and $$() in Console panel, as shown in Lawrence's answer
  • Third party extensions (not really necessary in most of the cases, could be an overkill)

Here is how you search XPath in Elements panel:

  1. Press F12 to open Chrome Developer Tool
  2. In "Elements" panel, press Ctrl+F
  3. In the search box, type in XPath or CSS Selector, if elements are found, they will be highlighted in yellow.

enter image description here

Firefox (since version 75)

Since FF 75 it's possible to use raw xpath query without evaluation xpath expressions, see documentation for more info.

Firefox (prior version 75)

  1. Either select "Web Console" from the Web Developer submenu in the Firefox Menu (or Tools menu if you display the menu bar or are on Mac OS X)
    or press the Ctrl+Shift+K (Command+Option+K on OS X) keyboard shortcut.
  2. In the command line at the bottom use the following:

    • $(): Returns the first element that matches. Equivalent to document.querySelector() or calls the $ function in the page, if it exists.

    • $$(): Returns an array of DOM nodes that match. This is like for document.querySelectorAll(), but returns an array instead of a NodeList.

    • $x(): Evaluates an XPath expression and returns an array of matching nodes.


Firefox (prior version 49)

  1. Install Firebug
  2. Install Firepath
  3. Press F12 to open Firebug
  4. Switch to FirePath panel
  5. In dropdown, select XPathor CSS
  6. Type in to locate

enter image description here

jQuery callback on image load (even when the image is cached)

You can also use this code with support for loading error:

$("img").on('load', function() {
  // do stuff on success
})
.on('error', function() {
  // do stuff on smth wrong (error 404, etc.)
})
.each(function() {
    if(this.complete) {
      $(this).load();
    } else if(this.error) {
      $(this).error();
    }
});

Dynamically create Bootstrap alerts box through JavaScript

Try this (see a working example of this code in jsfiddle: http://jsfiddle.net/periklis/7ATLS/1/)

<input type = "button" id = "clickme" value="Click me!"/>
<div id = "alert_placeholder"></div>
<script>
bootstrap_alert = function() {}
bootstrap_alert.warning = function(message) {
            $('#alert_placeholder').html('<div class="alert"><a class="close" data-dismiss="alert">×</a><span>'+message+'</span></div>')
        }

$('#clickme').on('click', function() {
            bootstrap_alert.warning('Your text goes here');
});
</script>?

EDIT: There are now libraries that simplify and streamline this process, such as bootbox.js

JavaScript implementation of Gzip

I ported an implementation of LZMA from a GWT module into standalone JavaScript. It's called LZMA-JS.

CSS technique for a horizontal line with words in the middle

h6 {
    font: 14px sans-serif;
    margin-top: 20px;
    text-align: center;
    text-transform: uppercase;
    font-weight: 900;
}

    h6.background {
        position: relative;
        z-index: 1;
        margin-top: 0%;
        width:85%;
        margin-left:6%;
    }

        h6.background span {
            background: #fff;
            padding: 0 15px;
        }

        h6.background:before {
            border-top: 2px solid #dfdfdf;
            content: "";
            margin: 0 auto; /* this centers the line to the full width specified */
            position: absolute; /* positioning must be absolute here, and relative positioning must be applied to the parent */
            top: 50%;
            left: 0;
            right: 0;
            bottom: 0;
            width: 95%;
            z-index: -1;
        }

this will help you


between line

React PropTypes : Allow different types of PropTypes for one prop

For documentation purpose, it's better to list the string values that are legal:

size: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.oneOf([ 'SMALL', 'LARGE' ]),
]),

What is an MDF file?

SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.

As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.

More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.

What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?

A readonly element is just not editable, but gets sent when the according form submits. A disabled element isn't editable and isn't sent on submit. Another difference is that readonly elements can be focused (and getting focused when "tabbing" through a form) while disabled elements can't.

Read more about this in this great article or the definition by w3c. To quote the important part:

Key Differences

The Disabled attribute

  • Values for disabled form elements are not passed to the processor method. The W3C calls this a successful element.(This works similar to form check boxes that are not checked.)
  • Some browsers may override or provide default styling for disabled form elements. (Gray out or emboss text) Internet Explorer 5.5 is particularly nasty about this.
  • Disabled form elements do not receive focus.
  • Disabled form elements are skipped in tabbing navigation.

The Read Only Attribute

  • Not all form elements have a readonly attribute. Most notable, the <SELECT> , <OPTION> , and <BUTTON> elements do not have readonly attributes (although they both have disabled attributes)
  • Browsers provide no default overridden visual feedback that the form element is read only. (This can be a problem… see below.)
  • Form elements with the readonly attribute set will get passed to the form processor.
  • Read only form elements can receive the focus
  • Read only form elements are included in tabbed navigation.

Class method decorator with self arguments?

A more concise example might be as follows:

#/usr/bin/env python3
from functools import wraps

def wrapper(method):
    @wraps(method)
    def _impl(self, *method_args, **method_kwargs):
        method_output = method(self, *method_args, **method_kwargs)
        return method_output + "!"
    return _impl

class Foo:
    @wrapper
    def bar(self, word):
        return word

f = Foo()
result = f.bar("kitty")
print(result)

Which will print:

kitty!

How do I save JSON to local text file

Node.js:

var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
    if (err) {
        console.log(err);
    }
});

Browser (webapi):

function download(content, fileName, contentType) {
    var a = document.createElement("a");
    var file = new Blob([content], {type: contentType});
    a.href = URL.createObjectURL(file);
    a.download = fileName;
    a.click();
}
download(jsonData, 'json.txt', 'text/plain');

How to show image using ImageView in Android

If you want to display an image file on the phone, you can do this:

private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageBitmap(BitmapFactory.decodeFile("pathToImageFile"));

If you want to display an image from your drawable resources, do this:

private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageResource(R.drawable.imageFileId);

You'll find the drawable folder(s) in the project res folder. You can put your image files there.

What is the official name for a credit card's 3 digit code?

It is called the Card Security Code (CSC) according to Wikipedia, but has also been known as other things, such as the Card Verification Value (CVV) or Card Verfication Code (CVC).

The second code, and the most cited, is CVV2 or CVC2. This CSC (also known as a CCID or Credit Card ID) is often asked for by merchants for them to secure "card not present" transactions occurring over the Internet, by mail, fax or over the phone. In many countries in Western Europe, due to increased attempts at card fraud, it is now mandatory to provide this code when the cardholder is not present in person.

Because this seems to be known by multiple names, and its name doesn't seem to be printed on the card itself, you'll probably (unfortunately) still need to tell your users how to find the code - ie by describing it as the "3 digit code on back of card".


2018 update

The situation has not improved, and is now worse - there are even more different names now. However, you can if you like use different terms depending on the card type:

  • "CVC2" or "Card Validation Code" – MasterCard
  • "CVV2" or "Card Verification Value 2" – Visa
  • "CSC" or "Card Security Code" – American Express

Note that some American Express and Discover cards use a 4-digit code on the front of the card. See the above linked Wikipedia article for more.

How to delete and update a record in Hive

Good news,Insert updates and deletes are now possible on Hive/Impala using Kudu.

You need to use IMPALA/kudu to maintain the tables and perform insert/update/delete records. Details with examples can be found here: insert-update-delete-on-hadoop

Please share the news if you are excited.

-MIK

How do I link to a library with Code::Blocks?

The gdi32 library is already installed on your computer, few programs will run without it. Your compiler will (if installed properly) normally come with an import library, which is what the linker uses to make a binding between your program and the file in the system. (In the unlikely case that your compiler does not come with import libraries for the system libs, you will need to download the Microsoft Windows Platform SDK.)

To link with gdi32:

enter image description here

This will reliably work with MinGW-gcc for all system libraries (it should work if you use any other compiler too, but I can't talk about things I've not tried). You can also write the library's full name, but writing libgdi32.a has no advantage over gdi32 other than being more type work.
If it does not work for some reason, you may have to provide a different name (for example the library is named gdi32.lib for MSVC).

For libraries in some odd locations or project subfolders, you will need to provide a proper pathname (click on the "..." button for a file select dialog).

Angular 2 / 4 / 5 - Set base href dynamically

Add-ons:If you want for eg: /users as application base for router and /public as base for assets use

$ ng build -prod --base-href /users --deploy-url /public

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

I would check that the file is not empty first:

import os

scores = {} # scores is an empty dict already

if os.path.getsize(target) > 0:      
    with open(target, "rb") as f:
        unpickler = pickle.Unpickler(f)
        # if file is not empty scores will be equal
        # to the value unpickled
        scores = unpickler.load()

Also open(target, 'a').close() is doing nothing in your code and you don't need to use ;.

Python assigning multiple variables to same value? list behavior

Yes, that's the expected behavior. a, b and c are all set as labels for the same list. If you want three different lists, you need to assign them individually. You can either repeat the explicit list, or use one of the numerous ways to copy a list:

b = a[:] # this does a shallow copy, which is good enough for this case
import copy
c = copy.deepcopy(a) # this does a deep copy, which matters if the list contains mutable objects

Assignment statements in Python do not copy objects - they bind the name to an object, and an object can have as many labels as you set. In your first edit, changing a[0], you're updating one element of the single list that a, b, and c all refer to. In your second, changing e, you're switching e to be a label for a different object (4 instead of 3).

pass parameter by link_to ruby on rails

Maybe try this:

<%= link_to "Add to cart", 
            :controller => "car", 
            :action => "add_to_cart", 
            :car => car.attributes %>

But I'd really like to see where the car object is getting setup for this page (i.e., the rest of the view).

How to know user has clicked "X" or the "Close" button?

I agree with the DialogResult-Solution as the more straight forward one.

In VB.NET however, typecast is required to get the CloseReason-Property

    Private Sub MyForm_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing

        Dim eCast As System.Windows.Forms.FormClosingEventArgs
        eCast = TryCast(e, System.Windows.Forms.FormClosingEventArgs)
        If eCast.CloseReason = Windows.Forms.CloseReason.None Then
            MsgBox("Button Pressed")
        Else
            MsgBox("ALT+F4 or [x] or other reason")
        End If

    End Sub

How do you add Boost libraries in CMakeLists.txt?

Try as saying Boost documentation:

set(Boost_USE_STATIC_LIBS        ON)  # only find static libs
set(Boost_USE_DEBUG_LIBS         OFF) # ignore debug libs and 
set(Boost_USE_RELEASE_LIBS       ON)  # only find release libs 
set(Boost_USE_MULTITHREADED      ON)
set(Boost_USE_STATIC_RUNTIME    OFF) 
find_package(Boost 1.66.0 COMPONENTS date_time filesystem system ...)
if(Boost_FOUND)   
    include_directories(${Boost_INCLUDE_DIRS})
    add_executable(foo foo.cc)   
    target_link_libraries(foo ${Boost_LIBRARIES})
endif()

Don't forget to replace foo to your project name and components to yours!

How can I restore the MySQL root user’s full privileges?

i also remove privileges of root and database not showing in mysql console when i was a root user, so changed user by mysql>mysql -u 'userName' -p; and password;

UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';

FLUSH PRIVILEGES;

after this command it all show database's in root .

Thanks

Unit Testing: DateTime.Now

These are all good answers, this is what I did on a different project:

Usage:

Get Today's REAL date Time

var today = SystemTime.Now().Date;

Instead of using DateTime.Now, you need to use SystemTime.Now()... It's not hard change but this solution might not be ideal for all projects.

Time Traveling (Lets go 5 years in the future)

SystemTime.SetDateTime(today.AddYears(5));

Get Our Fake "today" (will be 5 years from 'today')

var fakeToday = SystemTime.Now().Date;

Reset the date

SystemTime.ResetDateTime();

/// <summary>
/// Used for getting DateTime.Now(), time is changeable for unit testing
/// </summary>
public static class SystemTime
{
    /// <summary> Normally this is a pass-through to DateTime.Now, but it can be overridden with SetDateTime( .. ) for testing or debugging.
    /// </summary>
    public static Func<DateTime> Now = () => DateTime.Now;

    /// <summary> Set time to return when SystemTime.Now() is called.
    /// </summary>
    public static void SetDateTime(DateTime dateTimeNow)
    {
        Now = () =>  dateTimeNow;
    }

    /// <summary> Resets SystemTime.Now() to return DateTime.Now.
    /// </summary>
    public static void ResetDateTime()
    {
        Now = () => DateTime.Now;
    }
}

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

SVN change username

Go to Tortoise SVN --> Settings --> Saved Data.

There is an option to clear Authentication Data, click on the clear button, and it will allow you to select which connection you wanted to clear userid/pwd for.

After you do this, any checkout or update activity, it will reprompt for the userid and password.

Can't start Eclipse - Java was started but returned exit code=13

The solution is simple: Put the "eclipse" folder on "C:/Program Files". If it does not work, put it in "C:/Program Files (x86)".

Extract parameter value from url using regular expressions

Why dont you take the string and split it

Example on the url

var url = "http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk"

you can do a split as

var params = url.split("?")[1].split("&");

You will get array of strings with params as name value pairs with "=" as the delimiter.

Concatenating Column Values into a Comma-Separated List

SELECT LEFT(Car, LEN(Car) - 1)
FROM (
    SELECT Car + ', '
    FROM Cars
    FOR XML PATH ('')
  ) c (Car)

How to change the window title of a MATLAB plotting figure?

You need to set figure properties.

At the very beginning of the script, call

figure('name','something else')

Calling figure is a good thing, anyway, because without it, you always plot into the same window, and sometimes you may want to compare two windows side-by-side.

Alternatively, you can store the figure's handle by calling

figH = figure;

so that you can later change the figure properties to your liking (the 'numberTitle' property setting eliminates the "figure X" text)

set(figH,'Name','something else','NumberTitle','off')

Have a look at the figure properties in the MATLAB documentation to see what else you can change if you want.

How to replace comma (,) with a dot (.) using java

Just use str.replace(',', '.') - it is both fast and efficient when a single character is to be replaced. And if the comma doesn't exist, it does nothing.

How to read a file in other directory in python

You can't "open" a directory using the open function. This function is meant to be used to open files.

Here, what you want to do is open the file that's in the directory. The first thing you must do is compute this file's path. The os.path.join function will let you do that by joining parts of the path (the directory and the file name):

fpath = os.path.join(direct, "5_1.txt")

You can then open the file:

f = open(fpath)

And read its content:

content = f.read()

Additionally, I believe that on Windows, using open on a directory does return a PermissionDenied exception, although that's not really the case.

Convert Java String to sql.Timestamp

Have you tried using Timestamp.valueOf(String)? It looks like it should do almost exactly what you want - you just need to change the separator between your date and time to a space, and the ones between hours and minutes, and minutes and hours, to colons:

import java.sql.*;

public class Test {
    public static void main(String[] args) {
        String text = "2011-10-02 18:48:05.123456";
        Timestamp ts = Timestamp.valueOf(text);
        System.out.println(ts.getNanos());
    }
}

Assuming you've already validated the string length, this will convert to the right format:

static String convertSeparators(String input) {
    char[] chars = input.toCharArray();
    chars[10] = ' ';
    chars[13] = ':';
    chars[16] = ':';
    return new String(chars);
}

Alternatively, parse down to milliseconds by taking a substring and using Joda Time or SimpleDateFormat (I vastly prefer Joda Time, but your mileage may vary). Then take the remainder of the string as another string and parse it with Integer.parseInt. You can then combine the values pretty easily:

Date date = parseDateFromFirstPart();
int micros = parseJustLastThreeDigits();

Timestamp ts = new Timestamp(date.getTime());
ts.setNanos(ts.getNanos() + micros * 1000);

How to find memory leak in a C++ code/project?

There are some well-known programming techniques that will help you to minimize the risk of getting memory leaks at first hand:

  • if you have to do your own dynamic memory allocation, write new and delete always pairwise, and make sure the allocation/deallocation code is called pairwise
  • avoid dynamic memory allocation if you can. For example, use vector<T> t whereever possible instead of T* t = new T[size]
  • use "smart pointers" like boost smart pointers (http://www.boost.org/doc/libs/1_46_1/libs/smart_ptr/smart_ptr.htm)
  • my personal favorite: make sure you have understood the concept of ownership of a pointer, and make sure that everywhere where you use pointers, you know which code entity is the owner
  • learn which constructors / assignment operators are automatically created by the C++ compiler, and what that means if you have class that owns a pointer (or what that means if you have a class that contains a pointer to an object it does not own).

What is the purpose of XSD files?

An XSD is a formal contract that specifies how an XML document can be formed. It is often used to validate an XML document, or to generate code from.

Keyboard shortcuts in WPF

Although the top answers are correct, I personally like to work with attached properties to enable the solution to be applied to any UIElement, especially when the Window is not aware of the element that should be focused. In my experience I often see a composition of several view models and user controls, where the window is often nothing more that the root container.

Snippet

public sealed class AttachedProperties
{
    // Define the key gesture type converter
    [System.ComponentModel.TypeConverter(typeof(System.Windows.Input.KeyGestureConverter))]
    public static KeyGesture GetFocusShortcut(DependencyObject dependencyObject)
    {
        return (KeyGesture)dependencyObject?.GetValue(FocusShortcutProperty);
    }

    public static void SetFocusShortcut(DependencyObject dependencyObject, KeyGesture value)
    {
        dependencyObject?.SetValue(FocusShortcutProperty, value);
    }

    /// <summary>
    /// Enables window-wide focus shortcut for an <see cref="UIElement"/>.
    /// </summary>
    // Using a DependencyProperty as the backing store for FocusShortcut.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty FocusShortcutProperty =
        DependencyProperty.RegisterAttached("FocusShortcut", typeof(KeyGesture), typeof(AttachedProperties), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None, new PropertyChangedCallback(OnFocusShortcutChanged)));

    private static void OnFocusShortcutChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (!(d is UIElement element) || e.NewValue == e.OldValue)
            return;

        var window = FindParentWindow(d);
        if (window == null)
            return;

        var gesture = GetFocusShortcut(d);
        if (gesture == null)
        {
            // Remove previous added input binding.
            for (int i = 0; i < window.InputBindings.Count; i++)
            {
                if (window.InputBindings[i].Gesture == e.OldValue && window.InputBindings[i].Command is FocusElementCommand)
                    window.InputBindings.RemoveAt(i--);
            }
        }
        else
        {
            // Add new input binding with the dedicated FocusElementCommand.
            // see: https://gist.github.com/shuebner20/349d044ed5236a7f2568cb17f3ed713d
            var command = new FocusElementCommand(element);
            window.InputBindings.Add(new InputBinding(command, gesture));
        }
    }
}

With this attached property you can define a focus shortcut for any UIElement. It will automatically register the input binding at the window containing the element.

Usage (XAML)

<TextBox x:Name="SearchTextBox"
         Text={Binding Path=SearchText}
         local:AttachedProperties.FocusShortcutKey="Ctrl+Q"/>

Source code

The full sample including the FocusElementCommand implementation is available as gist: https://gist.github.com/shuebner20/c6a5191be23da549d5004ee56bcc352d

Disclaimer: You may use this code everywhere and free of charge. Please keep in mind, that this is a sample that is not suitable for heavy usage. For example, there is no garbage collection of removed elements because the Command will hold a strong reference to the element.

C# convert int to string with padding zeros?

Easy peasy

int i = 1;
i.ToString("0###")

ssh script returns 255 error

This is usually happens when the remote is down/unavailable; or the remote machine doesn't have ssh installed; or a firewall doesn't allow a connection to be established to the remote host.

ssh returns 255 when an error occurred or 255 is returned by the remote script:

 EXIT STATUS

     ssh exits with the exit status of the remote command or
     with 255 if an error occurred.

Usually you would an error message something similar to:

ssh: connect to host host.domain.com port 22: No route to host

Or

ssh: connect to host HOSTNAME port 22: Connection refused

Check-list:

  • What happens if you run the ssh command directly from the command line?

  • Are you able to ping that machine?

  • Does the remote has ssh installed?

  • If installed, then is the ssh service running?

Fit background image to div

You can use this attributes:

background-size: contain;
background-repeat: no-repeat;

and you code is then like this:

 <div style="text-align:center;background-image: url(/media/img_1_bg.jpg); background-size: contain;
background-repeat: no-repeat;" id="mainpage">

How can I set my Cygwin PATH to find javac?

Although all other answers are technically correct, I would recommend you adding the custom path to the beginning of your PATH, not at the end. That way it would be the first place to look for instead of the last:

Add to bottom of ~/.bash_profile:

export PATH="/cygdrive/C/Program Files/Java/jdk1.6.0_23/bin/":$PATH

That way if you have more than one java or javac it will use the one you provided first.

Spring Rest POST Json RequestBody Content type not supported

try to add jackson dependency

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.3</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.9.3</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.3</version>
        <exclusions>
            <exclusion>
                <artifactId>jackson-annotations</artifactId>
                <groupId>com.fasterxml.jackson.core</groupId>
            </exclusion>
        </exclusions>
    </dependency>

grep from tar.gz without extracting [faster one]

If this is really slow, I suspect you're dealing with a large archive file. It's going to uncompress it once to extract the file list, and then uncompress it N times--where N is the number of files in the archive--for the grep. In addition to all the uncompressing, it's going to have to scan a fair bit into the archive each time to extract each file. One of tar's biggest drawbacks is that there is no table of contents at the beginning. There's no efficient way to get information about all the files in the archive and only read that portion of the file. It essentially has to read all of the file up to the thing you're extracting every time; it can't just jump to a filename's location right away.

The easiest thing you can do to speed this up would be to uncompress the file first (gunzip file.tar.gz) and then work on the .tar file. That might help enough by itself. It's still going to loop through the entire archive N times, though.

If you really want this to be efficient, your only option is to completely extract everything in the archive before processing it. Since your problem is speed, I suspect this is a giant file that you don't want to extract first, but if you can, this will speed things up a lot:

tar zxf file.tar.gz
for f in hopefullySomeSubdir/*; do
  grep -l "string" $f
done

Note that grep -l prints the name of any matching file, quits after the first match, and is silent if there's no match. That alone will speed up the grepping portion of your command, so even if you don't have the space to extract the entire archive, grep -l will help. If the files are huge, it will help a lot.

Android ImageView Zoom-in and Zoom-Out

I know it is a bit late for this answer, but I hope it helps someone.

I was looking for the same thing (Zoom using pinch, and dragging image) and I found this Android Developers Blog link.

Works perfect. No artifacts or what so ever. It uses ScaleGestureDetector.

How to correctly represent a whitespace character

Using regular expressions, you can represent any whitespace character with the metacharacter "\s"

MSDN Reference

Javascript array sort and unique

// Another way, that does not rearrange the original Array 
// and spends a little less time handling duplicates.

function uniqueSort(arr, sortby){
    var A1= arr.slice();
    A1= typeof sortby== 'function'? A1.sort(sortby): A1.sort();

    var last= A1.shift(), next, A2= [last];
    while(A1.length){
        next= A1.shift();
        while(next=== last) next= A1.shift();
        if(next!=undefined){
            A2[A2.length]= next;
            last= next;
        }
    }
    return A2;
}
var myData= ['237','124','255','124','366','255','100','1000'];
uniqueSort(myData,function(a,b){return a-b})

// the ordinary sort() returns the same array as the number sort here,
// but some strings of digits do not sort so nicely numerical.

Get SSID when WIFI is connected

I found interesting solution to get SSID of currently connected Wifi AP. You simply need to use iterate WifiManager.getConfiguredNetworks() and find configuration with specific WifiInfo.getNetworkId()

My example

in Broadcast receiver with action WifiManager.NETWORK_STATE_CHANGED_ACTION I'm getting current connection state from intent

NetworkInfo nwInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
nwInfo.getState()

If NetworkInfo.getState is equal to NetworkInfo.State.CONNECTED then i can get current WifiInfo object

WifiManager wifiManager = (WifiManager) getSystemService (Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo ();

And after that

public String findSSIDForWifiInfo(WifiManager manager, WifiInfo wifiInfo) {

    List<WifiConfiguration> listOfConfigurations = manager.getConfiguredNetworks();

    for (int index = 0; index < listOfConfigurations.size(); index++) {
        WifiConfiguration configuration = listOfConfigurations.get(index);
        if (configuration.networkId == wifiInfo.getNetworkId()) {
            return configuration.SSID;
        }
    }

    return null;
}

And very important thing this method doesn't require Location nor Location Permisions

In API29 Google redesigned Wifi API so this solution is outdated for Android 10.

How to vertically center an image inside of a div element in HTML using CSS?

If you want content to be what ever you need to have inside a div, this did the job for me:

<div style="
  display: table-cell;
  vertical-align: middle;
  background-color: blue;
  width: ...px;
  height: ...px;
">
    <div style="
      margin: auto;
      display: block;
      width: fit-content;
    ">
        <!-- CONTENT -->
        <img src="...">
        <p> some text </p>
    </div>
 </div>

How to determine an interface{} value's "real" type?

You can use reflection (reflect.TypeOf()) to get the type of something, and the value it gives (Type) has a string representation (String method) that you can print.

Magento - Retrieve products with a specific attribute value

Almost all Magento Models have a corresponding Collection object that can be used to fetch multiple instances of a Model.

To instantiate a Product collection, do the following

$collection = Mage::getModel('catalog/product')->getCollection();

Products are a Magento EAV style Model, so you'll need to add on any additional attributes that you want to return.

$collection = Mage::getModel('catalog/product')->getCollection();

//fetch name and orig_price into data
$collection->addAttributeToSelect('name');  
$collection->addAttributeToSelect('orig_price');    

There's multiple syntaxes for setting filters on collections. I always use the verbose one below, but you might want to inspect the Magento source for additional ways the filtering methods can be used.

The following shows how to filter by a range of values (greater than AND less than)

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');  
$collection->addAttributeToSelect('orig_price');    

//filter for products whose orig_price is greater than (gt) 100
$collection->addFieldToFilter(array(
    array('attribute'=>'orig_price','gt'=>'100'),
)); 

//AND filter for products whose orig_price is less than (lt) 130
$collection->addFieldToFilter(array(
    array('attribute'=>'orig_price','lt'=>'130'),
));

While this will filter by a name that equals one thing OR another.

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');  
$collection->addAttributeToSelect('orig_price');    

//filter for products who name is equal (eq) to Widget A, or equal (eq) to Widget B
$collection->addFieldToFilter(array(
    array('attribute'=>'name','eq'=>'Widget A'),
    array('attribute'=>'name','eq'=>'Widget B'),        
));

A full list of the supported short conditionals (eq,lt, etc.) can be found in the _getConditionSql method in lib/Varien/Data/Collection/Db.php

Finally, all Magento collections may be iterated over (the base collection class implements on of the the iterator interfaces). This is how you'll grab your products once filters are set.

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');  
$collection->addAttributeToSelect('orig_price');    

//filter for products who name is equal (eq) to Widget A, or equal (eq) to Widget B
$collection->addFieldToFilter(array(
    array('attribute'=>'name','eq'=>'Widget A'),
    array('attribute'=>'name','eq'=>'Widget B'),        
));

foreach ($collection as $product) {
    //var_dump($product);
    var_dump($product->getData());
}

Increasing the maximum number of TCP/IP connections in Linux

There are a couple of variables to set the max number of connections. Most likely, you're running out of file numbers first. Check ulimit -n. After that, there are settings in /proc, but those default to the tens of thousands.

More importantly, it sounds like you're doing something wrong. A single TCP connection ought to be able to use all of the bandwidth between two parties; if it isn't:

  • Check if your TCP window setting is large enough. Linux defaults are good for everything except really fast inet link (hundreds of mbps) or fast satellite links. What is your bandwidth*delay product?
  • Check for packet loss using ping with large packets (ping -s 1472 ...)
  • Check for rate limiting. On Linux, this is configured with tc
  • Confirm that the bandwidth you think exists actually exists using e.g., iperf
  • Confirm that your protocol is sane. Remember latency.
  • If this is a gigabit+ LAN, can you use jumbo packets? Are you?

Possibly I have misunderstood. Maybe you're doing something like Bittorrent, where you need lots of connections. If so, you need to figure out how many connections you're actually using (try netstat or lsof). If that number is substantial, you might:

  • Have a lot of bandwidth, e.g., 100mbps+. In this case, you may actually need to up the ulimit -n. Still, ~1000 connections (default on my system) is quite a few.
  • Have network problems which are slowing down your connections (e.g., packet loss)
  • Have something else slowing you down, e.g., IO bandwidth, especially if you're seeking. Have you checked iostat -x?

Also, if you are using a consumer-grade NAT router (Linksys, Netgear, DLink, etc.), beware that you may exceed its abilities with thousands of connections.

I hope this provides some help. You're really asking a networking question.

How to call external JavaScript function in HTML

If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).

You need to use multiple script elements.

  1. a <script> to load the external script
  2. a <script> to hold your inline code (with the call to the function in the external script)

    scroll_messages();

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

I'm using a popup to show the map in a new window. I'm using the following url

https://www.google.com/maps?z=15&daddr=LATITUDE,LONGITUDE

HTML snippet

<a target='_blank' href='https://www.google.com/maps?z=15&daddr=${location.latitude},${location.longitude}'>Calculate route</a>

Determine SQL Server Database Size

According to SQL2000 help, sp_spaceused includes data and indexes.

This script should do:

CREATE TABLE #t (name SYSNAME, rows CHAR(11), reserved VARCHAR(18), 
data VARCHAR(18), index_size VARCHAR(18), unused VARCHAR(18))

EXEC sp_msforeachtable 'INSERT INTO #t EXEC sp_spaceused ''?'''
-- SELECT * FROM #t ORDER BY name
-- SELECT name, CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3)) FROM #t ORDER BY name
SELECT SUM(CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3))) FROM #t
DROP TABLE #t

Git clone without .git directory

Alternatively, if you have Node.js installed, you can use the following command:

npx degit GIT_REPO

npx comes with Node, and it allows you to run binary node-based packages without installing them first (alternatively, you can first install degit globally using npm i -g degit).

Degit is a tool created by Rich Harris, the creator of Svelte and Rollup, which he uses to quickly create a new project by cloning a repository without keeping the git folder. But it can also be used to clone any repo once...

How to check if a character in a string is a digit or letter

You could use the existing methods from the Character class. Take a look at the docs:

http://download.java.net/jdk7/archive/b123/docs/api/java/lang/Character.html#isDigit(char)

So, you could do something like this...

String character = in.next();
char c = character.charAt(0);
...
if (Character.isDigit(c)) { 
    ... 
} else if (Character.isLetter(c)) {
    ...
}
...

If you ever want to know exactly how this is implemented, you could always look at the Java source code.

Adding a collaborator to my free GitHub account?

It is pretty easy to add a collaborator to a free plan.

  1. Navigate to the repository on Github you wish to share with your collaborator.
  2. Click on the "Settings" tab on the right side of the menu at the top of the screen.
  3. On the new page, click the "Collaborators" menu item on the left side of the page.
  4. Start typing the new collaborator's GitHub username into the text box.
  5. Select the GitHub user from the list that appears below the text box.
  6. Click the "Add" button.

The added user should now be able to push to your repository on GitHub.

List method to delete last element in list as well as all elements

To delete the last element of the lists, you could use:

def deleteLast(self):
    if self.Ans:
        del self.Ans[-1]
    if self.masses:
        del self.masses[-1]

Should I write script in the body or the head of the html?

W3Schools have a nice article on this subject.

Scripts in <head>

Scripts to be executed when they are called, or when an event is triggered, are placed in functions.

Put your functions in the head section, this way they are all in one place, and they do not interfere with page content.

Scripts in <body>

If you don't want your script to be placed inside a function, or if your script should write page content, it should be placed in the body section.

How to send a PUT/DELETE request in jQuery?

We can extend jQuery to make shortcuts for PUT and DELETE:

jQuery.each( [ "put", "delete" ], function( i, method ) {
  jQuery[ method ] = function( url, data, callback, type ) {
    if ( jQuery.isFunction( data ) ) {
      type = type || callback;
      callback = data;
      data = undefined;
    }

    return jQuery.ajax({
      url: url,
      type: method,
      dataType: type,
      data: data,
      success: callback
    });
  };
});

and now you can use:

$.put('http://stackoverflow.com/posts/22786755/edit', {text:'new text'}, function(result){
   console.log(result);
})

copy from here

Difference between spring @Controller and @RestController annotation

@RestController is composition of @Controller and @ResponseBody, if we are not using the @ResponseBody in Method signature then we need to use the @Restcontroller.

Assign output of a program to a variable using a MS batch file

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

REM Prefer backtick usage for command output reading:
REM ENABLEDELAYEDEXPANSION is required for actualized
REM  outer variables within for's scope;
REM within for's scope, access to modified 
REM outer variable is done via !...! syntax.

SET CHP=C:\Windows\System32\chcp.com

FOR /F "usebackq tokens=1,2,3" %%i IN (`%CHP%`) DO (
    IF "%%i" == "Aktive" IF "%%j" == "Codepage:" (
        SET SELCP=%%k
        SET SELCP=!SELCP:~0,-1!
    )
)
echo actual codepage [%SELCP%]

ENDLOCAL

PL/SQL ORA-01422: exact fetch returns more than requested number of rows

It can also be due to a duplicate entry in any of the tables that are used.

"echo -n" prints "-n"

enable -n echo
echo -n "Some string..."

C# static class why use?

Static classes can be useful in certain situations, but there is a potential to abuse and/or overuse them, like most language features.

As Dylan Smith already mentioned, the most obvious case for using a static class is if you have a class with only static methods. There is no point in allowing developers to instantiate such a class.

The caveat is that an overabundance of static methods may itself indicate a flaw in your design strategy. I find that when you are creating a static function, its a good to ask yourself -- would it be better suited as either a) an instance method, or b) an extension method to an interface. The idea here is that object behaviors are usually associated with object state, meaning the behavior should belong to the object. By using a static function you are implying that the behavior shouldn't belong to any particular object.

Polymorphic and interface driven design are hindered by overusing static functions -- they cannot be overriden in derived classes nor can they be attached to an interface. Its usually better to have your 'helper' functions tied to an interface via an extension method such that all instances of the interface have access to that shared 'helper' functionality.

One situation where static functions are definitely useful, in my opinion, is in creating a .Create() or .New() method to implement logic for object creation, for instance when you want to proxy the object being created,

public class Foo
{
    public static Foo New(string fooString)
    {
        ProxyGenerator generator = new ProxyGenerator();

        return (Foo)generator.CreateClassProxy
             (typeof(Foo), new object[] { fooString }, new Interceptor()); 
    }

This can be used with a proxying framework (like Castle Dynamic Proxy) where you want to intercept / inject functionality into an object, based on say, certain attributes assigned to its methods. The overall idea is that you need a special constructor because technically you are creating a copy of the original instance with special added functionality.

Convert decimal to hexadecimal in UNIX shell script

Tried printf(1)?

printf "%x\n" 34
22

There are probably ways of doing that with builtin functions in all shells but it would be less portable. I've not checked the POSIX sh specs to see whether it has such capabilities.

Python string prints as [u'String']

If accessing/printing single element lists (e.g., sequentially or filtered):

my_list = [u'String'] # sample element
my_list = [str(my_list[0])]

Update only specific fields in a models.Model

Usually, the correct way of updating certain fields in one or more model instances is to use the update() method on the respective queryset. Then you do something like this:

affected_surveys = Survey.objects.filter(
    # restrict your queryset by whatever fits you
    # ...
    ).update(active=True)

This way, you don't need to call save() on your model anymore because it gets saved automatically. Also, the update() method returns the number of survey instances that were affected by your update.

Cropping an UIImage

On iOS9.2SDK ,I use below method to convert frame from UIView to UIImage

-(UIImage *)getNeedImageFrom:(UIImage*)image cropRect:(CGRect)rect
{
  CGSize cropSize = rect.size;
  CGFloat widthScale = image.size.width/self.imageViewOriginal.bounds.size.width;
  CGFloat heightScale = image.size.height/self.imageViewOriginal.bounds.size.height;
  cropSize = CGSizeMake(rect.size.width*widthScale, 
              rect.size.height*heightScale);
  CGPoint pointCrop = CGPointMake(rect.origin.x*widthScale,
             rect.origin.y*heightScale);
  rect = CGRectMake(pointCrop.x, pointCrop.y, cropSize.width, cropSize.height);
  CGImageRef subImage = CGImageCreateWithImageInRect(image.CGImage, rect);
  UIImage *croppedImage = [UIImage imageWithCGImage:subImage];
  CGImageRelease(subImage);

  return croppedImage;
}

How to run Spring Boot web application in Eclipse itself?

Just run the main method which is in the class SampleWebJspApplication. Spring Boot will take care of all the rest (starting the embedded tomcat which will host your sample application).

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

One-to-many and Many-to-one relationship is talking about the same logical relationship, eg an Owner may have many Homes, but a Home can only have one Owner.

So in this example Owner is the One, and Homes are the Many. Each Home always has an owner_id (eg the Foreign Key) as an extra column.

The difference in implementation between these two, is which table defines the relationship. In One-to-Many, the Owner is where the relationship is defined. Eg, owner1.homes lists all the homes with owner1's owner_id In Many-to-One, the Home is where the relationship is defined. Eg, home1.owner lists owner1's owner_id.

I dont actually know in what instance you would implement the many-to-one arrangement, because it seems a bit redundant as you already know the owner_id. Perhaps its related to cleanness of deletions and changes.

Proper way to catch exception from JSON.parse

i post something into an iframe then read back the contents of the iframe with json parse...so sometimes it's not a json string

Try this:

if(response) {
    try {
        a = JSON.parse(response);
    } catch(e) {
        alert(e); // error in the above string (in this case, yes)!
    }
}

How to improve Netbeans performance?

Really useful article about reasons why your NetBeans is slow:

http://wiki.netbeans.org/FaqSlowNetBeans

How to hide the title bar for an Activity in XML with existing custom theme

Add both of those for the theme you use:

    <item name="windowActionBar">false</item>
    <item name="android:windowNoTitle">true</item>

How to find event listeners on a DOM node when debugging or from the JavaScript code?

I was recently working with events and wanted to view/control all events in a page. Having looked at possible solutions, I've decided to go my own way and create a custom system to monitor events. So, I did three things.

First, I needed a container for all the event listeners in the page: that's theEventListeners object. It has three useful methods: add(), remove(), and get().

Next, I created an EventListener object to hold the necessary information for the event, i.e.: target, type, callback, options, useCapture, wantsUntrusted, and added a method remove() to remove the listener.

Lastly, I extended the native addEventListener() and removeEventListener() methods to make them work with the objects I've created (EventListener and EventListeners).

Usage:

var bodyClickEvent = document.body.addEventListener("click", function () {
    console.log("body click");
});

// bodyClickEvent.remove();

addEventListener() creates an EventListener object, adds it to EventListeners and returns the EventListener object, so it can be removed later.

EventListeners.get() can be used to view the listeners in the page. It accepts an EventTarget or a string (event type).

// EventListeners.get(document.body);
// EventListeners.get("click");

Demo

Let's say we want to know every event listener in this current page. We can do that (assuming you're using a script manager extension, Tampermonkey in this case). Following script does this:

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @include      https://stackoverflow.com/*
// @grant        none
// ==/UserScript==

(function() {
    fetch("https://raw.githubusercontent.com/akinuri/js-lib/master/EventListener.js")
        .then(function (response) {
            return response.text();
        })
        .then(function (text) {
            eval(text);
            window.EventListeners = EventListeners;
        });
})(window);

And when we list all the listeners, it says there are 299 event listeners. There "seems" to be some duplicates, but I don't know if they're really duplicates. Not every event type is duplicated, so all those "duplicates" might be an individual listener.

screenshot of console listing all event listeners in this page

Code can be found at my repository. I didn't want to post it here because it's rather long.


Update: This doesn't seem to work with jQuery. When I examine the EventListener, I see that the callback is

function(b){return"undefined"!=typeof r&&r.event.triggered!==b.type?r.event.dispatch.apply(a,arguments):void 0}

I believe this belongs to jQuery, and is not the actual callback. jQuery stores the actual callback in the properties of the EventTarget:

$(document.body).click(function () {
    console.log("jquery click");
});

enter image description here

To remove an event listener, the actual callback needs to be passed to the removeEventListener() method. So in order to make this work with jQuery, it needs further modification. I might fix that in the future.

Composer: file_put_contents(./composer.json): failed to open stream: Permission denied

For me, in Ubuntu 18.04. I needed to chown inside ~/.config/composer/

E.g.

sudo chown -R $USER ~/.config/composer

Then global commands work.

How do I join two lines in vi?

Just replace the "\n" with "".

In vi/Vim for every line in the document:

%s/>\n_/>_/g

If you want to confirm every replacement:

%s/>\n_/>_/gc

Check if input is number or letter javascript

you can use isNaN(). it returns true when data is not number.

var data = 'hello there';
if(isNaN(data)){
  alert("it is not number");
}else {
  alert("its a valid number");
}

Sound alarm when code finishes

It can be done by code as follows:

import time
time.sleep(10)   #Set the time
for x in range(60):  
    time.sleep(1)
    print('\a')

How to print a string in C++

#include <iostream>
std::cout << someString << "\n";

or

printf("%s\n",someString.c_str());

Python Array with String Indices

Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.

Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.

js window.open then print()

<script type="text/javascript">

    function printDiv(divName) {
         var printContents = document.getElementById(divName).innerHTML;
         var originalContents = document.body.innerHTML;
         document.body.innerHTML = printContents;
         window.print();
         document.body.innerHTML = originalContents;
    }

</script>


<div id="printableArea">CONTENT TO PRINT</div>



<input type="button" onclick="printDiv('printableArea')" value="Print Report" />

How to get on scroll events?

// @HostListener('scroll', ['$event']) // for scroll events of the current element
@HostListener('window:scroll', ['$event']) // for window scroll events
onScroll(event) {
  ...
}

or

<div (scroll)="onScroll($event)"></div>

Dynamically generating a QR code with PHP

I have been using google qrcode api for sometime, but I didn't quite like this because it requires me to be on the Internet to access the generated image.

I did a little comand-line research and found out that linux has a command line tool qrencode for generating qr-codes.

I wrote this little script. And the good part is that the generated image is less than 1KB in size. Well the supplied data is simply a url.

$url = ($_SERVER['HTTPS'] ? "https://" : "http://").$_SERVER['HTTP_HOST'].'/profile.php?id='.$_GET['pid'];
$img = shell_exec('qrencode --output=- -m=1 '.escapeshellarg($url));

$imgData = "data:image/png;base64,".base64_encode($img);

Then in the html I load the image:

<img class="emrQRCode" src="<?=$imgData ?>" />

You just need to have installed it. [most imaging apps on linux would have installed it under the hood without you realizing.

Sending emails in Node.js?

Mature, simple to use and has lots of features if simple isn't enought: Nodemailer: https://github.com/andris9/nodemailer (note correct url!)

How to get current working directory in Java?

Who says your main class is in a file on a local harddisk? Classes are more often bundled inside JAR files, and sometimes loaded over the network or even generated on the fly.

So what is it that you actually want to do? There is probably a way to do it that does not make assumptions about where classes come from.

Push items into mongo array via mongoose

Assuming, var friend = { firstName: 'Harry', lastName: 'Potter' };

There are two options you have:

Update the model in-memory, and save (plain javascript array.push):

person.friends.push(friend);
person.save(done);

or

PersonModel.update(
    { _id: person._id }, 
    { $push: { friends: friend } },
    done
);

I always try and go for the first option when possible, because it'll respect more of the benefits that mongoose gives you (hooks, validation, etc.).

However, if you are doing lots of concurrent writes, you will hit race conditions where you'll end up with nasty version errors to stop you from replacing the entire model each time and losing the previous friend you added. So only go to the former when it's absolutely necessary.

Custom Authentication in ASP.Net-Core

Creating custom authentication in ASP.NET Core can be done in a variety of ways. If you want to build off existing components (but don't want to use identity), checkout the "Security" category of docs on docs.asp.net. https://docs.asp.net/en/latest/security/index.html

Some articles you might find helpful:

Using Cookie Middleware without ASP.NET Identity

Custom Policy-Based Authorization

And of course, if that fails or docs aren't clear enough, the source code is at https://github.com/dotnet/aspnetcore/tree/master/src/Security which includes some samples.

undefined reference to WinMain@16 (codeblocks)

  1. You need to open the project file of your program and it should appear on Management panel.

  2. Right click on the project file, then select add file. You should add the 3 source code (secrypt.h, secrypt.cpp, and the trial.cpp)

  3. Compile and enjoy. Hope, I could help you.

How to truncate float values?

Short and easy variant

def truncate_float(value, digits_after_point=2):
    pow_10 = 10 ** digits_after_point
    return (float(int(value * pow_10))) / pow_10

>>> truncate_float(1.14333, 2)
>>> 1.14

>>> truncate_float(1.14777, 2)
>>> 1.14


>>> truncate_float(1.14777, 4)
>>> 1.1477

Accessing Redux state in an action creator?

I know I'm late to the party here, but I came here for opinions on my own desire to use state in actions, and then formed my own, when I realized what I think is the correct behavior.

This is where a selector makes the most sense to me. Your component that issues this request should be told wether it's time to issue it through selection.

export const SOME_ACTION = 'SOME_ACTION';
export function someAction(items) {
  return (dispatch) => {
    dispatch(anotherAction(items));
  }
}

It might feel like leaking abstractions, but your component clearly needs to send a message and the message payload should contain pertinent state. Unfortunately your question doesn't have a concrete example because we could work through a 'better model' of selectors and actions that way.

Is there a way to make mv create the directory to be moved to if it doesn't exist?

You can even use brace extensions:

mkdir -p directory{1..3}/subdirectory{1..3}/subsubdirectory{1..2}      
  • which creates 3 directories (directory1, directory2, directory3),
    • and in each one of them two subdirectories (subdirectory1, subdirectory2),
      • and in each of them two subsubdirectories (subsubdirectory1 and subsubdirectory2).

You have to use bash 3.0 or newer.

Python Infinity - Any caveats?

A VERY BAD CAVEAT : Division by Zero

in a 1/x fraction, up to x = 1e-323 it is inf but when x = 1e-324 or little it throws ZeroDivisionError

>>> 1/1e-323
inf

>>> 1/1e-324
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: float division by zero

so be cautious!

hibernate could not get next sequence value

Using the GeneratedValue and GenericGenerator with the native strategy:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_native")
@GenericGenerator(name = "id_native", strategy = "native")
@Column(name = "id", updatable = false, nullable = false)
private Long id;

I had to create a sequence call hibernate_sequence as Hibernate looks up for such a sequence by default:

create sequence hibernate_sequence start with 1 increment by 50;
grant usage, select on all sequences in schema public to my_user_name;

How to format strings in Java

This solution worked for me. I needed to create urls for a REST client dynamically so I created this method, so you just have to pass the restURL like this

/customer/{0}/user/{1}/order

and add as many params as you need:

public String createURL (String restURL, Object ... params) {       
    return new MessageFormat(restURL).format(params);
}

You just have to call this method like this:

createURL("/customer/{0}/user/{1}/order", 123, 321);

The output

"/customer/123/user/321/order"

jQuery .each() index?

$('#list option').each(function(intIndex){
//do stuff
});

How to find a value in an array of objects in JavaScript?

I had to search a nested sitemap structure for the first leaf item that machtes a given path. I came up with the following code just using .map() .filter() and .reduce. Returns the last item found that matches the path /c.

var sitemap = {
  nodes: [
    {
      items: [{ path: "/a" }, { path: "/b" }]
    },
    {
      items: [{ path: "/c" }, { path: "/d" }]
    },
    {
      items: [{ path: "/c" }, { path: "/d" }]
    }
  ]
};

const item = sitemap.nodes
  .map(n => n.items.filter(i => i.path === "/c"))
  .reduce((last, now) => last.concat(now))
  .reduce((last, now) => now);

Edit 4n4904z07

Non-recursive depth first search algorithm

An ES6 implementation based on biziclops great answer:

_x000D_
_x000D_
root = {_x000D_
  text: "root",_x000D_
  children: [{_x000D_
    text: "c1",_x000D_
    children: [{_x000D_
      text: "c11"_x000D_
    }, {_x000D_
      text: "c12"_x000D_
    }]_x000D_
  }, {_x000D_
    text: "c2",_x000D_
    children: [{_x000D_
      text: "c21"_x000D_
    }, {_x000D_
      text: "c22"_x000D_
    }]_x000D_
  }, ]_x000D_
}_x000D_
_x000D_
console.log("DFS:")_x000D_
DFS(root, node => node.children, node => console.log(node.text));_x000D_
_x000D_
console.log("BFS:")_x000D_
BFS(root, node => node.children, node => console.log(node.text));_x000D_
_x000D_
function BFS(root, getChildren, visit) {_x000D_
  let nodesToVisit = [root];_x000D_
  while (nodesToVisit.length > 0) {_x000D_
    const currentNode = nodesToVisit.shift();_x000D_
    nodesToVisit = [_x000D_
      ...nodesToVisit,_x000D_
      ...(getChildren(currentNode) || []),_x000D_
    ];_x000D_
    visit(currentNode);_x000D_
  }_x000D_
}_x000D_
_x000D_
function DFS(root, getChildren, visit) {_x000D_
  let nodesToVisit = [root];_x000D_
  while (nodesToVisit.length > 0) {_x000D_
    const currentNode = nodesToVisit.shift();_x000D_
    nodesToVisit = [_x000D_
      ...(getChildren(currentNode) || []),_x000D_
      ...nodesToVisit,_x000D_
    ];_x000D_
    visit(currentNode);_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Load a Bootstrap popover content with AJAX. Is this possible?

See my blog post for the working solution: https://medium.com/cagataygurturk/load-a-bootstrap-popover-content-with-ajax-8a95cd34f6a4

First we should add a data-poload attribute to the elements you would like to add a pop over to. The content of this attribute should be the url to be loaded (absolute or relative):

<a href="#" title="blabla" data-poload="/test.php">blabla</a>

And in JavaScript, preferably in a $(document).ready();

$('*[data-poload]').hover(function() {
    var e=$(this);
    e.off('hover');
    $.get(e.data('poload'),function(d) {
        e.popover({content: d}).popover('show');
    });
});

off('hover') prevents loading data more than once and popover() binds a new hover event. If you want the data to be refreshed at every hover event, you should remove the off.

Please see the working JSFiddle of the example.

What does it mean to write to stdout in C?

stdout stands for standard output stream and it is a stream which is available to your program by the operating system itself. It is already available to your program from the beginning together with stdin and stderr.

What they point to (or from) can be anything, actually the stream just provides your program an object that can be used as an interface to send or retrieve data. By default it is usually the terminal but it can be redirected wherever you want: a file, to a pipe goint to another process and so on.

MySQL count occurrences greater than 2

SELECT count(word) as count 
FROM words 
GROUP BY word
HAVING count >= 2;

LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

I find that when i choose option of Project->Properties->Linker->System->SubSystem->Console(/subsystem:console), and then make sure include the function : int _tmain(int argc,_TCHAR* argv[]){return 0} all of the compiling ,linking and running will be ok;

Map and filter an array at the same time

With ES6 you can do it very short:

options.filter(opt => !opt.assigned).map(opt => someNewObject)

Python equivalent of a given wget command

Let me Improve a example with threads in case you want download many files.

import math
import random
import threading

import requests
from clint.textui import progress

# You must define a proxy list
# I suggests https://free-proxy-list.net/
proxies = {
    0: {'http': 'http://34.208.47.183:80'},
    1: {'http': 'http://40.69.191.149:3128'},
    2: {'http': 'http://104.154.205.214:1080'},
    3: {'http': 'http://52.11.190.64:3128'}
}


# you must define the list for files do you want download
videos = [
    "https://i.stack.imgur.com/g2BHi.jpg",
    "https://i.stack.imgur.com/NURaP.jpg"
]

downloaderses = list()


def downloaders(video, selected_proxy):
    print("Downloading file named {} by proxy {}...".format(video, selected_proxy))
    r = requests.get(video, stream=True, proxies=selected_proxy)
    nombre_video = video.split("/")[3]
    with open(nombre_video, 'wb') as f:
        total_length = int(r.headers.get('content-length'))
        for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length / 1024) + 1):
            if chunk:
                f.write(chunk)
                f.flush()


for video in videos:
    selected_proxy = proxies[math.floor(random.random() * len(proxies))]
    t = threading.Thread(target=downloaders, args=(video, selected_proxy))
    downloaderses.append(t)

for _downloaders in downloaderses:
    _downloaders.start()

Is there a C# case insensitive equals operator?

string.Equals(StringA, StringB, StringComparison.CurrentCultureIgnoreCase);

CFNetwork SSLHandshake failed iOS 9

iOS 9 and OSX 10.11 require TLSv1.2 SSL for all hosts you plan to request data from unless you specify exception domains in your app's Info.plist file.

The syntax for the Info.plist configuration looks like this:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>yourserver.com</key>
    <dict>
      <!--Include to allow subdomains-->
      <key>NSIncludesSubdomains</key>
      <true/>
      <!--Include to allow insecure HTTP requests-->
      <key>NSExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      <!--Include to specify minimum TLS version-->
      <key>NSExceptionMinimumTLSVersion</key>
      <string>TLSv1.1</string>
    </dict>
  </dict>
</dict>

If your application (a third-party web browser, for instance) needs to connect to arbitrary hosts, you can configure it like this:

<key>NSAppTransportSecurity</key>
<dict>
    <!--Connect to anything (this is probably BAD)-->
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

If you're having to do this, it's probably best to update your servers to use TLSv1.2 and SSL, if they're not already doing so. This should be considered a temporary workaround.

As of today, the prerelease documentation makes no mention of any of these configuration options in any specific way. Once it does, I'll update the answer to link to the relevant documentation.

Checking if any elements in one list are in another

You could solve this many ways. One that is pretty simple to understand is to just use a loop.

def comp(list1, list2):
    for val in list1:
        if val in list2:
            return True
    return False

A more compact way you can do it is to use map and reduce:

reduce(lambda v1,v2: v1 or v2, map(lambda v: v in list2, list1))

Even better, the reduce can be replaced with any:

any(map(lambda v: v in list2, list1))

You could also use sets:

len(set(list1).intersection(list2)) > 0

Get value of a string after last slash in JavaScript

As required in Question::

var string1= "foo/bar/test.html";
  if(string1.contains("/"))
  {
      var string_parts = string1.split("/");
    var result = string_parts[string_parts.length - 1];
    console.log(result);
  }  

and for question asked on url (asked for one occurence of '=' )::
[http://stackoverflow.com/questions/24156535/how-to-split-a-string-after-a-particular-character-in-jquery][1]

var string1= "Hello how are =you";
  if(string1.contains("="))
  {
      var string_parts = string1.split("=");
    var result = string_parts[string_parts.length - 1];
    console.log(result);
  }

Does Notepad++ show all hidden characters?

In newer versions of Notepad++ (currently 5.9), this option is under:

View->Show Symbol->Show All Characters

or

View->Show Symbol->Show White Space and Tab

How to stop and restart memcached server?

if linux

if install by apt-get

service memcached stop
service memcached restart

if install by source code

Usage: /etc/init.d/memcached {start|stop|restart|force-reload|status}

can also simply kill $pid to stop

Is it possible to remove the hand cursor that appears when hovering over a link? (or keep it set as the normal pointer)

Using inline styling use <a href="your link here" style="cursor:default">your content here</a>. See this example

Alternatively use css. See this example.

This solution is cross-browser compatible.

Remove the last three characters from a string

I read through all these, but wanted something a bit more elegant. Just to remove a certain number of characters from the end of a string:

string.Concat("hello".Reverse().Skip(3).Reverse());

output:

"he"

JPA Criteria API - How to add JOIN clause (as general sentence as possible)

Maybe the following extract from the Chapter 23 - Using the Criteria API to Create Queries of the Java EE 6 tutorial will throw some light (actually, I suggest reading the whole Chapter 23):

Querying Relationships Using Joins

For queries that navigate to related entity classes, the query must define a join to the related entity by calling one of the From.join methods on the query root object, or another join object. The join methods are similar to the JOIN keyword in JPQL.

The target of the join uses the Metamodel class of type EntityType<T> to specify the persistent field or property of the joined entity.

The join methods return an object of type Join<X, Y>, where X is the source entity and Y is the target of the join.

Example 23-10 Joining a Query

CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Metamodel m = em.getMetamodel();
EntityType<Pet> Pet_ = m.entity(Pet.class);

Root<Pet> pet = cq.from(Pet.class);
Join<Pet, Owner> owner = pet.join(Pet_.owners);

Joins can be chained together to navigate to related entities of the target entity without having to create a Join<X, Y> instance for each join.

Example 23-11 Chaining Joins Together in a Query

CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Metamodel m = em.getMetamodel();
EntityType<Pet> Pet_ = m.entity(Pet.class);
EntityType<Owner> Owner_ = m.entity(Owner.class);

Root<Pet> pet = cq.from(Pet.class);
Join<Owner, Address> address = cq.join(Pet_.owners).join(Owner_.addresses);

That being said, I have some additional remarks:

First, the following line in your code:

Root entity_ = cq.from(this.baseClass);

Makes me think that you somehow missed the Static Metamodel Classes part. Metamodel classes such as Pet_ in the quoted example are used to describe the meta information of a persistent class. They are typically generated using an annotation processor (canonical metamodel classes) or can be written by the developer (non-canonical metamodel). But your syntax looks weird, I think you are trying to mimic something that you missed.

Second, I really think you should forget this assay_id foreign key, you're on the wrong path here. You really need to start to think object and association, not tables and columns.

Third, I'm not really sure to understand what you mean exactly by adding a JOIN clause as generical as possible and what your object model looks like, since you didn't provide it (see previous point). It's thus just impossible to answer your question more precisely.

To sum up, I think you need to read a bit more about JPA 2.0 Criteria and Metamodel API and I warmly recommend the resources below as a starting point.

See also

Related question

Writing a dictionary to a csv file with one line for every 'key: value'

Can you just do:

for key in mydict.keys():
    f.write(str(key) + ":" + str(mydict[key]) + ",");

So that you can have

key_1: value_1, key_2: value_2

How do I convert a factor into date format?

You can try lubridate package which makes life much easier

library(lubridate)

mdy_hms(mydate)

The above will change the date format to POSIXct

A sample working example:

> data <- "1/15/2006 01:15:00"
> library(lubridate)
> mydate <- mdy_hms(data)
> mydate
[1] "2006-01-15 01:15:00 UTC"
> class(mydate)
[1] "POSIXct" "POSIXt" 

For case with factor use as.character

data <- factor("1/15/2006 01:15:00")
library(lubridate)
mydate <- mdy_hms(as.character(data))

Use jQuery to change an HTML tag?

Once a dom element is created, the tag is immutable, I believe. You'd have to do something like this:

$(this).replaceWith($('<h5>' + this.innerHTML + '</h5>'));

How to convert the time from AM/PM to 24 hour format in PHP?

You can use this for 24 hour to 12 hour:

echo date("h:i", strtotime($time));

And for vice versa:

echo date("H:i", strtotime($time));

Correct way to pause a Python program

I use the following for Python 2 and Python 3 to pause code execution until user presses Enter

import six

if six.PY2:
    raw_input("Press the <Enter> key to continue...")
else:
    input("Press the <Enter> key to continue...")

Java executors: how to be notified, without blocking, when a task completes?

Use Guava's listenable future API and add a callback. Cf. from the website :

ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
ListenableFuture<Explosion> explosion = service.submit(new Callable<Explosion>() {
  public Explosion call() {
    return pushBigRedButton();
  }
});
Futures.addCallback(explosion, new FutureCallback<Explosion>() {
  // we want this handler to run immediately after we push the big red button!
  public void onSuccess(Explosion explosion) {
    walkAwayFrom(explosion);
  }
  public void onFailure(Throwable thrown) {
    battleArchNemesis(); // escaped the explosion!
  }
});

return in for loop or outside loop

There have been methodologies in all languages advocating for use of a single return statement in any function. However impossible it may be in certain code, some people do strive for that, however, it may end up making your code more complex (as in more lines of code), but on the other hand, somewhat easier to follow (as in logic flow).

This will not mess up garbage collection in any way!!

The better way to do it is to set a boolean value, if you want to listen to him.

boolean flag = false;
for(int i=0; i<array.length; ++i){
    if(array[i] == valueToFind) {
        flag = true;
        break;
    }
}
return flag;

Storing a file in a database as opposed to the file system?

Not to be vague or anything but I think the type of 'file' you will be storing is one of the biggest determining factors. If you essentially talking about a large text field which could be stored as file my preference would be for db storage.

CSS/Javascript to force html table row on a single line

For those further interested:

Existing Dynamic Table Cells: ## Long text with NO SPACES i.e. email addresses ##

It appears a full replication of the MS (and others) use of text-overflow:ellipsis cannot be duped in FireFox so far as adding the internally appended to clipped text is concerned; especially without javascript which is often user switched off these days.

All ideas I have found to help me have failed to address dynamic resizing and long text without spaces.

However, I had a need for clipping in a dynamic width table in one of my progs admin windows. So with a little fiddling an acceptable all browser answer can be hacked from the supplied samples at “MSDN”.

i.e.

<table width="20%" border="1" STYLE="position: absolute; top: 100;">
<tr>

<td width="100%"><DIV STYLE="position: relative; height: 14px; top: 0px; width:100%;">
<DIV STYLE="position: absolute; left: 0px; top: 0px; color: black; width: 100%; height: 14px;
    font: 12px Verdana, Arial, Geneva, sans-serif; overflow: hidden; text-overflow:ellipsis;">
<NOBR>fasfasfasfasfsfsffsdafffsafsfsfsfsfasfsfsfsafsfsfsfWe hold these truths to be self-evident, that all people are created equal.</NOBR></DIV>
</DIV>

</td>
</tr>
</table>

Only small shortcoming is Firefox users don’t see the “…” bit; which is summink I don’t really mind at this stage.

Future FF should, hopefully, resolve gracefully if implementing this very important useful option. So now I don’t need to rewrite using less favorable futuristic non tabled content either (don’t argue; there’s plenty of broken web sites around ’cause of it these days).

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

Hope it helps some bod.

how to get current month and year

label1.Text = DateTime.Now.Month.ToString();

and

label2.Text = DateTime.Now.Year.ToString();

Count number of lines in a git repository

xargs will do what you want:

git ls-files | xargs cat | wc -l

But with more information and probably better, you can do:

git ls-files | xargs wc -l

How to change language settings in R

You may also want to be aware of the difference between, for example, Sys.setenv(LANG = "ru") and Sys.setlocale(locale = "ru_RU.utf8").

> Sys.setlocale(locale = "ru_RU.utf8")
[1] "LC_CTYPE=ru_RU.utf8;LC_NUMERIC=C;LC_TIME=ru_RU.utf8;LC_COLLATE=ru_RU.utf8;LC_MONETARY=ru_RU.utf8;LC_MESSAGES=en_IE.utf8;LC_PAPER=en_IE.utf8;LC_NAME=en_IE.utf8;LC_ADDRESS=en_IE.utf8;LC_TELEPHONE=en_IE.utf8;LC_MEASUREMENT=en_IE.utf8;LC_IDENTIFICATION=en_IE.utf8"

If you are interested in changing the behaviour of functions that refer to one of these elements (e.g strptime to extract dates), you should use Sys.setlocale(). See ?Sys.setlocale for more details. In order to see all available languages on a linux system, you can run

system("locale -a", intern = TRUE)

HTTP response code for POST when resource already exists

Another potential treatment is using PATCH after all. A PATCH is defined as something that changes the internal state and is not restricted to appending.

PATCH would solve the problem by allowing you to update already existing items. See: RFC 5789: PATCH

PHP upload image

Simple PHP file/image upload code on same page.

<form action="" method="post" enctype="multipart/form-data">
  <table border="1px">
    <tr><td><input type="file" name="image" ></td></tr>
    <tr><td> <input type="submit" value="upload" name="btn"></td></tr>
  </table>
</form>

 <?php
   if(isset($_POST['btn'])){
     $image=$_FILES['image']['name']; 
     $imageArr=explode('.',$image); //first index is file name and second index file type
     $rand=rand(10000,99999);
     $newImageName=$imageArr[0].$rand.'.'.$imageArr[1];
     $uploadPath="uploads/".$newImageName;
     $isUploaded=move_uploaded_file($_FILES["image"]["tmp_name"],$uploadPath);
     if($isUploaded)
       echo 'successfully file uploaded';
     else
       echo 'something went wrong'; 
   }

 ?>

Make a DIV fill an entire table cell

Since every other browser (including IE 7, 8 and 9) handles position:relative on a table cell correctly and only Firefox gets it wrong, your best bet is to use a JavaScript shim. You shouldn’t have to alter your DOM for one failed browser. People use shims all the time when IE gets something wrong and all the other browsers get it right.

Here is a snippet with all the code annotated. The JavaScript, HTML and CSS use responsive web design practices in my example, but you don’t have to if you don’t want. (Responsive means it adapts to your browser width.)

http://jsfiddle.net/mrbinky3000/MfWuV/33/

Here is the code itself, but it doesn’t make sense without the context, so visit the jsfiddle URL above. (The full snippet also has plenty of comments in both the CSS and the Javascript.)

$(function() {
    // FireFox Shim
    if ($.browser.mozilla) {
        $('#test').wrapInner('<div class="ffpad"></div>');
        function ffpad() {
            var $ffpad = $('.ffpad'),
                $parent = $('.ffpad').parent(),
                w, h;
            $ffpad.height(0);
            if ($parent.css('display') == 'table-cell') {               
                h = $parent.outerHeight();
                $ffpad.height(h);
            }
        }
        $(window).on('resize', function() {
            ffpad();
        });
        ffpad();
    }
});

How to put two divs side by side

Regarding the width of your website, you'll want to consider using a wrapper class to surround your content (this should help to constrain your element widths and prevent them from expanding too far beyond the content):

<style>
.wrapper {
  width: 980px;
}
</style>

<body>
  <div class="wrapper">
    //everything else
  </div>
</body>

As far as the content boxes go, I would suggest trying to use

<style>
.boxes {
  display: inline-block;
  width: 360px;
  height: 360px;
}
#leftBox {
  float: left;
}
#rightBox {
  float: right;
}
</style>

I would spend some time researching the box-object model and all of the "display" properties. They will be forever helpful. Pay particularly close attention to "inline-block", I use it practically every day.

What is the best way to ensure only one instance of a Bash script is running?

Use the set -o noclobber option and attempt to overwrite a common file.

A short example

if ! (set -o noclobber ; echo > /tmp/global.lock) ; then
    exit 1  # the global.lock already exists
fi

# ... remainder of script ...

A longer example

This example will wait for the global.lock file but timeout after too long.

 function lockfile_waithold()
 {
    declare -ir time_beg=$(date '+%s')
    declare -ir time_max=7140  # 7140 s = 1 hour 59 min.
 
    # poll for lock file up to ${time_max}s
    # put debugging info in lock file in case of issues ...
    while ! \
       (set -o noclobber ; \
        echo -e "DATE:$(date)\nUSER:$(whoami)\nPID:$$" > /tmp/global.lock \ 
       ) 2>/dev/null
    do
        if [ $(($(date '+%s') - ${time_beg})) -gt ${time_max} ] ; then
            echo "Error: waited too long for lock file /tmp/global.lock" 1>&2
            return 1
        fi
        sleep 1
    done
 
    return 0
 }
 
 function lockfile_release()
 {
    rm -f /tmp/global.lock
 }
 
 if ! lockfile_waithold ; then
      exit 1
 fi
 trap lockfile_release EXIT
 
 # ... remainder of script ...

This has reliably worked for me on an Ubuntu 16 host with multiple instances of a bash script that used the same system-wide "lock" file.

(This is similar to this post by @Barry Kelly which was noticed afterward.)

Iif equivalent in C#

VB.NET:

If(someBool, "true", "false")

C#

someBool ? "true" : "false";

Disabled form inputs do not appear in the request

If you absolutely have to have the field disabled and pass the data you could use a javascript to input the same data into a hidden field (or just set the hidden field too). This would allow you to have it disabled but still post the data even though you'd be posting to another page.

HTML email with Javascript

Just as a warning, many modern email browsers have JavaScript disabled for incoming emails as it can cause security problems. This means that many of the people you are emailing may not be able to use the content.

PS. Didn't see above post's at time of posting. My bad.

Setting width/height as percentage minus pixels

Try box-sizing. For the list:

height: 100%;
/* Presuming 10px header height */
padding-top: 10px;
/* Firefox */
-moz-box-sizing: border-box;
/* WebKit */
-webkit-box-sizing: border-box;
/* Standard */
box-sizing: border-box;

For the header:

position: absolute;
left: 0;
top: 0;
height: 10px;

Of course, the parent container should has something like:

position: relative;

MySQL WHERE: how to write "!=" or "not equals"?

The != operator most certainly does exist! It is an alias for the standard <> operator.

Perhaps your fields are not actually empty strings, but instead NULL?

To compare to NULL you can use IS NULL or IS NOT NULL or the null safe equals operator <=>.

Is there a limit on number of tcp/ip connections between machines on linux?

You might wanna check out /etc/security/limits.conf

.bashrc at ssh login

If ayman's solution doesn't work, try naming your file .profile instead of .bash_profile. That worked for me.

Data at the root level is invalid

I found that the example I was using had an xml document specification on the first line. I was using a stylesheet I got at this blog entry and the first line was

<?xmlversion="1.0"encoding="utf-8"?>

which was causing the error. When I removed that line, so that the stylesheet started with the line

<xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

my transform worked. By the way, that blog post was the first good, easy-to follow example I have found for trying to get information from the XML definition of an SSIS package, but I did have to modify the paths in the example for my SSIS 2008 packages, so you might too. I also created a version to extract the "flow" from the precedence constraints. My final one looks like this:

    <xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" encoding="utf-8" />
    <xsl:template match="/">
    <xsl:text>From,To~</xsl:text>
    <xsl:text>
</xsl:text>
    <xsl:for-each select="//DTS:PrecedenceConstraints/DTS:PrecedenceConstraint">
      <xsl:value-of select="@DTS:From"/>
      <xsl:text>,</xsl:text>
      <xsl:value-of select="@DTS:To"/>
       <xsl:text>~</xsl:text>
      <xsl:text>
</xsl:text>
    </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

and gave me a CSV with the tilde as my line delimiter. I replaced that with a line feed in my text editor then imported into excel to get a with look at the data flow in the package.

How to load json into my angular.js ng-model?

Here's a simple example of how to load JSON data into an Angular model.

I have a JSON 'GET' web service which returns a list of Customer details, from an online copy of Microsoft's Northwind SQL Server database.

http://www.iNorthwind.com/Service1.svc/getAllCustomers

It returns some JSON data which looks like this:

{ 
    "GetAllCustomersResult" : 
        [
            {
              "CompanyName": "Alfreds Futterkiste",
              "CustomerID": "ALFKI"
            },
            {
              "CompanyName": "Ana Trujillo Emparedados y helados",
              "CustomerID": "ANATR"
            },
            {
              "CompanyName": "Antonio Moreno Taquería",
              "CustomerID": "ANTON"
            }
        ]
    }

..and I want to populate a drop down list with this data, to look like this...

Angular screenshot

I want the text of each item to come from the "CompanyName" field, and the ID to come from the "CustomerID" fields.

How would I do it ?

My Angular controller would look like this:

function MikesAngularController($scope, $http) {

    $scope.listOfCustomers = null;

    $http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
         .success(function (data) {
             $scope.listOfCustomers = data.GetAllCustomersResult;
         })
         .error(function (data, status, headers, config) {
             //  Do some error handling here
         });
}

... which fills a "listOfCustomers" variable with this set of JSON data.

Then, in my HTML page, I'd use this:

<div ng-controller='MikesAngularController'>
    <span>Please select a customer:</span>
    <select ng-model="selectedCustomer" ng-options="customer.CustomerID as customer.CompanyName for customer in listOfCustomers" style="width:350px;"></select>
</div>

And that's it. We can now see a list of our JSON data on a web page, ready to be used.

The key to this is in the "ng-options" tag:

customer.CustomerID as customer.CompanyName for customer in listOfCustomers

It's a strange syntax to get your head around !

When the user selects an item in this list, the "$scope.selectedCustomer" variable will be set to the ID (the CustomerID field) of that Customer record.

The full script for this example can be found here:

JSON data with Angular

Mike

Makefile to compile multiple C programs?

Do it like so

all: program1 program2

program1: program1.c
    gcc -o program1 program1.c

program2: program2.c
    gcc -o program2 program2.c

You said you don't want advanced stuff, but you could also shorten it like this based on some default rules.

all: program1 program2

program1: program1.c
program2: program2.c