Programs & Examples On #Variable assignment

A process of setting or re-setting the value stored in the storage location(s) denoted by a variable name.

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

Java Language Specification defines E1 op= E2 to be equivalent to E1 = (T) ((E1) op (E2)) where T is a type of E1 and E1 is evaluated once.

That's a technical answer, but you may be wondering why that's a case. Well, let's consider the following program.

public class PlusEquals {
    public static void main(String[] args) {
        byte a = 1;
        byte b = 2;
        a = a + b;
        System.out.println(a);
    }
}

What does this program print?

Did you guess 3? Too bad, this program won't compile. Why? Well, it so happens that addition of bytes in Java is defined to return an int. This, I believe was because the Java Virtual Machine doesn't define byte operations to save on bytecodes (there is a limited number of those, after all), using integer operations instead is an implementation detail exposed in a language.

But if a = a + b doesn't work, that would mean a += b would never work for bytes if it E1 += E2 was defined to be E1 = E1 + E2. As the previous example shows, that would be indeed the case. As a hack to make += operator work for bytes and shorts, there is an implicit cast involved. It's not that great of a hack, but back during the Java 1.0 work, the focus was on getting the language released to begin with. Now, because of backwards compatibility, this hack introduced in Java 1.0 couldn't be removed.

Python: Assign Value if None Exists

I'm also coming from Ruby so I love the syntax foo ||= 7.

This is the closest thing I can find.

foo = foo if 'foo' in vars() else 7

I've seen people do this for a dict:

try:
    foo['bar']
except KeyError:
    foo['bar'] = 7

Upadate: However, I recently found this gem:

foo['bar'] = foo.get('bar', 7)

If you like that, then for a regular variable you could do something like this:

vars()['foo'] = vars().get('foo', 7)

Global variables in R

What about .GlobalEnv$a <- "new" ? I saw this explicit way of creating a variable in a certain environment here: http://adv-r.had.co.nz/Environments.html. It seems shorter than using the assign() function.

Local variable referenced before assignment?

When Python parses the body of a function definition and encounters an assignment such as

feed = ...

Python interprets feed as a local variable by default. If you do not wish for it to be a local variable, you must put

global feed

in the function definition. The global statement does not have to be at the beginning of the function definition, but that is where it is usually placed. Wherever it is placed, the global declaration makes feed a global variable everywhere in the function.

Without the global statement, since feed is taken to be a local variable, when Python executes

feed = feed + 1,

Python evaluates the right-hand side first and tries to look up the value of feed. The first time through it finds feed is undefined. Hence the error.

The shortest way to patch up the code is to add global feed to the beginning of onLoadFinished. The nicer way is to use a class:

class Page(object):
    def __init__(self):
        self.feed = 0
    def onLoadFinished(self, result):
        ...
        self.feed += 1

The problem with having functions which mutate global variables is that it makes it harder to grok your code. Functions are no longer isolated units. Their interaction extends to everything that affects or is affected by the global variable. Thus it makes larger programs harder to understand.

By avoiding mutating globals, in the long run your code will be easier to understand, test and maintain.

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

@OP, you can use for loops to capture the return status of your program, if it outputs something other than numbers

Check if returned value is not null and if so assign it, in one line, with one method call

Same principle as Loki's answer but shorter. Just keep in mind that shorter doesn't automatically mean better.

dinner = Optional.ofNullable(cage.getChicken())
  .orElse(getFreerangeChicken());

Note: This usage of Optional is explicitly discouraged by the architects of the JDK and the designers of the Optional feature. You are allocating a fresh object and immediately throwing it away every time. But on the other hand it can be quite readable.

Linux bash: Multiple variable assignment

I think this might help...

In order to break down user inputted dates (mm/dd/yyyy) in my scripts, I store the day, month, and year into an array, and then put the values into separate variables as follows:

DATE_ARRAY=(`echo $2 | sed -e 's/\// /g'`)
MONTH=(`echo ${DATE_ARRAY[0]}`)
DAY=(`echo ${DATE_ARRAY[1]}`)
YEAR=(`echo ${DATE_ARRAY[2]}`)

How to assign a value to a TensorFlow variable?

Use Tensorflow eager execution mode which is latest.

import tensorflow as tf
tf.enable_eager_execution()
my_int_variable = tf.get_variable("my_int_variable", [1, 2, 3])
print(my_int_variable)

Assignment inside lambda expression in Python

Normal assignment (=) is not possible inside a lambda expression, although it is possible to perform various tricks with setattr and friends.

Solving your problem, however, is actually quite simple:

input = [Object(name=""), Object(name="fake_name"), Object(name="")]
output = filter(
    lambda o, _seen=set():
        not (not o and o in _seen or _seen.add(o)),
    input
    )

which will give you

[Object(Object(name=''), name='fake_name')]

As you can see, it's keeping the first blank instance instead of the last. If you need the last instead, reverse the list going in to filter, and reverse the list coming out of filter:

output = filter(
    lambda o, _seen=set():
        not (not o and o in _seen or _seen.add(o)),
    input[::-1]
    )[::-1]

which will give you

[Object(name='fake_name'), Object(name='')]

One thing to be aware of: in order for this to work with arbitrary objects, those objects must properly implement __eq__ and __hash__ as explained here.

Creating an array from a text file in Bash

Use mapfile or read -a

Always check your code using shellcheck. It will often give you the correct answer. In this case SC2207 covers reading a file that either has space separated or newline separated values into an array.

Don't do this

array=( $(mycommand) )

Files with values separated by newlines

mapfile -t array < <(mycommand)

Files with values separated by spaces

IFS=" " read -r -a array <<< "$(mycommand)"

The shellcheck page will give you the rationale why this is considered best practice.

Java array assignment (multiple values)

You may use a local variable, like:

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

What does the keyword Set actually do in VBA?

From MSDN:

Set Keyword: In VBA, the Set keyword is necessary to distinguish between assignment of an object and assignment of the default property of the object. Since default properties are not supported in Visual Basic .NET, the Set keyword is not needed and is no longer supported.

JavaScript OR (||) variable assignment explanation

Javascript variables are not typed, so f can be assigned an integer value even though it's been assigned through boolean operators.

f is assigned the nearest value that is not equivalent to false. So 0, false, null, undefined, are all passed over:

alert(null || undefined || false || '' || 0 || 4 || 'bar'); // alerts '4'

Expression must be a modifiable L-value

lvalue means "left value" -- it should be assignable. You cannot change the value of text since it is an array, not a pointer.

Either declare it as char pointer (in this case it's better to declare it as const char*):

const char *text;
if(number == 2) 
    text = "awesome"; 
else 
    text = "you fail";

Or use strcpy:

char text[60];
if(number == 2) 
    strcpy(text, "awesome"); 
else 
    strcpy(text, "you fail");

How do I copy the contents of one ArrayList into another?

You need to clone() the individual object. Constructor and other methods perform shallow copy. You may try Collections.copy method.

Saving a select count(*) value to an integer (SQL Server)

If @myInt is zero it means no rows in the table: it would be NULL if never set at all.

COUNT will always return a row, even for no rows in a table.

Edit, Apr 2012: the rules for this are described in my answer here:Does COUNT(*) always return a result?

Your count/assign is correct but could be either way:

select @myInt = COUNT(*) from myTable
set @myInt = (select COUNT(*) from myTable)

However, if you are just looking for the existence of rows, (NOT) EXISTS is more efficient:

IF NOT EXISTS (SELECT * FROM myTable)

How to assign from a function which returns more than one value?

(1) list[...]<- I had posted this over a decade ago on r-help. Since then it has been added to the gsubfn package. It does not require a special operator but does require that the left hand side be written using list[...] like this:

library(gsubfn)  # need 0.7-0 or later
list[a, b] <- functionReturningTwoValues()

If you only need the first or second component these all work too:

list[a] <- functionReturningTwoValues()
list[a, ] <- functionReturningTwoValues()
list[, b] <- functionReturningTwoValues()

(Of course, if you only needed one value then functionReturningTwoValues()[[1]] or functionReturningTwoValues()[[2]] would be sufficient.)

See the cited r-help thread for more examples.

(2) with If the intent is merely to combine the multiple values subsequently and the return values are named then a simple alternative is to use with :

myfun <- function() list(a = 1, b = 2)

list[a, b] <- myfun()
a + b

# same
with(myfun(), a + b)

(3) attach Another alternative is attach:

attach(myfun())
a + b

ADDED: with and attach

Shortest way to check for null and assign another value if not

You are looking for the C# coalesce operator: ??. This operator takes a left and right argument. If the left hand side of the operator is null or a nullable with no value it will return the right argument. Otherwise it will return the left.

var x = somePossiblyNullValue ?? valueIfNull;

Command not found error in Bash variable assignment

In the interactive mode everything looks fine:

$ str="Hello World"
$ echo $str
Hello World

Obviously(!) as Johannes said, no space around =. In case there is any space around = then in the interactive mode it gives errors as

No command 'str' found

Set variable in jinja

{{ }} tells the template to print the value, this won't work in expressions like you're trying to do. Instead, use the {% set %} template tag and then assign the value the same way you would in normal python code.

{% set testing = 'it worked' %}
{% set another = testing %}
{{ another }}

Result:

it worked

Why does foo = filter(...) return a <filter object>, not a list?

Have a look at the python documentation for filter(function, iterable) (from here):

Construct an iterator from those elements of iterable for which function returns true.

So in order to get a list back you have to use list class:

shesaid = list(filter(greetings(), ["hello", "goodbye"]))

But this probably isn't what you wanted, because it tries to call the result of greetings(), which is "hello", on the values of your input list, and this won't work. Here also the iterator type comes into play, because the results aren't generated until you use them (for example by calling list() on it). So at first you won't get an error, but when you try to do something with shesaid it will stop working:

>>> print(list(shesaid))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

If you want to check which elements in your list are equal to "hello" you have to use something like this:

shesaid = list(filter(lambda x: x == "hello", ["hello", "goodbye"]))

(I put your function into a lambda, see Randy C's answer for a "normal" function)

Initialization of all elements of an array to one default value in C++?

C++11 has another (imperfect) option:

std::array<int, 100> a;
a.fill(-1);

Multiple left-hand assignment with JavaScript

coffee-script can accomplish this with aplomb..

for x in [ 'a', 'b', 'c' ] then "#{x}" : true

[ { a: true }, { b: true }, { c: true } ]

How to force DNS refresh for a website?

If both of your servers are using WHM, I think we can reduce the time to nil. Create your domain in the new server and set everything ready. Go to the previous server and delete the account corresponding to that domain. Until now I have got no errors by doing this and felt the update instantaneous. FYI I used hostgator hosting (both dedicated servers). And I really dont know why it is so. It's supposed to be not like that until the TTL is over.

Pass multiple arguments into std::thread

You literally just pass them in std::thread(func1,a,b,c,d); that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminate is called. You could std::join or std::detach it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach .

This is how it should be done.

std::thread t(func1,a,b,c,d);
t.join();  

You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.

Is there a constraint that restricts my generic method to numeric types?

This question is a bit of a FAQ one, so I'm posting this as wiki (since I've posted similar before, but this is an older one); anyway...

What version of .NET are you using? If you are using .NET 3.5, then I have a generic operators implementation in MiscUtil (free etc).

This has methods like T Add<T>(T x, T y), and other variants for arithmetic on different types (like DateTime + TimeSpan).

Additionally, this works for all the inbuilt, lifted and bespoke operators, and caches the delegate for performance.

Some additional background on why this is tricky is here.

You may also want to know that dynamic (4.0) sort-of solves this issue indirectly too - i.e.

dynamic x = ..., y = ...
dynamic result = x + y; // does what you expect

How to replace all double quotes to single quotes using jquery?

Use double quote to enclose the quote or escape it.

newTemp = mystring.replace(/"/g, "'");

or

newTemp = mystring.replace(/"/g, '\'');

How do I select an element that has a certain class?

The element.class selector is for styling situations such as this:

<span class="large"> </span>
<p class="large"> </p>

.large {
    font-size:150%; font-weight:bold;
}

p.large {
    color:blue;
}

Both your span and p will be assigned the font-size and font-weight from .large, but the color blue will only be assigned to p.

As others have pointed out, what you're working with is descendant selectors.

Subprocess changing directory

If you want to have cd functionality (assuming shell=True) and still want to change the directory in terms of the Python script, this code will allow 'cd' commands to work.

import subprocess
import os

def cd(cmd):
    #cmd is expected to be something like "cd [place]"
    cmd = cmd + " && pwd" # add the pwd command to run after, this will get our directory after running cd
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # run our new command
    out = p.stdout.read()
    err = p.stderr.read()
    # read our output
    if out != "":
        print(out)
        os.chdir(out[0:len(out) - 1]) # if we did get a directory, go to there while ignoring the newline 
    if err != "":
        print(err) # if that directory doesn't exist, bash/sh/whatever env will complain for us, so we can just use that
    return

iPhone app could not be installed at this time

You can try to publish the application by changing the version of the build. I was also having the same problem and tried the same by just changing tIt may help you too.

Material effect on button with background color

If you are interested in ImageButton you can try this simple thing :

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@android:drawable/ic_button"
    android:background="?attr/selectableItemBackgroundBorderless"
/>

How to create a global variable?

if you want to use it in all of your classes you can use:

public var yourVariable = "something"

if you want to use just in one class you can use :

var yourVariable = "something"

How can git be installed on CENTOS 5.5?

If you are using CentOS the built in yum repositories don't seem to have git included and as such, you will need to add an additional repository to the system. For my servers I found that the Webtatic repository seems to be reasonably up to date and the installation for git will then be as follows:

# Add the repository
rpm -Uvh http://repo.webtatic.com/yum/centos/5/latest.rpm

# Install the latest version of git
yum install --enablerepo=webtatic git-all

To work around Missing Dependency: perl(Git) errors:

yum install --enablerepo=webtatic --disableexcludes=main  git-all

What is the point of WORKDIR on Dockerfile?

You can think of WORKDIR like a cd inside the container (it affects commands that come later in the Dockerfile, like the RUN command). If you removed WORKDIR in your example above, RUN npm install wouldn't work because you would not be in the /usr/src/app directory inside your container.

I don't see how this would be related to where you put your Dockerfile (since your Dockerfile location on the host machine has nothing to do with the pwd inside the container). You can put the Dockerfile wherever you'd like in your project. However, the first argument to COPY is a relative path, so if you move your Dockerfile you may need to update those COPY commands.

How to parse a JSON Input stream

use jackson to convert json input stream to the map or object http://jackson.codehaus.org/

there are also some other usefull libraries for json, you can google: json java

Getting only Month and Year from SQL DATE

This can be helpful as well.

SELECT YEAR(0), MONTH(0), DAY(0);

or

SELECT YEAR(getdate()), MONTH(getdate()), DAY(getdate());

or

SELECT YEAR(yourDateField), MONTH(yourDateField), DAY(yourDateField);

How can I get the current directory name in Javascript?

This will work for actual paths on the file system if you're not talking the URL string.

var path = document.location.pathname;
var directory = path.substring(path.indexOf('/'), path.lastIndexOf('/'));

How to detect READ_COMMITTED_SNAPSHOT is enabled?

Neither on SQL2005 nor 2012 does DBCC USEROPTIONS show is_read_committed_snapshot_on:

Set Option  Value
textsize    2147483647
language    us_english
dateformat  mdy
datefirst   7
lock_timeout    -1
quoted_identifier   SET
arithabort  SET
ansi_null_dflt_on   SET
ansi_warnings   SET
ansi_padding    SET
ansi_nulls  SET
concat_null_yields_null SET
isolation level read committed

How to write JUnit test with Spring Autowire?

You should make another XML-spring configuration file in your test resource folder or just copy the old one, it looks fine, but if you're trying to start a web context for testing a micro service, just put the following code as your master test class and inherits from that:

@WebAppConfiguration
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "classpath*:spring-test-config.xml")
public abstract class AbstractRestTest {
    @Autowired
    private WebApplicationContext wac;
}

How to pick an image from gallery (SD Card) for my app?

For some reasons, all of the answers in this thread, in onActivityResult() try to post-process the received Uri, like getting the real path of the image and then use BitmapFactory.decodeFile(path) to get the Bitmap.

This step is unnecessary. The ImageView class has a method called setImageURI(uri). Pass your uri to it and you should be done.

Uri imageUri = data.getData();
imageView.setImageURI(imageUri);

For a complete working example you could take a look here: http://androidbitmaps.blogspot.com/2015/04/loading-images-in-android-part-iii-pick.html

PS:
Getting the Bitmap in a separate variable would make sense in cases where the image to be loaded is too large to fit in memory, and a scale down operation is necessary to prevent OurOfMemoryError, like shown in the @siamii answer.

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

I got this error: "Source option 5 is no longer supported. Use 6 or later" after I changed the pom.xml

<java.version>7</java.version>

to

<java.version>11</java.version>

Later to realise the property was used with a dash insteal of a dot:

  <source>${java-version}</source>
  <target>${java-version}</target>

(swearings), I replaced the dot with a dash and the error went away:

<java-version>11</javaversion>

Oracle's default date format is YYYY-MM-DD, WHY?

Most of the IDE you can configure the default mask for some kind of data as date, currency, decimal separator, etc.

If your are using Oracle SQL Developer:

Tool > Preferences > Database > NLS

Date Format: YYYY-MM-DD HH24:MI:SS

How do you install and run Mocha, the Node.js testing module? Getting "mocha: command not found" after install

since npm 5.2.0, there's a new command "npx" included with npm that makes this much simpler, if you run:

npx mocha <args>

Note: the optional args are forwarded to the command being executed (mocha in this case)

this will automatically pick the executable "mocha" command from your locally installed mocha (always add it as a dev dependency to ensure the correct one is always used by you and everyone else).

Be careful though that if you didn't install mocha, this command will automatically fetch and use latest version, which is great for some tools (like scaffolders for example), but might not be the most recommendable for certain dependencies where you might want to pin to a specific version.

You can read more on npx here


Now, if instead of invoking mocha directly, you want to define a custom npm script, an alias that might invoke other npm binaries...

you don't want your library tests to fail depending on the machine setup (mocha as global, global mocha version, etc), the way to use the local mocha that works cross-platform is:

node node_modules/.bin/mocha

npm puts aliases to all the binaries in your dependencies on that special folder. Finally, npm will add node_modules/.bin to the PATH automatically when running an npm script, so in your package.json you can do just:

"scripts": {
  "test": "mocha"
}

and invoke it with

npm test

Visual Studio Code open tab in new window

When I want to split the screens I usually do one of the following:

  1. open new window with: Ctrl+Shift+N
    and after that I drag the current file I want to the new window.
  2. on the File explorer - I hit Ctrl+Enter on the file I want - and then this file and the other file open together in the same screen but in split mode, so you can see the two files together. If the screen is wide enough this is not a bad solution at all that you can get used to.

How can I get Android Wifi Scan Results into a list?

Try this code

public class WiFiDemo extends Activity implements OnClickListener
 {      
    WifiManager wifi;       
    ListView lv;
    TextView textStatus;
    Button buttonScan;
    int size = 0;
    List<ScanResult> results;

    String ITEM_KEY = "key";
    ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
    SimpleAdapter adapter;

    /* Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        textStatus = (TextView) findViewById(R.id.textStatus);
        buttonScan = (Button) findViewById(R.id.buttonScan);
        buttonScan.setOnClickListener(this);
        lv = (ListView)findViewById(R.id.list);

        wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifi.isWifiEnabled() == false)
        {
            Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
            wifi.setWifiEnabled(true);
        }   
        this.adapter = new SimpleAdapter(WiFiDemo.this, arraylist, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value });
        lv.setAdapter(this.adapter);

        registerReceiver(new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context c, Intent intent) 
            {
               results = wifi.getScanResults();
               size = results.size();
            }
        }, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));                    
    }

    public void onClick(View view) 
    {
        arraylist.clear();          
        wifi.startScan();

        Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
        try 
        {
            size = size - 1;
            while (size >= 0) 
            {   
                HashMap<String, String> item = new HashMap<String, String>();                       
                item.put(ITEM_KEY, results.get(size).SSID + "  " + results.get(size).capabilities);

                arraylist.add(item);
                size--;
                adapter.notifyDataSetChanged();                 
            } 
        }
        catch (Exception e)
        { }         
    }    
}

WiFiDemo.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textStatus"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Status" />

        <Button
            android:id="@+id/buttonScan"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:text="Scan" />
    </LinearLayout>

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="20dp"></ListView>
</LinearLayout>

For ListView- row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="8dp">

    <TextView
        android:id="@+id/list_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="14dp" />
</LinearLayout>

Add these permission in AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

SELECT inside a COUNT

SELECT a AS current_a, COUNT(*) AS b,
   (SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d
   from t group by a order by b desc

C++ passing an array pointer as a function argument

You do not need to take a pointer to the array in order to pass it to an array-generating function, because arrays already decay to pointers when you pass them to functions. Simply make the parameter int a[], and use it as a regular array inside the function, the changes will be made to the array that you have passed in.

void generateArray(int a[],  int si) {
    srand(time(0));
    for (int j=0;j<*si;j++)
        a[j]=(0+rand()%9);
}

int main(){
    const int size=5;
    int a[size];
    generateArray(a, size);
    return 0;
}

As a side note, you do not need to pass the size by pointer, because you are not changing it inside the function. Moreover, it is not a good idea to pass a pointer to constant to a parameter that expects a pointer to non-constant.

Sending mail attachment using Java

To send html file I have used below code in my project.

final String userID = "[email protected]";
final String userPass = "userpass";
final String emailTo = "[email protected]"

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");

Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userID, userPass);
            }
        });
try {

    Message message = new MimeMessage(session);
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailTo));
    message.setSubject("Hello, this is a test mail..");

    Multipart multipart = new MimeMultipart();
    String fileName = "fileName";

    addAttachment(multipart, fileName);

    MimeBodyPart messageBodyPart1 = new MimeBodyPart();
    messageBodyPart1.setText("No need to reply.");
    multipart.addBodyPart(messageBodyPart1);

    message.setContent(multipart);

    Transport.send(message);
    System.out.println("Email successfully sent to: " + emailTo);

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



private static void addAttachment(Multipart multipart, String fileName){
    DataSource source = null;
    File f = new File("filepath" +"/"+ fileName);
    if(f.exists() && !f.isDirectory()) {
        source = new FileDataSource("filepath" +"/"+ fileName);
        BodyPart messageBodyPart = new MimeBodyPart();
        try {
            messageBodyPart.setHeader("Content-Type", "text/html");
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

How to change an image on click using CSS alone?

You could use an <a> tag with different styles:

a:link    { }
a:visited { }
a:hover   { }
a:active  { }

I'd recommend using that in conjunction with CSS sprites: https://css-tricks.com/css-sprites/

Gridview row editing - dynamic binding to a DropDownList

Quite easy... You're doing it wrong, because by that event the control is not there:

protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow && 
        (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
    { 
        // Here you will get the Control you need like:
        DropDownList dl = (DropDownList)e.Row.FindControl("ddlPBXTypeNS");
    }
}

That is, it will only be valid for a DataRow (the actually row with data), and if it's in Edit mode... because you only edit one row at a time. The e.Row.FindControl("ddlPBXTypeNS") will only find the control that you want.

PuTTY Connection Manager download?

PuTTY Session Manager is a tool that allows system administrators to organise their PuTTY sessions into folders and assign hotkeys to favourite sessions. Multiple sessions can be launched with one click. Requires MS Windows and the .NET 2.0 Runtime.

http://sourceforge.net/projects/puttysm/

Convert datatable to JSON in C#

Convert datatable to JSON using C#.net

 public static object DataTableToJSON(DataTable table)
    {
        var list = new List<Dictionary<string, object>>();

        foreach (DataRow row in table.Rows)
        {
            var dict = new Dictionary<string, object>();

            foreach (DataColumn col in table.Columns)
            {
                dict[col.ColumnName] = (Convert.ToString(row[col]));
            }
            list.Add(dict);
        }
        JavaScriptSerializer serializer = new JavaScriptSerializer();

        return serializer.Serialize(list);
    }

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

Get last n lines of a file, similar to tail

Several of these solutions have issues if the file doesn't end in \n or in ensuring the complete first line is read.

def tail(file, n=1, bs=1024):
    f = open(file)
    f.seek(-1,2)
    l = 1-f.read(1).count('\n') # If file doesn't end in \n, count it anyway.
    B = f.tell()
    while n >= l and B > 0:
            block = min(bs, B)
            B -= block
            f.seek(B, 0)
            l += f.read(block).count('\n')
    f.seek(B, 0)
    l = min(l,n) # discard first (incomplete) line if l > n
    lines = f.readlines()[-l:]
    f.close()
    return lines

MySQL: ERROR 1227 (42000): Access denied - Cannot CREATE USER

First thing to do is run this:

SHOW GRANTS;

You will quickly see you were assigned the anonymous user to authenticate into mysql.

Instead of logging into mysql with

mysql

login like this:

mysql -uroot

By default, root@localhost has all rights and no password.

If you cannot login as root without a password, do the following:

Step 01) Add the two options in the mysqld section of my.ini:

[mysqld]
skip-grant-tables
skip-networking

Step 02) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 03) Connect to mysql

mysql

Step 04) Create a password from root@localhost

UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit

Step 05) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 06) Login as root with password

mysql -u root -p

You should be good from there.

CAVEAT: Please remove anonymous users !!!

size of uint8, uint16 and uint32?

uint8, uint16, uint32, and uint64 are probably Microsoft-specific types.

As of the 1999 standard, C supports standard typedefs with similar meanings, defined in <stdint.h>: uint8_t, uint16_t, uint32_t, and uint64_t. I'll assume that the Microsoft-specific types are defined similarly. Microsoft does support <stdint.h>, at least as of Visual Studio 2010, but older code may use uint8 et al.

The predefined types char, short, int et al have sizes that vary from one C implementation to another. The C standard has certain minimum requirements (char is at least 8 bits, short and int are at least 16, long is at least 32, and each type in that list is at least as wide as the previous type), but permits some flexibility. For example, I've seen systems where int is 16, 32, or 64 bits.

char is almost always exactly 8 bits, but it's permitted to be wider. And plain char may be either signed or unsigned.

uint8_t is required to be an unsigned integer type that's exactly 8 bits wide. It's likely to be a typedef for unsigned char, though it might be a typedef for plain char if plain char happens to be unsigned. If there is no predefined 8-bit unsigned type, then uint8_t will not be defined at all.

Similarly, each uintN_t type is an unsigned type that's exactly N bits wide.

In addition, <stdint.h> defines corresponding signed intN_t types, as well as int_fastN_t and int_leastN_t types that are at least the specified width.

The [u]intN_t types are guaranteed to have no padding bits, so the size of each is exactly N bits. The signed intN_t types are required to use a 2's-complement representation.

Although uint32_t might be the same as unsigned int, for example, you shouldn't assume that. Use unsigned int when you need an unsigned integer type that's at least 16 bits wide, and that's the "natural" size for the current system. Use uint32_t when you need an unsigned integer type that's exactly 32 bits wide.

(And no, uint64 or uint64_t is not the same as double; double is a floating-point type.)

What is the proper way to check if a string is empty in Perl?

As already mentioned by several people, eq is the right operator here.

If you use warnings; in your script, you'll get warnings about this (and many other useful things); I'd recommend use strict; as well.

Is there a way to link someone to a YouTube Video in HD 1080p quality?

To link to a YouTube video so it plays in HD by default, use the following URL:

https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080

Change VIDEOID to the YouTube video ID that you want to link to. When someone follows the link, it will display the highest-resolution available (up to 1080p) in full-screen mode. Unfortunately, vq=hd1080 does not work on the normal YouTube site (with comments and related videos).

Firebase cloud messaging notification not received by device

private void sendNotification(String message) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    int requestCode = 0;
    PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.URI_COLUMN_INDEX);
    NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentText(message)
            .setColor(getResources().getColor(R.color.colorPrimaryDark))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("FCM Message")
            .setContentText("hello").setLargeIcon(((BitmapDrawable) getResources().getDrawable(R.drawable.dog)).getBitmap())
            .setStyle(new NotificationCompat.BigPictureStyle()
                    .bigPicture(((BitmapDrawable) getResources().getDrawable(R.drawable.dog)).getBitmap()))
            .setAutoCancel(true)
            .setSound(sound)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, noBuilder.build());

SQlite - Android - Foreign key syntax

Since I cannot comment, adding this note in addition to @jethro answer.

I found out that you also need to do the FOREIGN KEY line as the last part of create the table statement, otherwise you will get a syntax error when installing your app. What I mean is, you cannot do something like this:

private static final String TASK_TABLE_CREATE = "create table "
    + TASK_TABLE + " (" + TASK_ID
    + " integer primary key autoincrement, " + TASK_TITLE
    + " text not null, " + TASK_NOTES + " text not null, "
+ TASK_CAT + " integer,"
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+" ("+CAT_ID+"), "
+ TASK_DATE_TIME + " text not null);";

Where I put the TASK_DATE_TIME after the foreign key line.

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

Update

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

How to create a string with format?

I think this could help you:

let timeNow = time(nil)
let aStr = String(format: "%@%x", "timeNow in hex: ", timeNow)
print(aStr)

Example result:

timeNow in hex: 5cdc9c8d

Postgres integer arrays as parameters?

You can always use a properly formatted string. The trick is the formatting.

command.Parameters.Add("@array_parameter", string.Format("{{{0}}}", string.Join(",", array));

Note that if your array is an array of strings, then you'll need to use array.Select(value => string.Format("\"{0}\", value)) or the equivalent. I use this style for an array of an enumerated type in PostgreSQL, because there's no automatic conversion from the array.

In my case, my enumerated type has some values like 'value1', 'value2', 'value3', and my C# enumeration has matching values. In my case, the final SQL query ends up looking something like (E'{"value1","value2"}'), and this works.

C#/Linq: Apply a mapping function to each element in an IEnumerable?

You're looking for Select which can be used to transform\project the input sequence:

IEnumerable<string> strings = integers.Select(i => i.ToString());

Difference between Big-O and Little-O Notation

The big-O notation has a companion called small-o notation. The big-O notation says the one function is asymptotical no more than another. To say that one function is asymptotically less than another, we use small-o notation. The difference between the big-O and small-o notations is analogous to the difference between <= (less than equal) and < (less than).

javascript: pause setTimeout();

If anyone wants the TypeScript version shared by the Honorable @SeanVieira here, you can use this:

    public timer(fn: (...args: any[]) => void, countdown: number): { onCancel: () => void, onPause: () => void, onResume: () => void } {
        let ident: NodeJS.Timeout | number;
        let complete = false;
        let totalTimeRun: number;
        const onTimeDiff = (date1: number, date2: number) => {
            return date2 ? date2 - date1 : new Date().getTime() - date1;
        };

        const handlers = {
            onCancel: () => {
                clearTimeout(ident as NodeJS.Timeout);
            },
            onPause: () => {
                clearTimeout(ident as NodeJS.Timeout);
                totalTimeRun = onTimeDiff(startTime, null);
                complete = totalTimeRun >= countdown;
            },
            onResume: () => {
                ident = complete ? -1 : setTimeout(fn, countdown - totalTimeRun);
            }
        };

        const startTime = new Date().getTime();
        ident = setTimeout(fn, countdown);

        return handlers;
    }

How to display special characters in PHP

In PHP there is a pretty good function utf8_encode() to solve this issue.

echo utf8_encode("Résumé");

//will output Résumé instead of R?sum?

Check the official PHP page.

How to sort a data frame by date

You can use order() to sort date data.

# Sort date ascending order
d[order(as.Date(d$V3, format = "%d/%m/%Y")),]

# Sort date descending order
d[rev(order(as.Date(d$V3, format = "%d/%m/%y"))),]

Hope this helps,

Link to my quora answer https://qr.ae/TWngCe

Thanks

How to recursively list all the files in a directory in C#?

private void GetFiles(DirectoryInfo dir, ref List<FileInfo> files)
{
    try
    {
        files.AddRange(dir.GetFiles());
        DirectoryInfo[] dirs = dir.GetDirectories();
        foreach (var d in dirs)
        {
            GetFiles(d, ref files);
        }
    }
    catch (Exception e)
    {

    }
}

Unzip files (7-zip) via cmd command

make sure that your path is pointing to .exe file in C:\Program Files\7-Zip (may in bin directory)

How to force Selenium WebDriver to click on element which is not currently visible?

Sometimes this means there are multiple elements on a page that have the same property you're trying to search by and you're "talking to the wrong one".

If your element can't be uniquely identified by :id or :name (or :class), it could be tricky.

Sometimes searching for the element by the :xpath will help and in some cases even that is not practical.

In those cases, you may have to get all the elements that match your criteria and reference the right one by the index. It's dirty, but it works.

I'm using Selenium / Watir from Ruby on Rails app, so in my case the example would be:

browser = Watir::Browser.new(:firefox, :profile => "default")       
browser.goto("http://www.google.com/analytics")
# login
browser.divs(:text, "+ New Property").last.click

Hope this helps.

Return multiple values in JavaScript?

Another worth to mention newly introduced (ES6) syntax is use of object creation shorthand in addition to destructing assignment.

function fun1() {
  var x = 'a';
  var y = 'b';
  return { x, y, z: 'c' };
  // literally means { x: x, y: y, z: 'c' };
}

var { z, x, y } = fun1(); // order or full presence is not really important
// literally means var r = fun1(), x = r.x, y = r.y, z = r.z;
console.log(x, y, z);

This syntax can be polyfilled with babel or other js polyfiller for older browsers but fortunately now works natively with the recent versions of Chrome and Firefox.

But as making a new object, memory allocation (and eventual gc load) are involved here, don't expect much performance from it. JavaScript is not best language for developing highly optimal things anyways but if that is needed, you can consider putting your result on surrounding object or such techniques which are usually common performance tricks between JavaScript, Java and other languages.

How do I print the full value of a long string in gdb?

Using set elements ... isn't always the best way. It would be useful if there were a distinct set string-elements ....

So, I use these functions in my .gdbinit:

define pstr
  ptype $arg0._M_dataplus._M_p
  printf "[%d] = %s\n", $arg0._M_string_length, $arg0._M_dataplus._M_p
end

define pcstr
  ptype $arg0
  printf "[%d] = %s\n", strlen($arg0), $arg0
end

Caveats:

  • The first is c++ lib dependent as it accesses members of std::string, but is easily adjusted.
  • The second can only be used on a running program as it calls strlen.

Boolean operators && and ||

The answer about "short-circuiting" is potentially misleading, but has some truth (see below). In the R/S language, && and || only evaluate the first element in the first argument. All other elements in a vector or list are ignored regardless of the first ones value. Those operators are designed to work with the if (cond) {} else{} construction and to direct program control rather than construct new vectors.. The & and the | operators are designed to work on vectors, so they will be applied "in parallel", so to speak, along the length of the longest argument. Both vectors need to be evaluated before the comparisons are made. If the vectors are not the same length, then recycling of the shorter argument is performed.

When the arguments to && or || are evaluated, there is "short-circuiting" in that if any of the values in succession from left to right are determinative, then evaluations cease and the final value is returned.

> if( print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(FALSE && print(1) ) {print(2)} else {print(3)} # `print(1)` not evaluated
[1] 3
> if(TRUE && print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(TRUE && !print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 3
> if(FALSE && !print(1) ) {print(2)} else {print(3)}
[1] 3

The advantage of short-circuiting will only appear when the arguments take a long time to evaluate. That will typically occur when the arguments are functions that either process larger objects or have mathematical operations that are more complex.

$("#form1").validate is not a function

I had the same issue, and yes I had my jquery included first followed by the jquery validate script. I had no idea what was wrong. Turns out I was using a validate url that had moved. I figured this out by doing the following:

  1. Open firefox
  2. Open firebug
  3. Click the NET tab in firebug. This will show you all the resources that get loaded.
  4. Load your page.
  5. Check the loaded resources and see if both your jquery & jquery.validate.js loaded.

In my situation I had a 403 Forbidden error when trying to obtain (http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js which is used in the example on http://rocketsquared.com/wiki/Plugins/Validation ).

Turns out the that link (http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js) had moved to http://view.jquery.com/trunk/plugins/validate/jquery.validate.js (Firebug told me this when I loaded the file locally as opposed to on my web server).

NOTE: I tried using microsoft's CDN link also but it failed when I tried to load the javascript file in the browser with the correct url, there was some odd issue going on with the CDN site.

Angularjs: Error: [ng:areq] Argument 'HomeController' is not a function, got undefined

I got the same error. I defined java script like this

<script src="controllers/home.js" />

then I changed to the this

<script src="controllers/home.js"></script>

After this my problem is solved.

How to print a list in Python "nicely"

from pprint import pprint
pprint(the_list)

C# if/then directives for debug vs release

Be sure to define the DEBUG constant in the Project Build Properties. This will enable the #if DEBUG. I don't see a pre-defined RELEASE constant, so that could imply that anything Not in a DEBUG block is RELEASE mode.

Define DEBUG constant in Project Build Properties

What is the use of BindingResult interface in spring MVC?

Well its a sequential process. The Request first treat by FrontController and then moves towards our own customize controller with @Controller annotation.

but our controller method is binding bean using modelattribute and we are also performing few validations on bean values.

so instead of moving the request to our controller class, FrontController moves it towards one interceptor which creates the temp object of our bean and the validate the values. if validation successful then bind the temp obj values with our actual bean which is stored in @ModelAttribute otherwise if validation fails it does not bind and moves the resp towards error page or wherever u want.

enter image description here

IndexError: index 1 is out of bounds for axis 0 with size 1/ForwardEuler

The problem, as the Traceback says, comes from the line x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ). Let's replace it in its context:

  • x is an array equal to [x0 * n], so its length is 1
  • you're iterating from 0 to n-2 (n doesn't matter here), and i is the index. In the beginning, everything is ok (here there's no beginning apparently... :( ), but as soon as i + 1 >= len(x) <=> i >= 0, the element x[i+1] doesn't exist. Here, this element doesn't exist since the beginning of the for loop.

To solve this, you must replace x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ) by x.append(x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )).

How can I create an error 404 in PHP?

Immediately after that line try closing the response using exit or die()

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
exit;

or

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
die();

Get DataKey values in GridView RowCommand

I managed to get the value of the DataKeys using this code:

In the GridView I added:

DataKeyNames="ID" OnRowCommand="myRowCommand"

Then in my row command function:

protected void myRowCommand(object sender, GridViewCommandEventArgs e) 
{
    LinkButton lnkBtn = (LinkButton)e.CommandSource;    // the button
    GridViewRow myRow = (GridViewRow)lnkBtn.Parent.Parent;  // the row
    GridView myGrid = (GridView)sender; // the gridview
    string ID = myGrid.DataKeys[myRow.RowIndex].Value.ToString(); // value of the datakey 

    switch (e.CommandName)
    {
      case "cmd1":
      // do something using the ID
      break;
      case "cmd2":
      // do something else using the ID
      break;
    }
 }

CSS vertical alignment text inside li

There are no perfect answers provided here except Asaf's answer which doesn't provide any code nor any example, so I would like to contribute mine...

Inorder to make vertical-align: middle; work, you need to use display: table; for your ul element and display: table-cell; for li elements and than you can use vertical-align: middle; for li elements.

You don't need to provide any explicit margins, paddings to make your text vertically middle.

Demo

ul.catBlock{
    display: table;
    width:960px; 
    height: 270px; 
    border:1px solid #ccc; 
}

ul.catBlock li {
    list-style: none;
    display: table-cell; 
    text-align: center; 
    width:160px; 
    vertical-align: middle;
}

ul.catBlock li a { 
    display: block;
}

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

Answer

You need to create a header with a proper formatted User agent String, it server to communicate client-server.

You can check your own user agent Here.

Example

Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0
Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.0

Third party Package user_agent 0.1.9

I found this module very simple to use, in one line of code it randomly generates a User agent string.

from user_agent import generate_user_agent, generate_navigator
from pprint import pprint

print(generate_user_agent())
# 'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.3; Win64; x64)'

print(generate_user_agent(os=('mac', 'linux')))
# 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:36.0) Gecko/20100101 Firefox/36.0'

pprint(generate_navigator())

# {'app_code_name': 'Mozilla',
#  'app_name': 'Netscape',
#  'appversion': '5.0',
#  'name': 'firefox',
#  'os': 'linux',
#  'oscpu': 'Linux i686 on x86_64',
#  'platform': 'Linux i686 on x86_64',
#  'user_agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686 on x86_64; rv:41.0) Gecko/20100101 Firefox/41.0',
#  'version': '41.0'}

pprint(generate_navigator_js())

# {'appCodeName': 'Mozilla',
#  'appName': 'Netscape',
#  'appVersion': '38.0',
#  'platform': 'MacIntel',
#  'userAgent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:38.0) Gecko/20100101 Firefox/38.0'}

How to copy an object in Objective-C

Apple documentation says

A subclass version of the copyWithZone: method should send the message to super first, to incorporate its implementation, unless the subclass descends directly from NSObject.

to add to the existing answer

@interface YourClass : NSObject <NSCopying> 
{
   SomeOtherObject *obj;
}

// In the implementation
-(id)copyWithZone:(NSZone *)zone
{
  YourClass *another = [super copyWithZone:zone];
  another.obj = [obj copyWithZone: zone];

  return another;
}

Combine multiple Collections into a single logical Collection?

If you're using at least Java 8, see my other answer.

If you're already using Google Guava, see Sean Patrick Floyd's answer.

If you're stuck at Java 7 and don't want to include Google Guava, you can write your own (read-only) Iterables.concat() using no more than Iterable and Iterator:

Constant number

public static <E> Iterable<E> concat(final Iterable<? extends E> iterable1,
                                     final Iterable<? extends E> iterable2) {
    return new Iterable<E>() {
        @Override
        public Iterator<E> iterator() {
            return new Iterator<E>() {
                final Iterator<? extends E> iterator1 = iterable1.iterator();
                final Iterator<? extends E> iterator2 = iterable2.iterator();

                @Override
                public boolean hasNext() {
                    return iterator1.hasNext() || iterator2.hasNext();
                }

                @Override
                public E next() {
                    return iterator1.hasNext() ? iterator1.next() : iterator2.next();
                }
            };
        }
    };
}

Variable number

@SafeVarargs
public static <E> Iterable<E> concat(final Iterable<? extends E>... iterables) {
    return concat(Arrays.asList(iterables));
}

public static <E> Iterable<E> concat(final Iterable<Iterable<? extends E>> iterables) {
    return new Iterable<E>() {
        final Iterator<Iterable<? extends E>> iterablesIterator = iterables.iterator();

        @Override
        public Iterator<E> iterator() {
            return !iterablesIterator.hasNext() ? Collections.emptyIterator()
                                                : new Iterator<E>() {
                Iterator<? extends E> iterableIterator = nextIterator();

                @Override
                public boolean hasNext() {
                    return iterableIterator.hasNext();
                }

                @Override
                public E next() {
                    final E next = iterableIterator.next();
                    findNext();
                    return next;
                }

                Iterator<? extends E> nextIterator() {
                    return iterablesIterator.next().iterator();
                }

                Iterator<E> findNext() {
                    while (!iterableIterator.hasNext()) {
                        if (!iterablesIterator.hasNext()) {
                            break;
                        }
                        iterableIterator = nextIterator();
                    }
                    return this;
                }
            }.findNext();
        }
    };
}

Text size of android design TabLayout tabs

Do as following.

1. Add the Style to the XML

    <style name="MyTabLayoutTextAppearance" parent="TextAppearance.Design.Tab">
        <item name="android:textSize">14sp</item>
    </style>

2. Apply Style

Find the Layout containing the TabLayout and add the style. The added line is bold.

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        app:tabTextAppearance="@style/MyTabLayoutTextAppearance" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

Facebook Like-Button - hide count?

All you need to do is edit the iframe code that facebook gives you and change the width to 47 (you need to change it in 2 places). Seems to work perfectly for me so far.

Can I run multiple versions of Google Chrome on the same machine? (Mac or Windows)

In the comments, I mentioned a step-by-step method to easily install multiple Chrome versions, side-by-side. This answer quotes my original answer, and includes a script which does the job for you.

Quoted from: section 7 of Cross-browser testing: All major browsers on ONE machine:

Chrome: Stand-alone installers can be downloaded from File Hippo. It is also possible to run multiple Chrome versions side-by-side.

Although Sandboxie can be used, it's recommended to use the next native method in order to run multiple versions side-by-side.

  1. Download the desired version(s) from File Hippo.
  2. Create a main directory, e.g. C:\Chrome\.
  3. Extract the installer (=without installing), using 7-Zip for example. After extracting, a chrome.7z archive is created. Also extract this file, and descend the created Chrome-bin directory. Now, you see chrome.exe and a dir like 18.0.1025.45. Move chrome.exe to 18.0.1025.45, then move this directory to C:\Chrome. The remaining files in Chrome-bin can safely be deleted.
  4. Create a shortcut for each version:

    "C:\Chrome\18.0.1024.45\chrome.exe" --user-data-dir="..\User Data\18" --chrome-version=18.0.1025.45
    

    Explanation of this shortcut:

    • "C:\Chrome\18.0.1024.45\chrome.exe" • This is the launcher
    • --user-data-dir="..\User Data\18" • User profile, relative to the location of chrome.exe. You could also have used --user-data-dir="C:\Chrome\User Data\18" for the same effect. Set your preferences for the lowest Chrome version, and duplicate the User profile for each Chrome version. Older Chrome versions refuse to use User profiles from new versions.
    • --chrome-version=18.0.1025.45Location of binaries:
      • The location (eg 18.0.1025.45) must be the name of the directory:
      • Must start and end with a number. A dot may appear in between.
      • The numbers do not necessarily have to match the real version number (though it's convenient to use real version numbers...).

Regarding configuration: All preferences can be set at chrome://settings/. I usually change the home page and "Under the hood" settings.

(the old version of this answer referred to Old Apps for old Chrome versions, but they do not offer direct download links any more through the UI. The files do still exist, I've created a shell script (bash) to ease the creation of a local repository of Chrome versions - see https://gist.github.com/Rob--W/8577499)

VB Script which automates install, config & launch

I've created a VB script which installs and configures Chrome (tested in XP and Win 7). Launch the script, and a file dialog appears (or: Drag & drop the chrome installer on the VBS). Select the destination of the Chrome installer, and the script automatically unpacks the files and duplicates the profile from a pre-configured base directory.

By default:

  1. The Chrome binaries are placed in subfolders of C:\Chrome\.
  2. The User profiles are created in C:\Chrome\User Data\.
  3. The user profiles will be duplicated from the directory as specified in the sFolderChromeUserDataDefault variable, which is C:\Chrome\User Data\2\ by default.
    After the first Chrome installation, set your preferences (Home page, bookmarks, ..). Then modify the variable (see 3.) in the source code. After that, installing and configuring Chrome is as easy as pie.

The only dependency is 7-zip, expected to be located at C:\Program Files\7-zip\7z.exe.

How can I install an older version of a package via NuGet?

Now, it's very much simplified in Visual Studio 2015 and later. You can do downgrade / upgrade within the User interface itself, without executing commands in the Package Manager Console.

  1. Right click on your project and *go to Manage NuGet Packages.

  2. Look at the below image.

    • Select your Package and Choose the Version, which you wanted to install.

NuGet Package Manager window of Project

Very very simple, isn't it? :)

How to access your website through LAN in ASP.NET

I'm not sure how stuck you are:

You must have a web server (Windows comes with one called IIS, but it may not be installed)

  1. Make sure you actually have IIS installed! Try typing http://localhost/ in your browser and see what happens. If nothing happens it means that you may not have IIS installed. See Installing IIS
  2. Set up IIS How to set up your first IIS Web site
  3. You may even need to Install the .NET Framework (or your server will only serve static html pages, and not asp.net pages)

Installing your application

Once you have done that, you can more or less just copy your application to c:\wwwroot\inetpub\. Read Installing ASP.NET Applications (IIS 6.0) for more information

Accessing the web site from another machine

In theory, once you have a web server running, and the application installed, you only need the IP address of your web server to access the application.

To find your IP address try: Start -> Run -> type cmd (hit ENTER) -> type ipconfig (hit ENTER)

Once

  • you have the IP address AND
  • IIS running AND
  • the application is installed

you can access your website from another machine in your LAN by just typing in the IP Address of you web server and the correct path to your application.

If you put your application in a directory called NewApp, you will need to type something like http://your_ip_address/NewApp/default.aspx

Turn off your firewall

If you do have a firewall turn it off while you try connecting for the first time, you can sort that out later.

What is the list of supported languages/locales on Android?

Updated list as of Android 5.1:

af_ [Afrikaans]
af_NA [Afrikaans (Namibia)]
af_ZA [Afrikaans (South Africa)]
agq_ [Aghem]
agq_CM [Aghem (Cameroon)]
ak_ [Akan]
ak_GH [Akan (Ghana)]
am_ [Amharic]
am_ET [Amharic (Ethiopia)]
ar_ [Arabic]
ar_001 [Arabic (World)]
ar_AE [Arabic (United Arab Emirates)]
ar_BH [Arabic (Bahrain)]
ar_DJ [Arabic (Djibouti)]
ar_DZ [Arabic (Algeria)]
ar_EG [Arabic (Egypt)]
ar_EH [Arabic (Western Sahara)]
ar_ER [Arabic (Eritrea)]
ar_IL [Arabic (Israel)]
ar_IQ [Arabic (Iraq)]
ar_JO [Arabic (Jordan)]
ar_KM [Arabic (Comoros)]
ar_KW [Arabic (Kuwait)]
ar_LB [Arabic (Lebanon)]
ar_LY [Arabic (Libya)]
ar_MA [Arabic (Morocco)]
ar_MR [Arabic (Mauritania)]
ar_OM [Arabic (Oman)]
ar_PS [Arabic (Palestine)]
ar_QA [Arabic (Qatar)]
ar_SA [Arabic (Saudi Arabia)]
ar_SD [Arabic (Sudan)]
ar_SO [Arabic (Somalia)]
ar_SS [Arabic (South Sudan)]
ar_SY [Arabic (Syria)]
ar_TD [Arabic (Chad)]
ar_TN [Arabic (Tunisia)]
ar_YE [Arabic (Yemen)]
as_ [Assamese]
as_IN [Assamese (India)]
asa_ [Asu]
asa_TZ [Asu (Tanzania)]
az_ [Azerbaijani]
az_ [Azerbaijani (Cyrillic)]
az_AZ [Azerbaijani (Cyrillic,Azerbaijan)]
az_ [Azerbaijani (Latin)]
az_AZ [Azerbaijani (Latin,Azerbaijan)]
bas_ [Basaa]
bas_CM [Basaa (Cameroon)]
be_ [Belarusian]
be_BY [Belarusian (Belarus)]
bem_ [Bemba]
bem_ZM [Bemba (Zambia)]
bez_ [Bena]
bez_TZ [Bena (Tanzania)]
bg_ [Bulgarian]
bg_BG [Bulgarian (Bulgaria)]
bm_ [Bambara]
bm_ML [Bambara (Mali)]
bn_ [Bengali]
bn_BD [Bengali (Bangladesh)]
bn_IN [Bengali (India)]
bo_ [Tibetan]
bo_CN [Tibetan (China)]
bo_IN [Tibetan (India)]
br_ [Breton]
br_FR [Breton (France)]
brx_ [Bodo]
brx_IN [Bodo (India)]
bs_ [Bosnian]
bs_ [Bosnian (Cyrillic)]
bs_BA [Bosnian (Cyrillic,Bosnia and Herzegovina)]
bs_ [Bosnian (Latin)]
bs_BA [Bosnian (Latin,Bosnia and Herzegovina)]
ca_ [Catalan]
ca_AD [Catalan (Andorra)]
ca_ES [Catalan (Spain)]
ca_FR [Catalan (France)]
ca_IT [Catalan (Italy)]
cgg_ [Chiga]
cgg_UG [Chiga (Uganda)]
chr_ [Cherokee]
chr_US [Cherokee (United States)]
cs_ [Czech]
cs_CZ [Czech (Czech Republic)]
cy_ [Welsh]
cy_GB [Welsh (United Kingdom)]
da_ [Danish]
da_DK [Danish (Denmark)]
da_GL [Danish (Greenland)]
dav_ [Taita]
dav_KE [Taita (Kenya)]
de_ [German]
de_AT [German (Austria)]
de_BE [German (Belgium)]
de_CH [German (Switzerland)]
de_DE [German (Germany)]
de_LI [German (Liechtenstein)]
de_LU [German (Luxembourg)]
dje_ [Zarma]
dje_NE [Zarma (Niger)]
dua_ [Duala]
dua_CM [Duala (Cameroon)]
dyo_ [Jola-Fonyi]
dyo_SN [Jola-Fonyi (Senegal)]
dz_ [Dzongkha]
dz_BT [Dzongkha (Bhutan)]
ebu_ [Embu]
ebu_KE [Embu (Kenya)]
ee_ [Ewe]
ee_GH [Ewe (Ghana)]
ee_TG [Ewe (Togo)]
el_ [Greek]
el_CY [Greek (Cyprus)]
el_GR [Greek (Greece)]
en_ [English]
en_001 [English (World)]
en_150 [English (Europe)]
en_AG [English (Antigua and Barbuda)]
en_AI [English (Anguilla)]
en_AS [English (American Samoa)]
en_AU [English (Australia)]
en_BB [English (Barbados)]
en_BE [English (Belgium)]
en_BM [English (Bermuda)]
en_BS [English (Bahamas)]
en_BW [English (Botswana)]
en_BZ [English (Belize)]
en_CA [English (Canada)]
en_CC [English (Cocos (Keeling) Islands)]
en_CK [English (Cook Islands)]
en_CM [English (Cameroon)]
en_CX [English (Christmas Island)]
en_DG [English (Diego Garcia)]
en_DM [English (Dominica)]
en_ER [English (Eritrea)]
en_FJ [English (Fiji)]
en_FK [English (Falkland Islands (Islas Malvinas))]
en_FM [English (Micronesia)]
en_GB [English (United Kingdom)]
en_GD [English (Grenada)]
en_GG [English (Guernsey)]
en_GH [English (Ghana)]
en_GI [English (Gibraltar)]
en_GM [English (Gambia)]
en_GU [English (Guam)]
en_GY [English (Guyana)]
en_HK [English (Hong Kong)]
en_IE [English (Ireland)]
en_IM [English (Isle of Man)]
en_IN [English (India)]
en_IO [English (British Indian Ocean Territory)]
en_JE [English (Jersey)]
en_JM [English (Jamaica)]
en_KE [English (Kenya)]
en_KI [English (Kiribati)]
en_KN [English (Saint Kitts and Nevis)]
en_KY [English (Cayman Islands)]
en_LC [English (Saint Lucia)]
en_LR [English (Liberia)]
en_LS [English (Lesotho)]
en_MG [English (Madagascar)]
en_MH [English (Marshall Islands)]
en_MO [English (Macau)]
en_MP [English (Northern Mariana Islands)]
en_MS [English (Montserrat)]
en_MT [English (Malta)]
en_MU [English (Mauritius)]
en_MW [English (Malawi)]
en_NA [English (Namibia)]
en_NF [English (Norfolk Island)]
en_NG [English (Nigeria)]
en_NR [English (Nauru)]
en_NU [English (Niue)]
en_NZ [English (New Zealand)]
en_PG [English (Papua New Guinea)]
en_PH [English (Philippines)]
en_PK [English (Pakistan)]
en_PN [English (Pitcairn Islands)]
en_PR [English (Puerto Rico)]
en_PW [English (Palau)]
en_RW [English (Rwanda)]
en_SB [English (Solomon Islands)]
en_SC [English (Seychelles)]
en_SD [English (Sudan)]
en_SG [English (Singapore)]
en_SH [English (Saint Helena)]
en_SL [English (Sierra Leone)]
en_SS [English (South Sudan)]
en_SX [English (Sint Maarten)]
en_SZ [English (Swaziland)]
en_TC [English (Turks and Caicos Islands)]
en_TK [English (Tokelau)]
en_TO [English (Tonga)]
en_TT [English (Trinidad and Tobago)]
en_TV [English (Tuvalu)]
en_TZ [English (Tanzania)]
en_UG [English (Uganda)]
en_UM [English (U.S. Outlying Islands)]
en_US [English (United States)]
en_US [English (United States,Computer)]
en_VC [English (St. Vincent & Grenadines)]
en_VG [English (British Virgin Islands)]
en_VI [English (U.S. Virgin Islands)]
en_VU [English (Vanuatu)]
en_WS [English (Samoa)]
en_ZA [English (South Africa)]
en_ZM [English (Zambia)]
en_ZW [English (Zimbabwe)]
eo_ [Esperanto]
es_ [Spanish]
es_419 [Spanish (Latin America)]
es_AR [Spanish (Argentina)]
es_BO [Spanish (Bolivia)]
es_CL [Spanish (Chile)]
es_CO [Spanish (Colombia)]
es_CR [Spanish (Costa Rica)]
es_CU [Spanish (Cuba)]
es_DO [Spanish (Dominican Republic)]
es_EA [Spanish (Ceuta and Melilla)]
es_EC [Spanish (Ecuador)]
es_ES [Spanish (Spain)]
es_GQ [Spanish (Equatorial Guinea)]
es_GT [Spanish (Guatemala)]
es_HN [Spanish (Honduras)]
es_IC [Spanish (Canary Islands)]
es_MX [Spanish (Mexico)]
es_NI [Spanish (Nicaragua)]
es_PA [Spanish (Panama)]
es_PE [Spanish (Peru)]
es_PH [Spanish (Philippines)]
es_PR [Spanish (Puerto Rico)]
es_PY [Spanish (Paraguay)]
es_SV [Spanish (El Salvador)]
es_US [Spanish (United States)]
es_UY [Spanish (Uruguay)]
es_VE [Spanish (Venezuela)]
et_ [Estonian]
et_EE [Estonian (Estonia)]
eu_ [Basque]
eu_ES [Basque (Spain)]
ewo_ [Ewondo]
ewo_CM [Ewondo (Cameroon)]
fa_ [Persian]
fa_AF [Persian (Afghanistan)]
fa_IR [Persian (Iran)]
ff_ [Fulah]
ff_SN [Fulah (Senegal)]
fi_ [Finnish]
fi_FI [Finnish (Finland)]
fil_ [Filipino]
fil_PH [Filipino (Philippines)]
fo_ [Faroese]
fo_FO [Faroese (Faroe Islands)]
fr_ [French]
fr_BE [French (Belgium)]
fr_BF [French (Burkina Faso)]
fr_BI [French (Burundi)]
fr_BJ [French (Benin)]
fr_BL [French (Saint Barthélemy)]
fr_CA [French (Canada)]
fr_CD [French (Congo (DRC))]
fr_CF [French (Central African Republic)]
fr_CG [French (Congo (Republic))]
fr_CH [French (Switzerland)]
fr_CI [French (Côte d’Ivoire)]
fr_CM [French (Cameroon)]
fr_DJ [French (Djibouti)]
fr_DZ [French (Algeria)]
fr_FR [French (France)]
fr_GA [French (Gabon)]
fr_GF [French (French Guiana)]
fr_GN [French (Guinea)]
fr_GP [French (Guadeloupe)]
fr_GQ [French (Equatorial Guinea)]
fr_HT [French (Haiti)]
fr_KM [French (Comoros)]
fr_LU [French (Luxembourg)]
fr_MA [French (Morocco)]
fr_MC [French (Monaco)]
fr_MF [French (Saint Martin)]
fr_MG [French (Madagascar)]
fr_ML [French (Mali)]
fr_MQ [French (Martinique)]
fr_MR [French (Mauritania)]
fr_MU [French (Mauritius)]
fr_NC [French (New Caledonia)]
fr_NE [French (Niger)]
fr_PF [French (French Polynesia)]
fr_PM [French (Saint Pierre and Miquelon)]
fr_RE [French (Réunion)]
fr_RW [French (Rwanda)]
fr_SC [French (Seychelles)]
fr_SN [French (Senegal)]
fr_SY [French (Syria)]
fr_TD [French (Chad)]
fr_TG [French (Togo)]
fr_TN [French (Tunisia)]
fr_VU [French (Vanuatu)]
fr_WF [French (Wallis and Futuna)]
fr_YT [French (Mayotte)]
ga_ [Irish]
ga_IE [Irish (Ireland)]
gl_ [Galician]
gl_ES [Galician (Spain)]
gsw_ [Swiss German]
gsw_CH [Swiss German (Switzerland)]
gsw_LI [Swiss German (Liechtenstein)]
gu_ [Gujarati]
gu_IN [Gujarati (India)]
guz_ [Gusii]
guz_KE [Gusii (Kenya)]
gv_ [Manx]
gv_IM [Manx (Isle of Man)]
ha_ [Hausa]
ha_ [Hausa (Latin)]
ha_GH [Hausa (Latin,Ghana)]
ha_NE [Hausa (Latin,Niger)]
ha_NG [Hausa (Latin,Nigeria)]
haw_ [Hawaiian]
haw_US [Hawaiian (United States)]
iw_ [Hebrew]
iw_IL [Hebrew (Israel)]
hi_ [Hindi]
hi_IN [Hindi (India)]
hr_ [Croatian]
hr_BA [Croatian (Bosnia and Herzegovina)]
hr_HR [Croatian (Croatia)]
hu_ [Hungarian]
hu_HU [Hungarian (Hungary)]
hy_ [Armenian]
hy_AM [Armenian (Armenia)]
in_ [Indonesian]
in_ID [Indonesian (Indonesia)]
ig_ [Igbo]
ig_NG [Igbo (Nigeria)]
ii_ [Sichuan Yi]
ii_CN [Sichuan Yi (China)]
is_ [Icelandic]
is_IS [Icelandic (Iceland)]
it_ [Italian]
it_CH [Italian (Switzerland)]
it_IT [Italian (Italy)]
it_SM [Italian (San Marino)]
ja_ [Japanese]
ja_JP [Japanese (Japan)]
jgo_ [Ngomba]
jgo_CM [Ngomba (Cameroon)]
jmc_ [Machame]
jmc_TZ [Machame (Tanzania)]
ka_ [Georgian]
ka_GE [Georgian (Georgia)]
kab_ [Kabyle]
kab_DZ [Kabyle (Algeria)]
kam_ [Kamba]
kam_KE [Kamba (Kenya)]
kde_ [Makonde]
kde_TZ [Makonde (Tanzania)]
kea_ [Kabuverdianu]
kea_CV [Kabuverdianu (Cape Verde)]
khq_ [Koyra Chiini]
khq_ML [Koyra Chiini (Mali)]
ki_ [Kikuyu]
ki_KE [Kikuyu (Kenya)]
kk_ [Kazakh]
kk_ [Kazakh (Cyrillic)]
kk_KZ [Kazakh (Cyrillic,Kazakhstan)]
kkj_ [Kako]
kkj_CM [Kako (Cameroon)]
kl_ [Kalaallisut]
kl_GL [Kalaallisut (Greenland)]
kln_ [Kalenjin]
kln_KE [Kalenjin (Kenya)]
km_ [Khmer]
km_KH [Khmer (Cambodia)]
kn_ [Kannada]
kn_IN [Kannada (India)]
ko_ [Korean]
ko_KP [Korean (North Korea)]
ko_KR [Korean (South Korea)]
kok_ [Konkani]
kok_IN [Konkani (India)]
ks_ [Kashmiri]
ks_ [Kashmiri (Arabic)]
ks_IN [Kashmiri (Arabic,India)]
ksb_ [Shambala]
ksb_TZ [Shambala (Tanzania)]
ksf_ [Bafia]
ksf_CM [Bafia (Cameroon)]
kw_ [Cornish]
kw_GB [Cornish (United Kingdom)]
ky_ [Kyrgyz]
ky_ [Kyrgyz (Cyrillic)]
ky_KG [Kyrgyz (Cyrillic,Kyrgyzstan)]
lag_ [Langi]
lag_TZ [Langi (Tanzania)]
lg_ [Ganda]
lg_UG [Ganda (Uganda)]
lkt_ [Lakota]
lkt_US [Lakota (United States)]
ln_ [Lingala]
ln_AO [Lingala (Angola)]
ln_CD [Lingala (Congo (DRC))]
ln_CF [Lingala (Central African Republic)]
ln_CG [Lingala (Congo (Republic))]
lo_ [Lao]
lo_LA [Lao (Laos)]
lt_ [Lithuanian]
lt_LT [Lithuanian (Lithuania)]
lu_ [Luba-Katanga]
lu_CD [Luba-Katanga (Congo (DRC))]
luo_ [Luo]
luo_KE [Luo (Kenya)]
luy_ [Luyia]
luy_KE [Luyia (Kenya)]
lv_ [Latvian]
lv_LV [Latvian (Latvia)]
mas_ [Masai]
mas_KE [Masai (Kenya)]
mas_TZ [Masai (Tanzania)]
mer_ [Meru]
mer_KE [Meru (Kenya)]
mfe_ [Morisyen]
mfe_MU [Morisyen (Mauritius)]
mg_ [Malagasy]
mg_MG [Malagasy (Madagascar)]
mgh_ [Makhuwa-Meetto]
mgh_MZ [Makhuwa-Meetto (Mozambique)]
mgo_ [Meta']
mgo_CM [Meta' (Cameroon)]
mk_ [Macedonian]
mk_MK [Macedonian (Macedonia (FYROM))]
ml_ [Malayalam]
ml_IN [Malayalam (India)]
mn_ [Mongolian]
mn_ [Mongolian (Cyrillic)]
mn_MN [Mongolian (Cyrillic,Mongolia)]
mr_ [Marathi]
mr_IN [Marathi (India)]
ms_ [Malay]
ms_ [Malay (Latin)]
ms_BN [Malay (Latin,Brunei)]
ms_MY [Malay (Latin,Malaysia)]
ms_SG [Malay (Latin,Singapore)]
mt_ [Maltese]
mt_MT [Maltese (Malta)]
mua_ [Mundang]
mua_CM [Mundang (Cameroon)]
my_ [Burmese]
my_MM [Burmese (Myanmar (Burma))]
naq_ [Nama]
naq_NA [Nama (Namibia)]
nb_ [Norwegian Bokmål]
nb_NO [Norwegian Bokmål (Norway)]
nb_SJ [Norwegian Bokmål (Svalbard and Jan Mayen)]
nd_ [North Ndebele]
nd_ZW [North Ndebele (Zimbabwe)]
ne_ [Nepali]
ne_IN [Nepali (India)]
ne_NP [Nepali (Nepal)]
nl_ [Dutch]
nl_AW [Dutch (Aruba)]
nl_BE [Dutch (Belgium)]
nl_BQ [Dutch (Caribbean Netherlands)]
nl_CW [Dutch (Curaçao)]
nl_NL [Dutch (Netherlands)]
nl_SR [Dutch (Suriname)]
nl_SX [Dutch (Sint Maarten)]
nmg_ [Kwasio]
nmg_CM [Kwasio (Cameroon)]
nn_ [Norwegian Nynorsk]
nn_NO [Norwegian Nynorsk (Norway)]
nnh_ [Ngiemboon]
nnh_CM [Ngiemboon (Cameroon)]
nus_ [Nuer]
nus_SD [Nuer (Sudan)]
nyn_ [Nyankole]
nyn_UG [Nyankole (Uganda)]
om_ [Oromo]
om_ET [Oromo (Ethiopia)]
om_KE [Oromo (Kenya)]
or_ [Oriya]
or_IN [Oriya (India)]
pa_ [Punjabi]
pa_ [Punjabi (Arabic)]
pa_PK [Punjabi (Arabic,Pakistan)]
pa_ [Punjabi (Gurmukhi)]
pa_IN [Punjabi (Gurmukhi,India)]
pl_ [Polish]
pl_PL [Polish (Poland)]
ps_ [Pashto]
ps_AF [Pashto (Afghanistan)]
pt_ [Portuguese]
pt_AO [Portuguese (Angola)]
pt_BR [Portuguese (Brazil)]
pt_CV [Portuguese (Cape Verde)]
pt_GW [Portuguese (Guinea-Bissau)]
pt_MO [Portuguese (Macau)]
pt_MZ [Portuguese (Mozambique)]
pt_PT [Portuguese (Portugal)]
pt_ST [Portuguese (São Tomé and Príncipe)]
pt_TL [Portuguese (Timor-Leste)]
rm_ [Romansh]
rm_CH [Romansh (Switzerland)]
rn_ [Rundi]
rn_BI [Rundi (Burundi)]
ro_ [Romanian]
ro_MD [Romanian (Moldova)]
ro_RO [Romanian (Romania)]
rof_ [Rombo]
rof_TZ [Rombo (Tanzania)]
ru_ [Russian]
ru_BY [Russian (Belarus)]
ru_KG [Russian (Kyrgyzstan)]
ru_KZ [Russian (Kazakhstan)]
ru_MD [Russian (Moldova)]
ru_RU [Russian (Russia)]
ru_UA [Russian (Ukraine)]
rw_ [Kinyarwanda]
rw_RW [Kinyarwanda (Rwanda)]
rwk_ [Rwa]
rwk_TZ [Rwa (Tanzania)]
saq_ [Samburu]
saq_KE [Samburu (Kenya)]
sbp_ [Sangu]
sbp_TZ [Sangu (Tanzania)]
seh_ [Sena]
seh_MZ [Sena (Mozambique)]
ses_ [Koyraboro Senni]
ses_ML [Koyraboro Senni (Mali)]
sg_ [Sango]
sg_CF [Sango (Central African Republic)]
shi_ [Tachelhit]
shi_ [Tachelhit (Latin)]
shi_MA [Tachelhit (Latin,Morocco)]
shi_ [Tachelhit (Tifinagh)]
shi_MA [Tachelhit (Tifinagh,Morocco)]
si_ [Sinhala]
si_LK [Sinhala (Sri Lanka)]
sk_ [Slovak]
sk_SK [Slovak (Slovakia)]
sl_ [Slovenian]
sl_SI [Slovenian (Slovenia)]
sn_ [Shona]
sn_ZW [Shona (Zimbabwe)]
so_ [Somali]
so_DJ [Somali (Djibouti)]
so_ET [Somali (Ethiopia)]
so_KE [Somali (Kenya)]
so_SO [Somali (Somalia)]
sq_ [Albanian]
sq_AL [Albanian (Albania)]
sq_MK [Albanian (Macedonia (FYROM))]
sq_XK [Albanian (Kosovo)]
sr_ [Serbian]
sr_ [Serbian (Cyrillic)]
sr_BA [Serbian (Cyrillic,Bosnia and Herzegovina)]
sr_ME [Serbian (Cyrillic,Montenegro)]
sr_RS [Serbian (Cyrillic,Serbia)]
sr_XK [Serbian (Cyrillic,Kosovo)]
sr_ [Serbian (Latin)]
sr_BA [Serbian (Latin,Bosnia and Herzegovina)]
sr_ME [Serbian (Latin,Montenegro)]
sr_RS [Serbian (Latin,Serbia)]
sr_XK [Serbian (Latin,Kosovo)]
sv_ [Swedish]
sv_AX [Swedish (Åland Islands)]
sv_FI [Swedish (Finland)]
sv_SE [Swedish (Sweden)]
sw_ [Swahili]
sw_KE [Swahili (Kenya)]
sw_TZ [Swahili (Tanzania)]
sw_UG [Swahili (Uganda)]
swc_ [Congo Swahili]
swc_CD [Congo Swahili (Congo (DRC))]
ta_ [Tamil]
ta_IN [Tamil (India)]
ta_LK [Tamil (Sri Lanka)]
ta_MY [Tamil (Malaysia)]
ta_SG [Tamil (Singapore)]
te_ [Telugu]
te_IN [Telugu (India)]
teo_ [Teso]
teo_KE [Teso (Kenya)]
teo_UG [Teso (Uganda)]
th_ [Thai]
th_TH [Thai (Thailand)]
ti_ [Tigrinya]
ti_ER [Tigrinya (Eritrea)]
ti_ET [Tigrinya (Ethiopia)]
to_ [Tongan]
to_TO [Tongan (Tonga)]
tr_ [Turkish]
tr_CY [Turkish (Cyprus)]
tr_TR [Turkish (Turkey)]
twq_ [Tasawaq]
twq_NE [Tasawaq (Niger)]
tzm_ [Central Atlas Tamazight]
tzm_ [Central Atlas Tamazight (Latin)]
tzm_MA [Central Atlas Tamazight (Latin,Morocco)]
ug_ [Uyghur]
ug_ [Uyghur (Arabic)]
ug_CN [Uyghur (Arabic,China)]
uk_ [Ukrainian]
uk_UA [Ukrainian (Ukraine)]
ur_ [Urdu]
ur_IN [Urdu (India)]
ur_PK [Urdu (Pakistan)]
uz_ [Uzbek]
uz_ [Uzbek (Arabic)]
uz_AF [Uzbek (Arabic,Afghanistan)]
uz_ [Uzbek (Cyrillic)]
uz_UZ [Uzbek (Cyrillic,Uzbekistan)]
uz_ [Uzbek (Latin)]
uz_UZ [Uzbek (Latin,Uzbekistan)]
vai_ [Vai]
vai_ [Vai (Latin)]
vai_LR [Vai (Latin,Liberia)]
vai_ [Vai (Vai)]
vai_LR [Vai (Vai,Liberia)]
vi_ [Vietnamese]
vi_VN [Vietnamese (Vietnam)]
vun_ [Vunjo]
vun_TZ [Vunjo (Tanzania)]
xog_ [Soga]
xog_UG [Soga (Uganda)]
yav_ [Yangben]
yav_CM [Yangben (Cameroon)]
yo_ [Yoruba]
yo_BJ [Yoruba (Benin)]
yo_NG [Yoruba (Nigeria)]
zgh_ [Standard Moroccan Tamazight]
zgh_MA [Standard Moroccan Tamazight (Morocco)]
zh_ [Chinese]
zh_ [Chinese (Simplified Han)]
zh_CN [Chinese (Simplified Han,China)]
zh_HK [Chinese (Simplified Han,Hong Kong)]
zh_MO [Chinese (Simplified Han,Macau)]
zh_SG [Chinese (Simplified Han,Singapore)]
zh_ [Chinese (Traditional Han)]
zh_HK [Chinese (Traditional Han,Hong Kong)]
zh_MO [Chinese (Traditional Han,Macau)]
zh_TW [Chinese (Traditional Han,Taiwan)]
zu_ [Zulu]
zu_ZA [Zulu (South Africa)]

Original Answer :

As of Android 5.0, all languages in BCP 47 are available for application development (they may not necessarily be available for selection in a given device's system settings, though). When using ISO 639-1 codes, the resource folder has the format values-xx... where xx is the ISO-639-1 code.

When using BCP 47 tags, the resource folder is named values-b+xxx... where xxx is the three-letter language code.

Here's the list for before Android 2.3 (Source)

Language / Locale                 Supported since version

English, US (en_US)               1.1
German, Germany (de_DE)           1.1
Chinese, PRC (zh_CN)              1.5
Chinese, Taiwan (zh_TW)           1.5
Czech, Czech Republic (cs_CZ)     1.5
Dutch, Belgium (nl_BE)            1.5
Dutch, Netherlands (nl_NL)        1.5
English, Australia (en_AU)        1.5
English, Britain (en_GB)          1.5
English, Canada (en_CA)           1.5
English, New Zealand (en_NZ)      1.5
English, Singapore(en_SG)         1.5
French, Belgium (fr_BE)           1.5
French, Canada (fr_CA)            1.5
French, France (fr_FR)            1.5
French, Switzerland (fr_CH)       1.5
German, Austria (de_AT)           1.5
German, Liechtenstein (de_LI)     1.5
German, Switzerland (de_CH)       1.5
Italian, Italy (it_IT)            1.5
Italian, Switzerland (it_CH)      1.5
Japanese (ja_JP)                  1.5
Korean (ko_KR)                    1.5
Polish (pl_PL)                    1.5
Russian (ru_RU)                   1.5
Spanish (es_ES)                   1.5
Arabic, Egypt (ar_EG)             2.3
Arabic, Israel (ar_IL)            2.3
Bulgarian, Bulgaria (bg_BG)       2.3
Catalan, Spain (ca_ES)            2.3
Croatian, Croatia (hr_HR)         2.3
Danish, Denmark(da_DK)            2.3
English, India (en_IN)            2.3
English, Ireland (en_IE)          2.3
English, Zimbabwe (en_ZA)         2.3
Finnish, Finland (fi_FI)          2.3
Greek, Greece (el_GR)             2.3
Hebrew, Israel (iw_IL)*           2.3
Hindi, India (hi_IN)              2.3
Hungarian, Hungary (hu_HU)        2.3
Indonesian, Indonesia (in_ID)*    2.3
Latvian, Latvia (lv_LV)           2.3
Lithuanian, Lithuania (lt_LT)     2.3
Norwegian-Bokmål, Norway(nb_NO)   2.3
Portuguese, Brazil (pt_BR)        2.3
Portuguese, Portugal (pt_PT)      2.3
Romanian, Romania (ro_RO)         2.3
Serbian (sr_RS)                   2.3
Slovak, Slovakia (sk_SK)          2.3
Slovenian, Slovenia (sl_SI)       2.3
Spanish, US (es_US)               2.3
Swedish, Sweden (sv_SE)           2.3
Tagalog, Philippines (tl_PH)      2.3
Thai, Thailand (th_TH)            2.3
Turkish, Turkey (tr_TR)           2.3
Ukrainian, Ukraine (uk_UA)        2.3
Vietnamese, Vietnam (vi_VN)       2.3

*Note that Java uses several deprecated two-letter codes. The Hebrew (“he”) >language code is rewritten as “iw”, Indonesian (“id”) as “in”, and Yiddish (“yi”) as “ji”. This rewriting happens even if you construct your own Locale object, not just for instances returned by the various lookup methods. See also https://issuetracker.google.com/issues/36908826.

How does Facebook Sharer select Images and other metadata when sharing my URL?

From my experience, the http://www.facebook.com/sharer.php does not use meta tags. It uses the string you pass. See below.

http://www.facebook.com/sharer.php?s=100&p[title]=THIS IS MY TITLE&p[summary]=THIS IS MY SUMMARY&p[url]=http://www.MYURL.com&&p[images][0]=http://www.MYURL.com/img/IMAGEADDRESS

The meta tags work with Facebook's developer like/send buttons, as does the other Open Graph info. So if you use one of Facebook's actual elements like the comments and such, that will all tie into the Open Graph stuff.

UPDATE: There are two ways to use the sharer * note the ?s versus the ?u value in the query string
1 ==> STRING: http://www.facebook.com/sharer.php?s + content from above
~~> Will pull info from the string.
2 ==> URL: http://www.facebook.com/sharer.php?u=url where url equals an actual url
~~> Will scrape the page provided in the url value
~~> You can test test the values here: https://developers.facebook.com/tools/debug

Ternary operator (?:) in Bash

ternary operator ? : is just short form of if/else

case "$b" in
 5) a=$c ;;
 *) a=$d ;;
esac

Or

 [[ $b = 5 ]] && a="$c" || a="$d"

How to make primary key as autoincrement for Room Persistence lib

Its unbelievable after so many answers, but I did it little differently in the end. I don't like primary key to be nullable, I want to have it as first argument and also want to insert without defining it and also it should not be var.

@Entity(tableName = "employments")
data class Employment(
    @PrimaryKey(autoGenerate = true) val id: Long,
    @ColumnInfo(name = "code") val code: String,
    @ColumnInfo(name = "title") val name: String
){
    constructor(code: String, name: String) : this(0, code, name)
}

How to use sys.exit() in Python

you didn't import sys in your code, nor did you close the () when calling the function... try:

import sys
sys.exit()

Detecting user leaving page with react-router

Using history.listen

For example like below:

In your component,

componentWillMount() {
    this.props.history.listen(() => {
      // Detecting, user has changed URL
      console.info(this.props.history.location.pathname);
    });
}

Laravel - Forbidden You don't have permission to access / on this server

I had the same problem and builded a .htaccess file to fix this issue with a few more improvements. You can use it as it is, just download it from Github Gist and change the filename "public/index.php" to "public/app.php" and see how it works! :)

Calling a function when ng-repeat has finished

Please have a look at the fiddle, http://jsfiddle.net/yNXS2/. Since the directive you created didn't created a new scope i continued in the way.

$scope.test = function(){... made that happen.

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

Import mysql DB with XAMPP in command LINE

Go to the xampp shell command line and run

mysql -h localhost -u username databasename < dump.sql

How do I "Add Existing Item" an entire directory structure in Visual Studio?

It's annoying that Visual Studio doesn't support this natively, but CMake could generate the Visual Studio project as a work around.

Other than that, just use Qt Creator. It can then export a Visual Studio project.

Generating matplotlib graphs without a running X server

@Neil's answer is one (perfectly valid!) way of doing it, but you can also simply call matplotlib.use('Agg') before importing matplotlib.pyplot, and then continue as normal.

E.g.

import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
fig.savefig('temp.png')

You don't have to use the Agg backend, as well. The pdf, ps, svg, agg, cairo, and gdk backends can all be used without an X-server. However, only the Agg backend will be built by default (I think?), so there's a good chance that the other backends may not be enabled on your particular install.

Alternately, you can just set the backend parameter in your .matplotlibrc file to automatically have matplotlib.pyplot use the given renderer.

How can I display a tooltip on an HTML "option" tag?

I don't think this would be possible to do across all browsers.

W3Schools reports that the option events exist in all browsers, but after setting up this test demo. I can only get it to work for Firefox (not Chrome or IE), I haven't tested it on other browsers.

Firefox also allows mouseenter and mouseleave but this is not reported on the w3schools page.


Update: Honestly, from looking at the example code you provided, I wouldn't even use a select box. I think it would look nicer with a slider. I've updated your demo. I had to make a few minor changes to your ratings object (adding a level number) and the safesurf tab. But I left pretty much everything else intact.

Double border with different color

You can use the border and box-shadow properties along with CSS pseudo elements to achieve a triple-border sort of effect. See the example below for an idea of how to create three borders at the bottom of a div:

_x000D_
_x000D_
.triple-border:after {_x000D_
    content: " ";_x000D_
    display: block;_x000D_
    width: 100%;_x000D_
    background: #FFE962;_x000D_
    height: 9px;_x000D_
    padding-bottom: 8px;_x000D_
    border-bottom: 9px solid #A3C662;_x000D_
    box-shadow: -2px 11px 0 -1px #34b6af;_x000D_
}
_x000D_
<div class="triple-border">Triple border bottom with multiple colours</div>
_x000D_
_x000D_
_x000D_

You'll have to play around with the values to get the alignment correct. However, you can also achieve more flexibility, e.g. 4 borders if you put some of the attributes in the proper element rather than the pseudo selector.

How can I get the ID of an element using jQuery?

.id is not a valid jquery function. You need to use the .attr() function to access attributes an element possesses. You can use .attr() to both change an attribute value by specifying two parameters, or get the value by specifying one.

http://api.jquery.com/attr/

Clearing NSUserDefaults

This code resets the defaults to the registration domain:

[[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];

In other words, it removeObjectForKey for every single key you ever registered in that app.

Credits to Ken Thomases on this Apple Developer Forums thread.

python: urllib2 how to send cookie with urlopen request

This answer is not working since the urllib2 module has been split across several modules in Python 3. You need to do

from urllib import request
opener = request.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")

String array initialization in Java

You can do the following during declaration:

String names[] = {"Ankit","Bohra","Xyz"};

And if you want to do this somewhere after declaration:

String names[];
names = new String[] {"Ankit","Bohra","Xyz"};

How do I remove the horizontal scrollbar in a div?

I had been having issues where I was using

overflow: none;

But I knew CSS didn't really like it and it didn’t work 100% for how I wanted it to.

However, this is a perfect solution as none of my content is supposed to be larger than intended and this has fixed the issue I had.

overflow: auto;

How to loop through all the properties of a class?

VB version of C# given by Brannon:

Public Sub DisplayAll(ByVal Someobject As Foo)
    Dim _type As Type = Someobject.GetType()
    Dim properties() As PropertyInfo = _type.GetProperties()  'line 3
    For Each _property As PropertyInfo In properties
        Console.WriteLine("Name: " + _property.Name + ", Value: " + _property.GetValue(Someobject, Nothing))
    Next
End Sub

Using Binding flags in instead of line no.3

    Dim flags As BindingFlags = BindingFlags.Public Or BindingFlags.Instance
    Dim properties() As PropertyInfo = _type.GetProperties(flags)

Get DOS path instead of Windows path

Being a programmer made this 10-minute Winform project. It's been useful for me. Making this app to a context menu for file explorer would save more clicks.

10-minute application

Form1.cs:

using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace ToShortPath
{
    public partial class Form1 : Form
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern int GetShortPathName(
                 [MarshalAs(UnmanagedType.LPTStr)]
                   string path,
                 [MarshalAs(UnmanagedType.LPTStr)]
                   StringBuilder shortPath,
                 int shortPathLength
                 );
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Show the dialog and get result.
            var openFileDialog1 = new OpenFileDialog();
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK) // Test result.
            {
                textBox1.Text = openFileDialog1.FileName;
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            var openFileDialog1 = new FolderBrowserDialog();
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK) // Test result.
            {
                textBox1.Text = openFileDialog1.SelectedPath;
            }

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            StringBuilder shortPath = new StringBuilder(65000);
            GetShortPathName(textBox1.Text, shortPath, shortPath.Capacity);
            textBox2.Text = shortPath.ToString();
        }

    }
}

Form1.Designer.cs:

namespace ToShortPath
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(69, 13);
            this.textBox1.Multiline = true;
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(516, 53);
            this.textBox1.TabIndex = 0;
            this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
            // 
            // textBox2
            // 
            this.textBox2.Location = new System.Drawing.Point(69, 72);
            this.textBox2.Multiline = true;
            this.textBox2.Name = "textBox2";
            this.textBox2.ReadOnly = true;
            this.textBox2.Size = new System.Drawing.Size(516, 53);
            this.textBox2.TabIndex = 1;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(7, 35);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(56, 13);
            this.label1.TabIndex = 2;
            this.label1.Text = "Long Path";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(7, 95);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(57, 13);
            this.label2.TabIndex = 3;
            this.label2.Text = "Short Path";
            // 
            // button1
            // 
            this.button1.AutoSize = true;
            this.button1.Location = new System.Drawing.Point(591, 13);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(40, 53);
            this.button1.TabIndex = 4;
            this.button1.Text = "File";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // button2
            // 
            this.button2.AutoSize = true;
            this.button2.Location = new System.Drawing.Point(637, 12);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(46, 53);
            this.button2.TabIndex = 5;
            this.button2.Text = "Folder";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(687, 135);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.textBox1);
            this.Name = "Form1";
            this.Text = "Short Path";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button button2;
    }
}

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

 function convertDatePickerTimeToMySQLTime(str) {
        var month, day, year, hours, minutes, seconds;
        var date = new Date(str),
            month = ("0" + (date.getMonth() + 1)).slice(-2),
            day = ("0" + date.getDate()).slice(-2);
        hours = ("0" + date.getHours()).slice(-2);
        minutes = ("0" + date.getMinutes()).slice(-2);
        seconds = ("0" + date.getSeconds()).slice(-2);

        var mySQLDate = [date.getFullYear(), month, day].join("-");
        var mySQLTime = [hours, minutes, seconds].join(":");
        return [mySQLDate, mySQLTime].join(" ");
    }

How to change the height of a <br>?

<br> is for a line break.
<br /> is also for line break, the "/" optionally needed for void elements or for xhtml.
Using <br></br>, browsers will insert two line breaks for both are "virtually" the same.
There is no way to increase the size of a line break because it's just a line break.
Use a div with vilibility set to hidden (<div style="vilibility:hidden; line-height:150%;"</div>) or better still, a paragraph.

How to import Angular Material in project?

Import all Angular Material modules in Angular 9.

Create material.module.ts file in your_project/src/app/ directory and paste this code.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';


import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatRadioModule } from '@angular/material/radio';
import { MatSelectModule } from '@angular/material/select';
import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatMenuModule } from '@angular/material/menu';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatBadgeModule } from '@angular/material/badge';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatListModule } from '@angular/material/list';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatCardModule } from '@angular/material/card';
import { MatStepperModule } from '@angular/material/stepper';
import { MatTabsModule } from '@angular/material/tabs';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatChipsModule } from '@angular/material/chips';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatDialogModule } from '@angular/material/dialog';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
import { MatSortModule } from '@angular/material/sort';
import { MatPaginatorModule } from '@angular/material/paginator';


@NgModule( {
    imports: [
        CommonModule,
        BrowserAnimationsModule,
        MatCheckboxModule,
        MatCheckboxModule,
        MatButtonModule,
        MatInputModule,
        MatAutocompleteModule,
        MatDatepickerModule,
        MatFormFieldModule,
        MatRadioModule,
        MatSelectModule,
        MatSliderModule,
        MatSlideToggleModule,
        MatMenuModule,
        MatSidenavModule,
        MatBadgeModule,
        MatToolbarModule,
        MatListModule,
        MatGridListModule,
        MatCardModule,
        MatStepperModule,
        MatTabsModule,
        MatExpansionModule,
        MatButtonToggleModule,
        MatChipsModule,
        MatIconModule,
        MatProgressSpinnerModule,
        MatProgressBarModule,
        MatDialogModule,
        MatTooltipModule,
        MatSnackBarModule,
        MatTableModule,
        MatSortModule,
        MatPaginatorModule

    ],
    exports: [
        MatButtonModule,
        MatToolbarModule,
        MatIconModule,
        MatSidenavModule,
        MatBadgeModule,
        MatListModule,
        MatGridListModule,
        MatInputModule,
        MatFormFieldModule,
        MatSelectModule,
        MatRadioModule,
        MatDatepickerModule,
        MatChipsModule,
        MatTooltipModule,
        MatTableModule,
        MatPaginatorModule
    ],
    providers: [
        MatDatepickerModule,
    ]
} )

export class AngularMaterialModule { }

Is there a way to use PhantomJS in Python?

PhantomJS recently dropped Python support altogether. However, PhantomJS now embeds Ghost Driver.

A new project has since stepped up to fill the void: ghost.py. You probably want to use that instead:

from ghost import Ghost
ghost = Ghost()

with ghost.start() as session:
    page, extra_resources = ghost.open("http://jeanphi.me")
    assert page.http_status==200 and 'jeanphix' in ghost.content

Remove non-utf8 characters from string

So the rules are that the first UTF-8 octlet has the high bit set as a marker, and then 1 to 4 bits to indicate how many additional octlets; then each of the additional octlets must have the high two bits set to 10.

The pseudo-python would be:

newstring = ''
cont = 0
for each ch in string:
  if cont:
    if (ch >> 6) != 2: # high 2 bits are 10
      # do whatever, e.g. skip it, or skip whole point, or?
    else:
      # acceptable continuation of multi-octlet char
      newstring += ch
    cont -= 1
  else:
    if (ch >> 7): # high bit set?
      c = (ch << 1) # strip the high bit marker
      while (c & 1): # while the high bit indicates another octlet
        c <<= 1
        cont += 1
        if cont > 4:
           # more than 4 octels not allowed; cope with error
      if !cont:
        # illegal, do something sensible
      newstring += ch # or whatever
if cont:
  # last utf-8 was not terminated, cope

This same logic should be translatable to php. However, its not clear what kind of stripping is to be done once you get a malformed character.

Difference between PCDATA and CDATA in DTD

From here (Google is your friend):

In a DTD, PCDATA and CDATA are used to assert something about the allowable content of elements and attributes, respectively. In an element's content model, #PCDATA says that the element contains (may contain) "any old text." (With exceptions as noted below.) In an attribute's declaration, CDATA is one sort of constraint you can put on the attribute's allowable values (other sorts, all mutually exclusive, include ID, IDREF, and NMTOKEN). An attribute whose allowable values are CDATA can (like PCDATA in an element) contain "any old text."

A potentially really confusing issue is that there's another "CDATA," also referred to as marked sections. A marked section is a portion of element (#PCDATA) content delimited with special strings: to close it. If you remember that PCDATA is "parsed character data," a CDATA section is literally the same thing, without the "parsed." Parsers transmit the content of a marked section to downstream applications without hiccupping every time they encounter special characters like < and &. This is useful when you're coding a document that contains lots of those special characters (like scripts and code fragments); it's easier on data entry, and easier on reading, than the corresponding entity reference.

So you can infer that the exception to the "any old text" rule is that PCDATA cannot include any of these unescaped special characters, UNLESS they fall within the scope of a CDATA marked section.

How to access static resources when mapping a global front controller servlet on /*

If you use Tomcat, you can map resources to the default servlet:

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/static/*</url-pattern>
</servlet-mapping>

and access your resources with url http://{context path}/static/res/...

Also works with Jetty, not sure about other servlet containers.

How to create a box when mouse over text in pure CSS?

You can easily make this CSS Tool Tip through simple code :-

    <!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
a.info{
    position:relative; /*this is the key*/
    color:#000;
    top:100px;
    left:50px;
    text-decoration:none;
    text-align:center;
  }



a.info span{display: none}

a.info:hover span{ /*the span will display just on :hover state*/
    display:block;
    position:absolute;
    top:-60px;
    width:15em;
    border:5px solid #0cf;
    background-color:#cff; color:#000;
    text-align: center;
    padding:10px;
  }

  a.info:hover span:after{ /*the span will display just on :hover state*/
    content:'';
    position:absolute;
    bottom:-11px;
    width:10px;
    height:10px;
    border-bottom:5px solid #0cf;
    border-right:5px solid #0cf;
    background:#cff;
    left:50%;
    margin-left:-5px;
    -moz-transform:rotate(45deg);
    -webkit-transform:rotate(45deg);
    transform:rotate(45deg);
  }


</style>
</head>
<body>
<a href="#" class="info">Shailender Arora <span>TOOLTIP</span></a>
  </div>
</body>
</html>

http://jsbin.com/ebucoz/25/edit

How to remove only 0 (Zero) values from column in excel 2010

Consider your data is into column A and will write coding now

Sub deletezeros()
    Dim c As Range
    Dim searchrange As Range
    Dim i As Long

    Set searchrange = ActiveSheet.Range("A1", ActiveSheet.Range("A65536").End(xlUp))

    For i = searchrange.Cells.Count To 1 Step -1
        Set c = searchrange.Cells(i)
        If c.Value = "0" Then c.EntireRow.delete
    Next i
End Sub

What are Unwind segues for and how do you use them?

For example if you navigate from viewControllerB to viewControllerA then in your viewControllerA below delegate will call and data will share.

@IBAction func unWindSeague (_ sender : UIStoryboardSegue) {
        if sender.source is ViewControllerB  {
            if let _ = sender.source as? ViewControllerB {
                self.textLabel.text = "Came from B = B->A , B exited"
            }
            
        }

}
  • Unwind Seague Source View Controller ( You Need to connect Exit Button to VC’s exit icon and connect it to unwindseague:

enter image description here

  • Unwind Seague Completed -> TextLabel of viewControllerA is Changed.

enter image description here

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.


Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)


Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

Create a function with optional call variables

Powershell provides a lot of built-in support for common parameter scenarios, including mandatory parameters, optional parameters, "switch" (aka flag) parameters, and "parameter sets."

By default, all parameters are optional. The most basic approach is to simply check each one for $null, then implement whatever logic you want from there. This is basically what you have already shown in your sample code.

If you want to learn about all of the special support that Powershell can give you, check out these links:

about_Functions

about_Functions_Advanced

about_Functions_Advanced_Parameters

Drop multiple columns in pandas

Try this

df.drop(df.iloc[:, 1:69], inplace=True, axis=1)

This works for me

Changing default startup directory for command prompt in Windows 7

In the new Windows Terminal, you can click Settings and edit the line "startingDirectory" to achieve something similar.

Please note, however, that this changes the default startup directory only in Windows Terminal, and not for the command prompt globally.

Get specific ArrayList item

We print the value using mainList.get(index) where index starts with '0'. For Example: mainList.get(2) prints the 3rd element in the list.

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

Real/physical iPhone 6 Plus resolution is 1920x1080 but in Xcode you make your interface for 2208x1242 resolution (736x414 points) and on device it is automatically scaled down to 1920x1080 pixels.

iPhone resolutions quick reference:

Device          Points    Pixels     Scale  Physical Pixels   PPI   Ratio   Size
iPhone XS Max   896x414   2688x1242  3x     2688x1242         458   19.5:9  6.5"
iPhone XR       896x414   1792x828   2x     1792x828          326   19.5:9  6.1"
iPhone X        812x375   2436x1125  3x     2436x1125         458   19.5:9  5.8"
iPhone 6 Plus   736x414   2208x1242  3x     1920x1080         401   16:9    5.5"
iPhone 6        667x375   1334x750   2x     1334x750          326   16:9    4.7"
iPhone 5        568x320   1136x640   2x     1136x640          326   16:9    4.0"
iPhone 4        480x320   960x640    2x     960x640           326   3:2     3.5"
iPhone 3GS      480x320   480x320    1x     480x320           163   3:2     3.5"

iPhone resolutions

Hadoop: «ERROR : JAVA_HOME is not set»

Here we provide simple steps to setup JAVA_HOME while installing of Hadoop

Step1: Goto Java library path /lib jvm

Then set the JAVA_HOME & PATH in .bashrc file

Source : http://commandstech.com/hadoop-error-java_home-is-not-set-and-could-not-be-found-in-hadoop-installation/

Step 2 : Once it is done then go with Hadoop env file then update it.

After once it is done then stop the daemons and start daemons once again.

CreateProcess error=206, The filename or extension is too long when running main() method

Try this:

java -jar -Dserver.port=8080 build/libs/APP_NAME_HERE.jar

"rm -rf" equivalent for Windows?

RMDIR or RD if you are using the classic Command Prompt (cmd.exe):

rd /s /q "path"

RMDIR [/S] [/Q] [drive:]path

RD [/S] [/Q] [drive:]path

/S Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree.

/Q Quiet mode, do not ask if ok to remove a directory tree with /S

If you are using PowerShell you can use Remove-Item (which is aliased to del, erase, rd, ri, rm and rmdir) and takes a -Recurse argument that can be shorted to -r

rd -r "path"

How to define custom exception class in Java, the easiest way?

and don't forget the easiest way to throw an exception (you don't need to create a class)

if (rgb > MAX) throw new RuntimeException("max color exceeded");

Where to find free public Web Services?

https://www.programmableweb.com/ -- Great collection of all category API's across web. It not only show cases the API's , but also Developers who use those API's in their applications and code samples, rating of the API and much more. They have more than apis they also have sdk and libraries too.

How to create an instance of System.IO.Stream stream

Stream stream = new MemoryStream();

you can use MemoryStream

Reference: MemoryStream

notifyDataSetChange not working from custom adapter

If adapter is set to AutoCompleteTextView then notifyDataSetChanged() doesn't work.

Need this to update adapter:

myAutoCompleteAdapter = new ArrayAdapter<String>(MainActivity.this, 
        android.R.layout.simple_dropdown_item_1line, myList);

myAutoComplete.setAdapter(myAutoCompleteAdapter);

Refer: http://android-er.blogspot.in/2012/10/autocompletetextview-with-dynamic.html

How to suspend/resume a process in Windows?

I use (a very old) process explorer from SysInternals (procexp.exe). It is a replacement / addition to the standard Task manager, you can suspend a process from there.

Edit: Microsoft has bought over SysInternals, url: procExp.exe

Other than that you can set the process priority to low so that it does not get in the way of other processes, but this will not suspend the process.

Does a VPN Hide my Location on Android?

Your question can be conveniently divided into several parts:

Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.

How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.

You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):

  1. Download and install a trusted VPN.

  2. Install the VPN on your Android device.

  3. Open the application and connect to a server in a different country.

  4. Your Android location will now be successfully changed!

Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.

Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.

mvn clean install vs. deploy vs. release

  • mvn install will put your packaged maven project into the local repository, for local application using your project as a dependency.
  • mvn release will basically put your current code in a tag on your SCM, change your version in your projects.
  • mvn deploy will put your packaged maven project into a remote repository for sharing with other developers.

Resources :

Can I clear cell contents without changing styling?

you can use ClearContents. ex,

Range("X").Cells.ClearContents

How to specify multiple conditions in an if statement in javascript

function go(type, pageCount) {
    if ((type == 2 && pageCount == 0) || (type == 2 && pageCount == '')) {
        pageCount = document.getElementById('<%=hfPageCount.ClientID %>').value;
    }
}

Is there a way to programmatically minimize a window

in c#.net

this.WindowState = FormWindowState.Minimized

Javascript Error Null is not an Object

I agree with alex about making sure the DOM is loaded. I also think that the submit button will trigger a refresh.

This is what I would do

<html>
<head>
<title>webpage</title>
</head>
<script type="text/javascript">
var myButton;
var myTextfield;

function setup() {
  myButton = document.getElementById("myButton");
  myTextfield = document.getElementById("myTextfield");
  myButton.onclick = function() {
    var userName = myTextfield.value;
    greetUser(userName);
    return false;
  }
}

function greetUser(userName) {
  var greeting = "Hello " + userName + "!";
  document.getElementsByTagName("h2")[0].innerHTML = greeting;
}

</script>
<body onload="setup()">
  <h2>Hello World!</h2>
  <p id="myParagraph">This is an example website</p>

  <form>
    <input type="text" id="myTextfield" placeholder="Type your name" />
    <input type="button" id="myButton" value="Go" />
  </form>
  </body>
</html>

have fun!

How to update/refresh specific item in RecyclerView

Update single item

  1. Update the data item
  2. Notify the adapter of the change with notifyItemChanged(updateIndex)

Example

Change the "Sheep" item so that it says "I like sheep."

Update single item

String newValue = "I like sheep.";
int updateIndex = 3;
data.set(updateIndex, newValue);
adapter.notifyItemChanged(updateIndex);

My full answer with more examples is here.

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

you could use "AUTHID CURRENT_USER" in body of your procedure definition for your requirements.

Tokenizing strings in C

strtok can be very dangerous. It is not thread safe. Its intended use is to be called over and over in a loop, passing in the output from the previous call. The strtok function has an internal variable that stores the state of the strtok call. This state is not unique to each thread - it is global. If any other code uses strtok in another thread, you get problems. Not the kind of problems you want to track down either!

I'd recommend looking for a regex implementation, or using sscanf to pull apart the string.

Try this:

char strprint[256];
char text[256];
strcpy(text, "My string to test");
while ( sscanf( text, "%s %s", strprint, text) > 0 ) {
   printf("token: %s\n", strprint);
}

Note: The 'text' string is destroyed as it's separated. This may not be the preferred behaviour =)

no target device found android studio 2.1.1

I had this problem after upgrading from Android Studio 2.3 to 3.0. As simple as it sounds, I actually just restarted my phone to fix it.

My guess is that the adb server on the phone somehow cached something from the previous installation of android studio, maybe a connection object or something, and by restarting the adb server it resolved the issue.

I hope this helps someone.

Change auto increment starting number?

You can use ALTER TABLE to change the auto_increment initial value:

ALTER TABLE tbl AUTO_INCREMENT = 5;

See the MySQL reference for more details.

Update built-in vim on Mac OS X

This blog post was helpful for me. I used the "Homebrew built Vim" solution, which in my case saved the new version in /usr/local/bin. At this point, the post suggested hiding the system vim, which didn't work for me, so I used an alias instead.

$ brew install vim
$ alias vim='/path/to/new/vim
$ which vim
vim: aliased to /path/to/new/vim

How to open port in Linux

The following configs works on Cent OS 6 or earlier

As stated above first have to disable selinux.

Step 1 nano /etc/sysconfig/selinux

Make sure the file has this configurations

SELINUX=disabled

SELINUXTYPE=targeted

Then restart the system

Step 2

iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT

Step 3

sudo service iptables save

For Cent OS 7

step 1

firewall-cmd --zone=public --permanent --add-port=8080/tcp

Step 2

firewall-cmd --reload

How to create custom button in Android using XML Styles

Copy-pasted from a recipe written by "Adrián Santalla" on androidcookbook.com: https://www.androidcookbook.com/Recipe.seam?recipeId=3307

1. Create an XML file that represents the button states

Create an xml into drawable called 'button.xml' to name the button states:

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_enabled="false"
        android:drawable="@drawable/button_disabled" />
    <item
        android:state_pressed="true"
        android:state_enabled="true"
        android:drawable="@drawable/button_pressed" />
    <item
        android:state_focused="true"
        android:state_enabled="true"
        android:drawable="@drawable/button_focused" />
    <item
        android:state_enabled="true"
        android:drawable="@drawable/button_enabled" />
</selector>

2. Create an XML file that represents each button state

Create one xml file for each of the four button states. All of them should be under drawables folder. Let's follow the names set in the button.xml file.

button_enabled.xml:

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <gradient
        android:startColor="#00CCFF"
        android:centerColor="#0000CC"
        android:endColor="#00CCFF"
        android:angle="90"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <stroke
        android:width="2dip"
        android:color="#FFFFFF" />
    <corners android:radius= "8dp" />
</shape>

button_focused.xml:

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <gradient
        android:startColor="#F7D358"
        android:centerColor="#DF7401"
        android:endColor="#F7D358"
        android:angle="90"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <stroke
        android:width="2dip"
        android:color="#FFFFFF" />
    <corners android:radius= "8dp" />
</shape>

button_pressed.xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <gradient
        android:startColor="#0000CC"
        android:centerColor="#00CCFF"
        android:endColor="#0000CC"
        android:angle="90"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <stroke
        android:width="2dip"
        android:color="#FFFFFF" />
    <corners android:radius= "8dp" />
</shape>

button_disabled.xml:

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <gradient
        android:startColor="#F2F2F2"
        android:centerColor="#A4A4A4"
        android:endColor="#F2F2F2"
        android:angle="90"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <stroke
        android:width="2dip"
        android:color="#FFFFFF" />
    <corners android:radius= "8dp" />
</shape>

3. Create an XML file that represents the button style

Once you have created the files mentioned above, it's time to create your application button style. Now, you need to create a new XML file, called styles.xml (if you don't have it yet) where you can include more custom styles, into de values directory.

This file will contain the new button style of your application. You need to set your new button style features in it. Note that one of those features, the background of your new style, should be set with a reference to the button (button.xml) drawable that was created in the first step. To refer to the new button style we use the name attribute.

The example below show the content of the styles.xml file:

<resources>
    <style name="button" parent="@android:style/Widget.Button">
        <item name="android:gravity">center_vertical|center_horizontal</item>
        <item name="android:textColor">#FFFFFFFF</item>
        <item name="android:shadowColor">#FF000000</item>
        <item name="android:shadowDx">0</item>
        <item name="android:shadowDy">-1</item>
        <item name="android:shadowRadius">0.2</item>
        <item name="android:textSize">16dip</item>
        <item name="android:textStyle">bold</item>
        <item name="android:background">@drawable/button</item>
        <item name="android:focusable">true</item>
        <item name="android:clickable">true</item>
    </style>
</resources>

4. Create an XML with your own custom application theme

Finally, you need to override the default Android button style. For that, you need to create a new XML file, called themes.xml (if you don't have it yet), into the values directory and override the default Android button style.

The example below show the content of the themes.xml:

<resources>
    <style name="YourApplicationTheme" parent="android:style/Theme.NoTitleBar">
        <item name="android:buttonStyle">@style/button</item>
    </style>
</resources>

Hope you guys can have the same luck as I had with this, when I was looking for custom buttons. Enjoy.

Webview load html from assets directory

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView wb = new WebView(this);
        wb.loadUrl("file:///android_asset/index.html");
        setContentView(wb);
    }


keep your .html in `asset` folder

Change drive in git bash for windows

In order to navigate to a different drive/directory you can do it in convenient way (instead of typing cd /e/Study/Codes), just type in cd[Space], and drag-and-drop your directory Codes with your mouse to git bash, hit [Enter].

Group By Eloquent ORM

Eloquent uses the query builder internally, so you can do:

$users = User::orderBy('name', 'desc')
                ->groupBy('count')
                ->having('count', '>', 100)
                ->get();

IntelliJ IDEA "The selected directory is not a valid home for JDK"

I had the same issue. But I figured it out by choosing this path:

First at all, you need to select the C:\ folder. Then, you select Program Files. After it, you select java, and finally the jdk you downloaded. In my case, I downloaded the JDK1.8.0_60 version.

To resume the path:

C:\Program Files\java\jdk1.8.0_60

After you are done with it, you can click on the button next. Then you select the create project from templates. This will create a java application with a main() method. After it, you click next to create the name of you project.

I hope this helps you.

How to move git repository with all branches from bitbucket to github?

You can refer to the GitHub page "Duplicating a repository"

It uses:

That would give:

git clone --mirror https://bitbucket.org/exampleuser/repository-to-mirror.git
# Make a bare mirrored clone of the repository

cd repository-to-mirror.git
git remote set-url --push origin https://github.com/exampleuser/mirrored
# Set the push location to your mirror

git push --mirror

As Noted in the comments by L S:

Editing legend (text) labels in ggplot

The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2 package.

An example with your data:

# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")

# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) + 
  geom_point(size=5) +
  labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
        axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
        plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))

this results in:

enter image description here

As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888")) instead of scale_color_manual().

How to save a data frame as CSV to a user selected location using tcltk

You need not to use even the package "tcltk". You can simply do as shown below:

write.csv(x, file = "c:\\myname\\yourfile.csv", row.names = FALSE)

Give your path inspite of "c:\myname\yourfile.csv".

How to create nonexistent subdirectories recursively using Bash?

$ mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"

LINQ Group By into a Dictionary Object

Dictionary<string, List<CustomObject>> myDictionary = ListOfCustomObjects
    .GroupBy(o => o.PropertyName)
    .ToDictionary(g => g.Key, g => g.ToList());

How find out which process is using a file in Linux?

@jim's answer is correct -- fuser is what you want.

Additionally (or alternately), you can use lsof to get more information including the username, in case you need permission (without having to run an additional command) to kill the process. (THough of course, if killing the process is what you want, fuser can do that with its -k option. You can have fuser use other signals with the -s option -- check the man page for details.)

For example, with a tail -F /etc/passwd running in one window:

ghoti@pc:~$ lsof | grep passwd
tail      12470    ghoti    3r      REG  251,0     2037 51515911 /etc/passwd

Note that you can also use lsof to find out what processes are using particular sockets. An excellent tool to have in your arsenal.

Include php files when they are in different folders

None of the above answers fixed this issue for me. I did it as following (Laravel with Ubuntu server):

<?php
     $footerFile = '/var/www/website/main/resources/views/emails/elements/emailfooter.blade.php';
     include($footerFile);
?>

Get the week start date and week end date from week number

Here is a DATEFIRST agnostic solution:

SET DATEFIRST 4     /* or use any other weird value to test it */
DECLARE @d DATETIME

SET @d = GETDATE()

SELECT
  @d ThatDate,
  DATEADD(dd, 0 - (@@DATEFIRST + 5 + DATEPART(dw, @d)) % 7, @d) Monday,
  DATEADD(dd, 6 - (@@DATEFIRST + 5 + DATEPART(dw, @d)) % 7, @d) Sunday

How to create a <style> tag with Javascript?

Here's a script which adds IE-style createStyleSheet() and addRule() methods to browsers which don't have them:

if(typeof document.createStyleSheet === 'undefined') {
    document.createStyleSheet = (function() {
        function createStyleSheet(href) {
            if(typeof href !== 'undefined') {
                var element = document.createElement('link');
                element.type = 'text/css';
                element.rel = 'stylesheet';
                element.href = href;
            }
            else {
                var element = document.createElement('style');
                element.type = 'text/css';
            }

            document.getElementsByTagName('head')[0].appendChild(element);
            var sheet = document.styleSheets[document.styleSheets.length - 1];

            if(typeof sheet.addRule === 'undefined')
                sheet.addRule = addRule;

            if(typeof sheet.removeRule === 'undefined')
                sheet.removeRule = sheet.deleteRule;

            return sheet;
        }

        function addRule(selectorText, cssText, index) {
            if(typeof index === 'undefined')
                index = this.cssRules.length;

            this.insertRule(selectorText + ' {' + cssText + '}', index);
        }

        return createStyleSheet;
    })();
}

You can add external files via

document.createStyleSheet('foo.css');

and dynamically create rules via

var sheet = document.createStyleSheet();
sheet.addRule('h1', 'background: red;');

How to manage startActivityForResult on Android?

You need to override Activity.onActivityResult()

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

if (resultCode == RESULT_CODE_ONE) {


   String a = data.getStringExtra("RESULT_CODE_ONE");

}
else if(resultCode == RESULT_CODE_TWO){

   // b was clicked

}
else{

}
}

What does ON [PRIMARY] mean?

ON [PRIMARY] will create the structures on the "Primary" filegroup. In this case the primary key index and the table will be placed on the "Primary" filegroup within the database.

Understanding passport serialize deserialize

For anyone using Koa and koa-passport:

Know that the key for the user set in the serializeUser method (often a unique id for that user) will be stored in:

this.session.passport.user

When you set in done(null, user) in deserializeUser where 'user' is some user object from your database:

this.req.user OR this.passport.user

for some reason this.user Koa context never gets set when you call done(null, user) in your deserializeUser method.

So you can write your own middleware after the call to app.use(passport.session()) to put it in this.user like so:

app.use(function * setUserInContext (next) {
  this.user = this.req.user
  yield next
})

If you're unclear on how serializeUser and deserializeUser work, just hit me up on twitter. @yvanscher

Loop timer in JavaScript

Note that setTimeout and setInterval are very different functions:

  • setTimeout will execute the code once, after the timeout.
  • setInterval will execute the code forever, in intervals of the provided timeout.

Both functions return a timer ID which you can use to abort the timeout. All you have to do is store that value in a variable and use it as argument to clearTimeout(tid) or clearInterval(tid) respectively.

So, depending on what you want to do, you have two valid choices:

// set timeout
var tid = setTimeout(mycode, 2000);
function mycode() {
  // do some stuff...
  tid = setTimeout(mycode, 2000); // repeat myself
}
function abortTimer() { // to be called when you want to stop the timer
  clearTimeout(tid);
}

or

// set interval
var tid = setInterval(mycode, 2000);
function mycode() {
  // do some stuff...
  // no need to recall the function (it's an interval, it'll loop forever)
}
function abortTimer() { // to be called when you want to stop the timer
  clearInterval(tid);
}

Both are very common ways of achieving the same.

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

initialize mysql before start on windows.

mysqld --initialize

Explain the concept of a stack frame in a nutshell

A quick wrap up. Maybe someone has a better explanation.

A call stack is composed of 1 or many several stack frames. Each stack frame corresponds to a call to a function or procedure which has not yet terminated with a return.

To use a stack frame, a thread keeps two pointers, one is called the Stack Pointer (SP), and the other is called the Frame Pointer (FP). SP always points to the "top" of the stack, and FP always points to the "top" of the frame. Additionally, the thread also maintains a program counter (PC) which points to the next instruction to be executed.

The following are stored on the stack: local variables and temporaries, actual parameters of the current instruction (procedure, function, etc.)

There are different calling conventions regarding the cleaning of the stack.

Manually adding a Userscript to Google Chrome

Share and install userscript with one-click

To make auto-install (but mannually confirm), You can make gist (gist.github.com) with <filename>.user.js filename to get on-click installation when you click on Raw and get this page:

Installation page

How to do this ?

  1. Name your gist <filename>.user.js, write your code and click on "Create".
    Make file on gist

  2. In the gist page, click on Raw to get installation page (first screen).
    Raw button

  3. Check the code and install it.

Better way to find last used row

How is this?

dim rownum as integer
dim colnum as integer
dim lstrow as integer
dim lstcol as integer
dim r as range

'finds the last row

lastrow = ActiveSheet.UsedRange.Rows.Count

'finds the last column

lastcol = ActiveSheet.UsedRange.Columns.Count

'sets the range

set r = range(cells(rownum,colnum), cells(lstrow,lstcol))

PHP: How to check if a date is today, yesterday or tomorrow

<?php 
 $current = strtotime(date("Y-m-d"));
 $date    = strtotime("2014-09-05");

 $datediff = $date - $current;
 $difference = floor($datediff/(60*60*24));
 if($difference==0)
 {
    echo 'today';
 }
 else if($difference > 1)
 {
    echo 'Future Date';
 }
 else if($difference > 0)
 {
    echo 'tomorrow';
 }
 else if($difference < -1)
 {
    echo 'Long Back';
 }
 else
 {
    echo 'yesterday';
 }  
?>

Android: How do I get string from resources using its name?

Verify if your packageName is correct. You have to refer for the root package of your Android application.

private String getStringResourceByName(String aString) {
      String packageName = getPackageName();
      int resId = getResources().getIdentifier(aString, "string", packageName);
      return getString(resId);
    }

How can I find the number of elements in an array?

void numel(int array1[100][100])
{
    int count=0;
    for(int i=0;i<100;i++)
    {
        for(int j=0;j<100;j++)
        {
            if(array1[i][j]!='\0') 
            {
                count++;
                //printf("\n%d-%d",array1[i][j],count);
            }
            else 
                break;
        }
    }
    printf("Number of elements=%d",count);
}
int main()
{   
    int r,arr[100][100]={0},c;
    printf("Enter the no. of rows: ");
    scanf("%d",&r);
    printf("\nEnter the no. of columns: ");
    scanf("%d",&c);
    printf("\nEnter the elements: ");
    for(int i=0;i<r;i++)
    {
        for(int j=0;j<c;j++)
        {
            scanf("%d",&arr[i][j]);
        }
    }
    numel(arr);
}

This shows the exact number of elements in matrix irrespective of the array size you mentioned while initilasing(IF that's what you meant)

How to compare only date in moment.js

You could use startOf('day') method to compare just the date

Example :

var dateToCompare = moment("06/04/2015 18:30:00");
var today = moment(new Date());

dateToCompare.startOf('day').isSame(today.startOf('day'));

Is gcc's __attribute__((packed)) / #pragma pack unsafe?

(The following is a very artificial example cooked up to illustrate.) One major use of packed structs is where you have a stream of data (say 256 bytes) to which you wish to supply meaning. If I take a smaller example, suppose I have a program running on my Arduino which sends via serial a packet of 16 bytes which have the following meaning:

0: message type (1 byte)
1: target address, MSB
2: target address, LSB
3: data (chars)
...
F: checksum (1 byte)

Then I can declare something like

typedef struct {
  uint8_t msgType;
  uint16_t targetAddr; // may have to bswap
  uint8_t data[12];
  uint8_t checksum;
} __attribute__((packed)) myStruct;

and then I can refer to the targetAddr bytes via aStruct.targetAddr rather than fiddling with pointer arithmetic.

Now with alignment stuff happening, taking a void* pointer in memory to the received data and casting it to a myStruct* will not work unless the compiler treats the struct as packed (that is, it stores data in the order specified and uses exactly 16 bytes for this example). There are performance penalties for unaligned reads, so using packed structs for data your program is actively working with is not necessarily a good idea. But when your program is supplied with a list of bytes, packed structs make it easier to write programs which access the contents.

Otherwise you end up using C++ and writing a class with accessor methods and stuff that does pointer arithmetic behind the scenes. In short, packed structs are for dealing efficiently with packed data, and packed data may be what your program is given to work with. For the most part, you code should read values out of the structure, work with them, and write them back when done. All else should be done outside the packed structure. Part of the problem is the low level stuff that C tries to hide from the programmer, and the hoop jumping that is needed if such things really do matter to the programmer. (You almost need a different 'data layout' construct in the language so that you can say 'this thing is 48 bytes long, foo refers to the data 13 bytes in, and should be interpreted thus'; and a separate structured data construct, where you say 'I want a structure containing two ints, called alice and bob, and a float called carol, and I don't care how you implement it' -- in C both these use cases are shoehorned into the struct construct.)

How do I create a basic UIButton programmatically?

In Swift 5 and Xcode 10.2

Basically we have two types of buttons.

1) System type button

2) Custom type button (In custom type button we can set background image for button)

And these two types of buttons has few control states https://developer.apple.com/documentation/uikit/uicontrol/state

Important states are

1) Normal state

2) Selected state

3) Highlighted state

4) Disabled state etc...

//For system type button
let button = UIButton(type: .system)
button.frame = CGRect(x: 100, y: 250, width: 100, height: 50)
//  button.backgroundColor = .blue
button.setTitle("Button", for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 13.0)
button.titleLabel?.textAlignment = .center//Text alighment center
button.titleLabel?.numberOfLines = 0//To display multiple lines in UIButton
button.titleLabel?.lineBreakMode = .byWordWrapping//By word wrapping
button.tag = 1//To assign tag value
button.btnProperties()//Call UIButton properties from extension function
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)

//For custom type button (add image to your button)
let button2 = UIButton(type: .custom)
button2.frame = CGRect(x: 100, y: 400, width: 100, height: 50)
//        button2.backgroundColor = .blue
button2.setImage(UIImage.init(named: "img.png"), for: .normal)
button2.tag = 2
button2.btnProperties()//Call UIButton properties from extension function
button2.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button2)

@objc func buttonClicked(sender:UIButton) {
    print("Button \(sender.tag) clicked")
}

//You can add UIButton properties using extension
extension UIButton {
    func btnProperties() {
        layer.cornerRadius = 10//Set button corner radious
        clipsToBounds = true
        backgroundColor = .blue//Set background colour
        //titleLabel?.textAlignment = .center//add properties like this
    }
}

Plotting with C#

I started using the new ASP.NET Chart control a few days ago, and it's absolutely amazing in its capabilities.

Here is the link.

EDIT: This is obviously only if you are using ASP.NET. Not sure about WinForms.

in linux terminal, how do I show the folder's last modification date, taking its content into consideration?

Something like:

find /path/ -type f -exec stat \{} --printf="%y\n" \; | 
     sort -n -r | 
     head -n 1

Explanation:

  • the find command will print modification time for every file recursively ignoring directories (according to the comment by IQAndreas you can't rely on the folders timestamps)
  • sort -n (numerically) -r (reverse)
  • head -n 1: get the first entry

How do I grant read access for a user to a database in SQL Server?

This is a two-step process:

  1. you need to create a login to SQL Server for that user, based on its Windows account

    CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
    
  2. you need to grant this login permission to access a database:

    USE (your database)
    CREATE USER (username) FOR LOGIN (your login name)
    

Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader database role to read all tables.

USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'

CodeIgniter: Load controller within controller

Just to add more information to what Zain Abbas said:

Load the controller that way, and use it like he said:

$this->load->library('../controllers/instructor');

$this->instructor->functioname();

Or you can create an object and use it this way:

$this->load->library('../controllers/your_controller');

$obj = new $this->your_controller();

$obj->your_function();

Hope this can help.

How to merge many PDF files into a single one?

First, get Pdftk:

sudo apt-get install pdftk

Now, as shown on example page, use

pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf

for merging pdf files into one.

Find the closest ancestor element that has a specific class

Update: Now supported in most major browsers

document.querySelector("p").closest(".near.ancestor")

Note that this can match selectors, not just classes

https://developer.mozilla.org/en-US/docs/Web/API/Element.closest


For legacy browsers that do not support closest() but have matches() one can build selector-matching similar to @rvighne's class matching:

function findAncestor (el, sel) {
    while ((el = el.parentElement) && !((el.matches || el.matchesSelector).call(el,sel)));
    return el;
}

How to apply font anti-alias effects in CSS?

Works the best. If you want to use it sitewide, without having to add this syntax to every class or ID, add the following CSS to your css body:

body { 
    -webkit-font-smoothing: antialiased;
    text-shadow: 1px 1px 1px rgba(0,0,0,0.004);
    background: url('./images/background.png');
    text-align: left;
    margin: auto;

}

Find element in List<> that contains a value

Using function Find is cleaner way.

MyClass item = MyList.Find(item => item.name == "foo");
if (item != null) // check item isn't null
{
 ....
}

How to create a link to another PHP page

echo "<a href='index.php'>Index Page</a>";

if you wanna use html tag like anchor tag you have to put in echo

WPF MVVM: How to close a window

The solution to close a window in wpf that that worked for me is not answered here so i thought i would add my solution too.

        private static Window GetWindow(DependencyObject sender)
        {
            Window window = null;
            if (sender is Window)
                window = (Window)sender;
            if (window == null)
                window = Window.GetWindow(sender);
            return window;
        }
        private void CloseWindow(object sender, RoutedEventArgs e)
        {
            var button = (Button)sender as DependencyObject;

            Window window = GetWindow(button);
                if (window != null)
                    window.Close();
                   // window.Visibility = Visibility.Hidden; 
           // choose between window.close or set window.visibility to close or hide the window.

            //            }
        }

Add CloseWindow event to the button in you window as following.

<Button Content="Cancel" Click="CloseWindow" >

How do you specifically order ggplot2 x axis instead of alphabetical order?

It is a little difficult to answer your specific question without a full, reproducible example. However something like this should work:

#Turn your 'treatment' column into a character vector
data$Treatment <- as.character(data$Treatment)
#Then turn it back into a factor with the levels in the correct order
data$Treatment <- factor(data$Treatment, levels=unique(data$Treatment))

In this example, the order of the factor will be the same as in the data.csv file.

If you prefer a different order, you can order them by hand:

data$Treatment <- factor(data$Treatment, levels=c("Y", "X", "Z"))

However this is dangerous if you have a lot of levels: if you get any of them wrong, that will cause problems.

Why does corrcoef return a matrix?

Consider using matplotlib.cbook pieces

for example:

import matplotlib.cbook as cbook
segments = cbook.pieces(np.arange(20), 3)
for s in segments:
     print s

PHP, Get tomorrows date from date

 $tomorrow = date("Y-m-d", strtotime('tomorrow'));

or

  $tomorrow = date("Y-m-d", strtotime("+1 day"));

Help Link: STRTOTIME()

Extract images from PDF without resampling, in python?

Often in a PDF, the image is simply stored as-is. For example, a PDF with a jpg inserted will have a range of bytes somewhere in the middle that when extracted is a valid jpg file. You can use this to very simply extract byte ranges from the PDF. I wrote about this some time ago, with sample code: Extracting JPGs from PDFs.

How to get the values of a ConfigurationSection of type NameValueSectionHandler

Here's a good post that shows how to do it.

If you want to read the values from a file other than the app.config, you need to load it into the ConfigurationManager.

Try this method: ConfigurationManager.OpenMappedExeConfiguration()

There's an example of how to use it in the MSDN article.

Double decimal formatting in Java

new DecimalFormat("#0.00").format(4.0d);

What is the Java equivalent for LINQ?

There is no equivalent to LINQ for Java. But there is some of the external API which is looks like LINQ such as https://github.com/nicholas22/jpropel-light, https://code.google.com/p/jaque/

Choose File Dialog

Was looking for a file/folder browser myself recently and decided to make a new explorer activity (Android library): https://github.com/vaal12/AndroidFileBrowser

Matching Test application https://github.com/vaal12/FileBrowserTestApplication- is a sample how to use.

Allows picking directories and files from phone file structure.

How to split a large text file into smaller files with equal number of lines?

split the file "file.txt" into 10000 lines files:

split -l 10000 file.txt

Installing python module within code

import os
os.system('pip install requests')

I tried above for temporary solution instead of changing docker file. Hope these might be useful to some

Stop an input field in a form from being submitted

Simple try to remove name attribute from input element.
So it has to look like

<input type="checkbox" checked="" id="class_box_2" value="2">

How to Fill an array from user input C#?

It made a lot more sense to add this as an answer to arin's code than to keep doing it in comments...

1) Consider using decimal instead of double. It's more likely to give the answer the user expects. See http://pobox.com/~skeet/csharp/floatingpoint.html and http://pobox.com/~skeet/csharp/decimal.html for reasons why. Basically decimal works a lot closer to how humans think about numbers than double does. Double works more like how computers "naturally" think about numbers, which is why it's faster - but that's not relevant here.

2) For user input, it's usually worth using a method which doesn't throw an exception on bad input - e.g. decimal.TryParse and int.TryParse. These return a Boolean value to say whether or not the parse succeeded, and use an out parameter to give the result. If you haven't started learning about out parameters yet, it might be worth ignoring this point for the moment.

3) It's only a little point, but I think it's wise to have braces round all "for"/"if" (etc) bodies, so I'd change this:

for (int counter = 0; counter < 6; counter++)
    Console.WriteLine("{0,5}{1,8}", counter, array[counter]);

to this:

for (int counter = 0; counter < 6; counter++)
{
    Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
}

It makes the block clearer, and means you don't accidentally write:

for (int counter = 0; counter < 6; counter++)
    Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
    Console.WriteLine("----"); // This isn't part of the for loop!

4) Your switch statement doesn't have a default case - so if the user types anything other than "yes" or "no" it will just ignore them and quit. You might want to have something like:

bool keepGoing = true;
while (keepGoing)
{
    switch (answer)
    {
        case "yes":
            Console.WriteLine("===============================================");
            Console.WriteLine("please enter the array index you wish to get the value of it");
            int index = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("===============================================");
            Console.WriteLine("The Value of the selected index is:");
            Console.WriteLine(array[index]);
            keepGoing = false;
            break;

        case "no":
            Console.WriteLine("===============================================");
            Console.WriteLine("HAVE A NICE DAY SIR");
            keepGoing = false;
            break;

        default:
            Console.WriteLine("Sorry, I didn't understand that. Please enter yes or no");
            break;
    }
}

5) When you've started learning about LINQ, you might want to come back to this and replace your for loop which sums the input as just:

// Or decimal, of course, if you've made the earlier selected change
double sum = input.Sum();

Again, this is fairly advanced - don't worry about it for now!

How do I change the IntelliJ IDEA default JDK?

  • I am using IntelliJ IDEA 14.0.3, and I also have same question. Choose menu File \ Other Settings \ Default Project Structure...

enter image description here

  • Choose Project tab, section Project language level, choose level from dropdown list, this setting is default for all new project.

    enter image description here

how to select first N rows from a table in T-SQL?

You can also use rowcount, but TOP is probably better and cleaner, hence the upvote for Mehrdad

SET ROWCOUNT 10
SELECT * FROM dbo.Orders
WHERE EmployeeID = 5
ORDER BY OrderDate

SET ROWCOUNT 0

What properties does @Column columnDefinition make redundant?

My Answer: All of the following should be overridden (i.e. describe them all within columndefinition, if appropriate):

  • length
  • precision
  • scale
  • nullable
  • unique

i.e. the column DDL will consist of: name + columndefinition and nothing else.

Rationale follows.


  1. Annotation containing the word "Column" or "Table" is purely physical - properties only used to control DDL/DML against database.

  2. Other annotation purely logical - properties used in-memory in java to control JPA processing.

  3. That's why sometimes it appears the optionality/nullability is set twice - once via @Basic(...,optional=true) and once via @Column(...,nullable=true). Former says attribute/association can be null in the JPA object model (in-memory), at flush time; latter says DB column can be null. Usually you'd want them set the same - but not always, depending on how the DB tables are setup and reused.

In your example, length and nullable properties are overridden and redundant.


So, when specifying columnDefinition, what other properties of @Column are made redundant?

  1. In JPA Spec & javadoc:

    • columnDefinition definition: The SQL fragment that is used when generating the DDL for the column.

    • columnDefinition default: Generated SQL to create a column of the inferred type.

    • The following examples are provided:

      @Column(name="DESC", columnDefinition="CLOB NOT NULL", table="EMP_DETAIL")
      @Column(name="EMP_PIC", columnDefinition="BLOB NOT NULL")
      
    • And, err..., that's it really. :-$ ?!

    Does columnDefinition override other properties provided in the same annotation?

    The javadoc and JPA spec don't explicity address this - spec's not giving great protection. To be 100% sure, test with your chosen implementation.

  2. The following can be safely implied from examples provided in the JPA spec

    • name & table can be used in conjunction with columnDefinition, neither are overridden
    • nullable is overridden/made redundant by columnDefinition
  3. The following can be fairly safely implied from the "logic of the situation" (did I just say that?? :-P ):

    • length, precision, scale are overridden/made redundant by the columnDefinition - they are integral to the type
    • insertable and updateable are provided separately and never included in columnDefinition, because they control SQL generation in-memory, before it is emmitted to the database.
  4. That leaves just the "unique" property. It's similar to nullable - extends/qualifies the type definition, so should be treated integral to type definition. i.e. should be overridden.


Test My Answer For columns "A" & "B", respectively:

  @Column(name="...", table="...", insertable=true, updateable=false,
          columndefinition="NUMBER(5,2) NOT NULL UNIQUE"

  @Column(name="...", table="...", insertable=false, updateable=true,
          columndefinition="NVARCHAR2(100) NULL"
  • confirm generated table has correct type/nullability/uniqueness
  • optionally, do JPA insert & update: former should include column A, latter column B

How can I check if a Perl array contains a particular value?

Method 1: grep (may careful while value is expected to be a regex).

Try to avoid using grep, if looking at resources.

if ( grep( /^$value$/, @badparams ) ) {
  print "found";
}

Method 2: Linear Search

for (@badparams) {
    if ($_ eq $value) {
       print "found";
       last;
    }
}

Method 3: Use a hash

my %hash = map {$_ => 1} @badparams;
print "found" if (exists $hash{$value});

Method 4: smartmatch

(added in Perl 5.10, marked is experimental in Perl 5.18).

use experimental 'smartmatch';  # for perl 5.18
print "found" if ($value ~~ @badparams);

Method 5: Use the module List::MoreUtils

use List::MoreUtils qw(any);
@badparams = (1,2,3);
$value = 1;
print "found" if any {$_ == $value} @badparams;

Java - Reading XML file

One of the possible implementations:

File file = new File("userdata.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
        .newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
String usr = document.getElementsByTagName("user").item(0).getTextContent();
String pwd = document.getElementsByTagName("password").item(0).getTextContent();

when used with the XML content:

<credentials>
    <user>testusr</user>
    <password>testpwd</password>
</credentials>

results in "testusr" and "testpwd" getting assigned to the usr and pwd references above.

In Python try until no error

Like most of the others, I'd recommend trying a finite number of times and sleeping between attempts. This way, you don't find yourself in an infinite loop in case something were to actually happen to the remote server.

I'd also recommend continuing only when you get the specific exception you're expecting. This way, you can still handle exceptions you might not expect.

from urllib.error import HTTPError
import traceback
from time import sleep


attempts = 10
while attempts > 0:
    try:
        #code with possible error
    except HTTPError:
        attempts -= 1
        sleep(1)
        continue
    except:
        print(traceback.format_exc())

    #the rest of the code
    break

Also, you don't need an else block. Because of the continue in the except block, you skip the rest of the loop until the try block works, the while condition gets satisfied, or an exception other than HTTPError comes up.

Adding a directory to the PATH environment variable in Windows

If you run the command cmd, it will update all system variables for that command window.

MVVM: Tutorial from start to finish?

I have written an application using WPF, Prism and MVVM to simulate hiring a cab, you can read about it on my blog, download the source here and play with it.

Uploading images using Node.js, Express, and Mongoose

Here's a way to upload your images using the formidable package, which is recommended over bodyParser in later versions of Express. This also includes the ability to resize your images on the fly:

From my website: Uploading and Resizing Images (on the fly) With Node.js and Express.

Here's the gist:

var express = require("express"),
app = express(),
formidable = require('formidable'),
util = require('util')
fs   = require('fs-extra'),
qt   = require('quickthumb');

// Use quickthumb
app.use(qt.static(__dirname + '/'));

app.post('/upload', function (req, res){
  var form = new formidable.IncomingForm();
  form.parse(req, function(err, fields, files) {
    res.writeHead(200, {'content-type': 'text/plain'});
    res.write('received upload:\n\n');
    res.end(util.inspect({fields: fields, files: files}));
  });

  form.on('end', function(fields, files) {
    /* Temporary location of our uploaded file */
    var temp_path = this.openedFiles[0].path;
    /* The file name of the uploaded file */
    var file_name = this.openedFiles[0].name;
    /* Location where we want to copy the uploaded file */
    var new_location = 'uploads/';

    fs.copy(temp_path, new_location + file_name, function(err) {  
      if (err) {
        console.error(err);
      } else {
        console.log("success!")
      }
    });
  });
});

// Show the upload form 
app.get('/', function (req, res){
  res.writeHead(200, {'Content-Type': 'text/html' });
  /* Display the file upload form. */
  form = '<form action="/upload" enctype="multipart/form-data" method="post">'+ '<input name="title" type="text" />
  '+ '<input multiple="multiple" name="upload" type="file" />
  '+ '<input type="submit" value="Upload" />'+ '</form>';
  res.end(form); 
}); 
app.listen(8080);

NOTE: This requires Image Magick for the quick thumb resizing.

How do I tell CMake to link in a static library in the source directory?

I found this helpful...

http://www.cmake.org/pipermail/cmake/2011-June/045222.html

From their example:

ADD_LIBRARY(boost_unit_test_framework STATIC IMPORTED)
SET_TARGET_PROPERTIES(boost_unit_test_framework PROPERTIES IMPORTED_LOCATION /usr/lib/libboost_unit_test_framework.a)
TARGET_LINK_LIBRARIES(mytarget A boost_unit_test_framework C)

"unary operator expected" error in Bash if condition

You can also set a default value for the variable, so you don't need to use two "[", which amounts to two processes ("[" is actually a program) instead of one.

It goes by this syntax: ${VARIABLE:-default}.

The whole thing has to be thought in such a way that this "default" value is something distinct from a "valid" value/content.

If that's not possible for some reason you probably need to add a step like checking if there's a value at all, along the lines of "if [ -z $VARIABLE ] ; then echo "the variable needs to be filled"", or "if [ ! -z $VARIABLE ] ; then #everything is fine, proceed with the rest of the script".

How to Insert Double or Single Quotes

Easier steps:

  1. Highlight the cells you want to add the quotes.
  2. Go to Format–>Cells–>Custom
  3. Copy/Paste the following into the Type field: \"@\" or \'@\'
  4. Done!

XPath using starts-with function

Try this

//ITEM/*[starts-with(text(),'2552')]/following-sibling::*

Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException

This could also be the case when you have too many object references. Take a look at the results from the build, esp in the task :dex:multiDebug:

trouble writing output: Too many method references: 67114; max is 65536.

When should I use git pull --rebase?

I think you should use git pull --rebase when collaborating with others on the same branch. You are in your work ? commit ? work ? commit cycle, and when you decide to push your work your push is rejected, because there's been parallel work on the same branch. At this point I always do a pull --rebase. I do not use squash (to flatten commits), but I rebase to avoid the extra merge commits.

As your Git knowledge increases you find yourself looking a lot more at history than with any other version control systems I've used. If you have a ton of small merge commits, it's easy to lose focus of the bigger picture that's happening in your history.

This is actually the only time I do rebasing(*), and the rest of my workflow is merge based. But as long as your most frequent committers do this, history looks a whole lot better in the end.

(*) While teaching a Git course, I had a student arrest me on this, since I also advocated rebasing feature branches in certain circumstances. And he had read this answer ;) Such rebasing is also possible, but it always has to be according to a pre-arranged/agreed system, and as such should not "always" be applied. And at that time I usually don't do pull --rebase either, which is what the question is about ;)

Move cursor to end of file in vim

I thought the question was "Move cursor to end of file in vim" ?

End-of-file: Esc + G
Begin-of-file Esc + g (or gg if you are already in the command area)

What is "origin" in Git?

From https://www.git-tower.com/learn/git/glossary/origin:

In Git, "origin" is a shorthand name for the remote repository that a project was originally cloned from. More precisely, it is used instead of that original repository's URL - and thereby makes referencing much easier.

Note that origin is by no means a "magical" name, but just a standard convention. Although it makes sense to leave this convention untouched, you could perfectly rename it without losing any functionality.

In the following example, the URL parameter to the "clone" command becomes the "origin" for the cloned local repository:

git clone https://github.com/gittower/git-crash-course.git

Number of occurrences of a character in a string

Here is the most inefficient way to get the count in all answers. But you'll get a Dictionary that contains key-value pairs as a bonus.

string test = "key1=value1&key2=value2&key3=value3";

var keyValues = Regex.Matches(test, @"([\w\d]+)=([\w\d]+)[&$]*")
                     .Cast<Match>()
                     .ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);

var count = keyValues.Count - 1;

Get ID of element that called a function

I'm surprised that nobody has mentioned the use of this in the event handler. It works automatically in modern browsers and can be made to work in other browsers. If you use addEventListener or attachEvent to install your event handler, then you can make the value of this automatically be assigned to the object the created the event.

Further, the user of programmatically installed event handlers allows you to separate javascript code from HTML which is often considered a good thing.

Here's how you would do that in your code in plain javascript:

Remove the onmouseover="zoom()" from your HTML and install the event handler in your javascript like this:

// simplified utility function to register an event handler cross-browser
function setEventHandler(obj, name, fn) {
    if (typeof obj == "string") {
        obj = document.getElementById(obj);
    }
    if (obj.addEventListener) {
        return(obj.addEventListener(name, fn));
    } else if (obj.attachEvent) {
        return(obj.attachEvent("on" + name, function() {return(fn.call(obj));}));
    }
}

function zoom() {
    // you can use "this" here to refer to the object that caused the event
    // this here will refer to the calling object (which in this case is the <map>)
    console.log(this.id);
    document.getElementById("preview").src="http://photos.smugmug.com/photos/344290962_h6JjS-Ti.jpg";
}

// register your event handler
setEventHandler("nose", "mouseover", zoom);

Making HTML page zoom by default

A better solution is not to make your page dependable on zoom settings. If you set limits like the one you are proposing, you are limiting accessibility. If someone cannot read your text well, they just won't be able to change that. I would use proper CSS to make it look nice in any zoom.

If your really insist, take a look at this question on how to detect zoom level using JavaScript (nightmare!): How to detect page zoom level in all modern browsers?

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

Errors: "Bad encrypt / decrypt" "gitencrypt_smudge: FAILURE: openssl error decrypting file"

There are various error strings that are thrown from openssl, depending on respective versions, and scenarios. Below is the checklist I use in case of openssl related issues:

  1. Ideally, openssl is able to encrypt/decrypt using same key (+ salt) & enc algo only.
  2. Ensure that openssl versions (used to encrypt/decrypt), are compatible. For eg. the hash used in openssl changed at version 1.1.0 from MD5 to SHA256. This produces a different key from the same password. Fix: add "-md md5" in 1.1.0 to decrypt data from lower versions, and add "-md sha256 in lower versions to decrypt data from 1.1.0

  3. Ensure that there is a single openssl version installed in your machine. In case there are multiple versions installed simultaneously (in my machine, these were installed :- 'LibreSSL 2.6.5' and 'openssl 1.1.1d'), make the sure that only the desired one appears in your PATH variable.