Programs & Examples On #Currentuiculture

Is there a way of setting culture for a whole application? All current threads and new threads?

For .NET 4.5 and higher, you should use:

var culture = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;

C# DateTime to "YYYYMMDDHHMMSS" format

This site has great examples check it out

// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}",      dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}",      dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}",      dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",          dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",               dt);  // "5 05"            minute
String.Format("{0:s ss}",               dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}",      dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}",      dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",               dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",           dt);  // "-6 -06 -06:00"   time zone

// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}",           dt);  // "3/9/2008"
String.Format("{0:MM/dd/yyyy}",         dt);  // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}",   dt);  // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt);  // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}",           dt);  // "03/09/08"
String.Format("{0:MM/dd/yyyy}",         dt);  // "03/09/2008"

Standard DateTime Formatting

String.Format("{0:t}", dt);  // "4:05 PM"                           ShortTime
String.Format("{0:d}", dt);  // "3/9/2008"                          ShortDate
String.Format("{0:T}", dt);  // "4:05:07 PM"                        LongTime
String.Format("{0:D}", dt);  // "Sunday, March 09, 2008"            LongDate
String.Format("{0:f}", dt);  // "Sunday, March 09, 2008 4:05 PM"    LongDate+ShortTime
String.Format("{0:F}", dt);  // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt);  // "3/9/2008 4:05 PM"                  ShortDate+ShortTime
String.Format("{0:G}", dt);  // "3/9/2008 4:05:07 PM"               ShortDate+LongTime
String.Format("{0:m}", dt);  // "March 09"                          MonthDay
String.Format("{0:y}", dt);  // "March, 2008"                       YearMonth
String.Format("{0:r}", dt);  // "Sun, 09 Mar 2008 16:05:07 GMT"     RFC1123
String.Format("{0:s}", dt);  // "2008-03-09T16:05:07"               SortableDateTime
String.Format("{0:u}", dt);  // "2008-03-09 16:05:07Z"              UniversalSortableDateTime

/*
Specifier   DateTimeFormatInfo property     Pattern value (for en-US culture)
    t           ShortTimePattern                    h:mm tt
    d           ShortDatePattern                    M/d/yyyy
    T           LongTimePattern                     h:mm:ss tt
    D           LongDatePattern                     dddd, MMMM dd, yyyy
    f           (combination of D and t)            dddd, MMMM dd, yyyy h:mm tt
    F           FullDateTimePattern                 dddd, MMMM dd, yyyy h:mm:ss tt
    g           (combination of d and t)            M/d/yyyy h:mm tt
    G           (combination of d and T)            M/d/yyyy h:mm:ss tt
    m, M        MonthDayPattern                     MMMM dd
    y, Y        YearMonthPattern                    MMMM, yyyy
    r, R        RFC1123Pattern                      ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
    s           SortableDateTi­mePattern             yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
    u           UniversalSorta­bleDateTimePat­tern    yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
                                                    (*) = culture independent   
*/

Update using c# 6 string interpolation format

// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

$"{dt:y yy yyy yyyy}";  // "8 08 008 2008"   year
$"{dt:M MM MMM MMMM}";  // "3 03 Mar March"  month
$"{dt:d dd ddd dddd}";  // "9 09 Sun Sunday" day
$"{dt:h hh H HH}";      // "4 04 16 16"      hour 12/24
$"{dt:m mm}";           // "5 05"            minute
$"{dt:s ss}";           // "7 07"            second
$"{dt:f ff fff ffff}";  // "1 12 123 1230"   sec.fraction
$"{dt:F FF FFF FFFF}";  // "1 12 123 123"    without zeroes
$"{dt:t tt}";           // "P PM"            A.M. or P.M.
$"{dt:z zz zzz}";       // "-6 -06 -06:00"   time zone

// month/day numbers without/with leading zeroes
$"{dt:M/d/yyyy}";    // "3/9/2008"
$"{dt:MM/dd/yyyy}";  // "03/09/2008"

// day/month names
$"{dt:ddd, MMM d, yyyy}";    // "Sun, Mar 9, 2008"
$"{dt:dddd, MMMM d, yyyy}";  // "Sunday, March 9, 2008"

// two/four digit year
$"{dt:MM/dd/yy}";    // "03/09/08"
$"{dt:MM/dd/yyyy}";  // "03/09/2008"

npm notice created a lockfile as package-lock.json. You should commit this file

Yes. You should add this file to your version control system, i.e. You should commit it.

This file is intended to be committed into source repositories

You can read more about what it is/what it does here:

package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.

Why do I have ORA-00904 even when the column is present?

I use Toad for Oracle and if the table is owned by another username than the one you logged in as and you have access to read the table, you still may need to add the original table owner to the table name.

For example, lets say the table owner's name is 'OWNER1' and you are logged in as 'USER1'. This query may give you a ORA-00904 error:

select * from table_name where x='test';

Prefixing the table_name with the table owner eliminated the error and gives results:

select * from 

What is Teredo Tunneling Pseudo-Interface?

Is to do with IPv6

All the gory details here: http://www.microsoft.com/technet/network/ipv6/teredo.mspx

Some people have had issues with it, and disabled it, but as a general rule, if it aint broke...

Get Absolute Position of element within the window in wpf

I think what BrandonS wants is not the position of the mouse relative to the root element, but rather the position of some descendant element.

For that, there is the TransformToAncestor method:

Point relativePoint = myVisual.TransformToAncestor(rootVisual)
                              .Transform(new Point(0, 0));

Where myVisual is the element that was just double-clicked, and rootVisual is Application.Current.MainWindow or whatever you want the position relative to.

exclude @Component from @ComponentScan

Using explicit types in scan filters is ugly for me. I believe more elegant approach is to create own marker annotation:

@Retention(RetentionPolicy.RUNTIME)
public @interface IgnoreDuringScan {
}

Mark component that should be excluded with it:

@Component("foo") 
@IgnoreDuringScan
class Foo {
    ...
}

And exclude this annotation from your component scan:

@ComponentScan(excludeFilters = @Filter(IgnoreDuringScan.class))
public class MySpringConfiguration {}

If two cells match, return value from third

All you have to do is write an IF condition in the column d like this:

=IF(A1=C1;B1;" ")

After that just apply this formula to all rows above that one.

How do you print in Sublime Text 2

One way to print your code is to push it to an online version control system like Github or Bitbucket. In your browser, navigate to the file and print it.

Doing it this way, you'll get syntax highlighting and version control.

converting drawable resource image into bitmap

Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.my_drawable);

Context can be your current Activity.

ClassCastException, casting Integer to Double

We can cast an int to a double but we can't do the same with the wrapper classes Integer and Double:

 int     a = 1;
 Integer b = 1;   // inboxing, requires Java 1.5+

 double  c = (double) a;   // OK
 Double  d = (Double) b;   // No way.

This shows the compile time error that corresponds to your runtime exception.

How to run a PowerShell script

Type:

powershell -executionpolicy bypass -File .\Test.ps1

NOTE: Here Test.ps1 is the PowerShell script.

setting an environment variable in virtualenv

Another way to do it that's designed for django, but should work in most settings, is to use django-dotenv.

Restoring database from .mdf and .ldf files of SQL Server 2008

Yes, it is possible. The steps are:

  1. First Put the .mdf and .ldf file in C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\ folder

  2. Then go to sql software , Right-click “Databases” and click the “Attach” option to open the Attach Databases dialog box

  3. Click the “Add” button to open and Locate Database Files From C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\folder

  4. Click the "OK" button. SQL Server Management Studio loads the database from the .MDF file.

How to fix System.NullReferenceException: Object reference not set to an instance of an object

If the problem is 100% here

EffectSelectorForm effectSelectorForm = new EffectSelectorForm(Effects);

There's only one possible explanation: property/variable "Effects" is not initialized properly... Debug your code to see what you pass to your objects.

EDIT after several hours

There were some problems:

  • MEF attribute [Import] didn't work as expected, so we replaced it for the time being with a manually populated List<>. While the collection was null, it was causing exceptions later in the code, when the method tried to get the type of the selected item and there was none.

  • several event handlers weren't wired up to control events

Some problems are still present, but I believe OP's original problem has been fixed. Other problems are not related to this one.

C++ initial value of reference to non-const must be an lvalue

The &nKByte creates a temporary value, which cannot be bound to a reference to non-const.

You could change void test(float *&x) to void test(float * const &x) or you could just drop the pointer altogether and use void test(float &x); /*...*/ test(nKByte);.

How do I initialize a byte array in Java?

byte[] myvar = "Any String you want".getBytes();

String literals can be escaped to provide any character:

byte[] CDRIVES = "\u00e0\u004f\u00d0\u0020\u00ea\u003a\u0069\u0010\u00a2\u00d8\u0008\u0000\u002b\u0030\u0030\u009d".getBytes();

Custom li list-style with font-awesome icon

I did two things inspired by @OscarJovanny comment, with some hacks.

Step 1:

  • Download icons file as svg from Here, as I only need only this icon from font awesome

Step 2:

<style>
ul {
    list-style-type: none;
    margin-left: 10px;
}

ul li {
    margin-bottom: 12px;
    margin-left: -10px;
    display: flex;
    align-items: center;
}

ul li::before {
    color: transparent;
    font-size: 1px;
    content: " ";
    margin-left: -1.3em;
    margin-right: 15px;
    padding: 10px;
    background-color: orange;
    -webkit-mask-image: url("./assets/img/check-circle-solid.svg");
    -webkit-mask-size: cover;
}
</style>

Results

enter image description here

Multiplication on command line terminal

I have a simple script I use for this:

me@mycomputer:~$ cat /usr/local/bin/c

#!/bin/sh

echo "$*" | sed 's/x/\*/g' | bc -l

It changes x to * since * is a special character in the shell. Use it as follows:

  • c 5x5
  • c 5-4.2 + 1
  • c '(5 + 5) * 30' (you still have to use quotes if the expression contains any parentheses).

Iterate through a C array

You can store the size somewhere, or you can have a struct with a special value set that you use as a sentinel, the same way that '\0' indicates the end of a string.

Declare multiple module.exports in Node.js

also you can export it like this

const func1 = function (){some code here}
const func2 = function (){some code here}
exports.func1 = func1;
exports.func2 = func2;

or for anonymous functions like this

    const func1 = ()=>{some code here}
    const func2 = ()=>{some code here}
    exports.func1 = func1;
    exports.func2 = func2;

Simple way to count character occurrences in a string

Not optimal, but simple way to count occurrences:

String s = "...";
int counter = s.split("\\$", -1).length - 1;

Note:

  • Dollar sign is a special Regular Expression symbol, so it must be escaped with a backslash.
  • A backslash is a special symbol for escape characters such as newlines, so it must be escaped with a backslash.
  • The second argument of split prevents empty trailing strings from being removed.

How can I multiply all items in a list together with Python?

If you want to avoid importing anything and avoid more complex areas of Python, you can use a simple for loop

product = 1  # Don't use 0 here, otherwise, you'll get zero 
             # because anything times zero will be zero.
list = [1, 2, 3]
for x in list:
    product *= x

visual c++: #include files from other projects in the same solution

#include has nothing to do with projects - it just tells the preprocessor "put the contents of the header file here". If you give it a path that points to the correct location (can be a relative path, like ../your_file.h) it will be included correctly.

You will, however, have to learn about libraries (static/dynamic libraries) in order to make such projects link properly - but that's another question.

Android Device Chooser -- device not showing up

In galaxy note 3 you need to enable the developer option. Access the "About Device" and click on the Build number multiple time until a message appear which telling you that the developer option has been enabled. Go back to general and there your go..the developer option has been enabled and select USB debugging option. This is for Galaxy note 3 N9005 Andriod 4.3.

How to resolve a Java Rounding Double issue

To control the precision of floating point arithmetic, you should use java.math.BigDecimal. Read The need for BigDecimal by John Zukowski for more information.

Given your example, the last line would be as following using BigDecimal.

import java.math.BigDecimal;

BigDecimal premium = BigDecimal.valueOf("1586.6");
BigDecimal netToCompany = BigDecimal.valueOf("708.75");
BigDecimal commission = premium.subtract(netToCompany);
System.out.println(commission + " = " + premium + " - " + netToCompany);

This results in the following output.

877.85 = 1586.6 - 708.75

Why is there no String.Empty in Java?

Seems like this is the obvious answer:

String empty = org.apache.commons.lang.StringUtils.EMPTY;

Awesome because "empty initialization" code no longer has a "magic string" and uses a constant.

Extract text from a string

Just to add a non-regex solution:

'(' + $myString.Split('()')[1] + ')'

This splits the string at the parentheses and takes the string from the array with the program name in it.

If you don't need the parentheses, just use:

$myString.Split('()')[1]

Getting a File's MD5 Checksum in Java

Using nio2 (Java 7+) and no external libraries:

byte[] b = Files.readAllBytes(Paths.get("/path/to/file"));
byte[] hash = MessageDigest.getInstance("MD5").digest(b);

To compare the result with an expected checksum:

String expected = "2252290BC44BEAD16AA1BF89948472E8";
String actual = DatatypeConverter.printHexBinary(hash);
System.out.println(expected.equalsIgnoreCase(actual) ? "MATCH" : "NO MATCH");

window.open with target "_blank" in Chrome

window.open(skey, "_blank", "toolbar=1, scrollbars=1, resizable=1, width=" + 1015 + ", height=" + 800);

What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?

Instead of defining: COLUMN_HEADINGS("columnHeadings")

Try defining it as: COLUMNHEADINGS("columnHeadings")

Then when you call getByName(String name) method, call it with the upper-cased String like this: getByName(myStringVariable.toUpperCase())

I had the same problem as you, and this worked for me.

Angular 4 default radio button checked by default

We can use [(ngModel)] in following way and have a value selection variable radioSelected

Example tutorial

Demo Link

app.component.html

  <div class="text-center mt-5">
  <h4>Selected value is {{radioSel.name}}</h4>

  <div>
    <ul class="list-group">
          <li class="list-group-item"  *ngFor="let item of itemsList">
            <input type="radio" [(ngModel)]="radioSelected" name="list_name" value="{{item.value}}" (change)="onItemChange(item)"/> 
            {{item.name}}

          </li>
    </ul>
  </div>


  <h5>{{radioSelectedString}}</h5>

  </div>

app.component.ts

  import {Item} from '../app/item';
  import {ITEMS} from '../app/mock-data';

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
  })
  export class AppComponent {
    title = 'app';
    radioSel:any;
    radioSelected:string;
    radioSelectedString:string;
    itemsList: Item[] = ITEMS;


      constructor() {
        this.itemsList = ITEMS;
        //Selecting Default Radio item here
        this.radioSelected = "item_3";
        this.getSelecteditem();
      }

      // Get row item from array  
      getSelecteditem(){
        this.radioSel = ITEMS.find(Item => Item.value === this.radioSelected);
        this.radioSelectedString = JSON.stringify(this.radioSel);
      }
      // Radio Change Event
      onItemChange(item){
        this.getSelecteditem();
      }

  }

Sample Data for Listing

        export const ITEMS: Item[] = [
            {
                name:'Item 1',
                value:'item_1'
            },
            {
                name:'Item 2',
                value:'item_2'
            },
            {
                name:'Item 3',
                value:'item_3'
            },
            {
                name:'Item 4',
                value:'item_4'
                },
                {
                    name:'Item 5',
                    value:'item_5'
                }
        ];

What is HTTP "Host" header?

I would always recommend going to the authoritative source when trying to understand the meaning and purpose of HTTP headers.

The "Host" header field in a request provides the host and port
information from the target URI, enabling the origin server to
distinguish among resources while servicing requests for multiple
host names on a single IP address.

https://tools.ietf.org/html/rfc7230#section-5.4

How to access site running apache server over lan without internet connection

Open httpd.conf of Apache server (backup first) Look for the the following : Listen

Change the line to

Listen *:80

Still in httpd.conf, look for the following (or similar):

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Allow from all
    Deny from all
</Directory>

Change this block to :

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Allow from all
    #Deny from all
</Directory>

Save httpd.conf and restart apache

Open port 80 of the server such that everyone can access your server.

Open Control Panel >> System and Security >> Windows Firewall then click on “Advance Setting” and then select “Inbound Rules” from the left panel and then click on “Add Rule…”. Select “PORT” as an option from the list and then in the next screen select “TCP” protocol and enter port number “80” under “Specific local port” then click on the ”Next” button and select “Allow the Connection” and then give the general name and description to this port and click Done.

Restart WAMP and access your machine in LAN or WAN.

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

Another addition: be careful when replacing multiples and converting the type of the column back from object to float. If you want to be certain that your None's won't flip back to np.NaN's apply @andy-hayden's suggestion with using pd.where. Illustration of how replace can still go 'wrong':

In [1]: import pandas as pd

In [2]: import numpy as np

In [3]: df = pd.DataFrame({"a": [1, np.NAN, np.inf]})

In [4]: df
Out[4]:
     a
0  1.0
1  NaN
2  inf

In [5]: df.replace({np.NAN: None})
Out[5]:
      a
0     1
1  None
2   inf

In [6]: df.replace({np.NAN: None, np.inf: None})
Out[6]:
     a
0  1.0
1  NaN
2  NaN

In [7]: df.where((pd.notnull(df)), None).replace({np.inf: None})
Out[7]:
     a
0  1.0
1  NaN
2  NaN

Android, landscape only orientation?

Yes, in AndroidManifest.xml, declare your Activity like so: <activity ... android:screenOrientation="landscape" .../>

invalid target release: 1.7

When maven is working outside of Eclipse, but giving this error after a JDK change, Go to your Maven Run Configuration, and at the bottom of the Main page, there's a 'Maven Runtime' option. Mine was using the Embedded Maven, so after switching it to use my external maven, it worked.

C pass int array pointer as parameter into a function

main()
{
    int *arr[5];
    int i=31, j=5, k=19, l=71, m;

    arr[0]=&i;
    arr[1]=&j;
    arr[2]=&k;
    arr[3]=&l;
    arr[4]=&m;

    for(m=0; m<=4; m++)
    {
        printf("%d",*(arr[m]));
    }
    return 0;
}

The equivalent of wrap_content and match_parent in flutter?

There are actually some options available:

You can use SizedBox.expand to make your widget match parents dimensions, or SizedBox(width: double.infinity) to match only the width or SizedBox(heigth: double.infinity) to match only the heigth.

If you want a wrap_content behavior it depends on the parent widget you are using, for example if you put a button on a column it will behave like wrap_content and to use it like match_parent you can wrap the button with a Expanded widget or a sizedbox.

With a ListView the button gets a match_parent behavior and to get a wrap_content behavior you can wrap it with a Flex widget like Row.

Using an Expanded widget makes a child of a Row, Column, or Flex expand to fill the available space in the main axis (e.g., horizontally for a Row or vertically for a Column). https://docs.flutter.io/flutter/widgets/Expanded-class.html

Using a Flexible widget gives a child of a Row, Column, or Flex the flexibility to expand to fill the available space in the main axis (e.g., horizontally for a Row or vertically for a Column), but, unlike Expanded, Flexible does not require the child to fill the available space. https://docs.flutter.io/flutter/widgets/Flexible-class.html

What exactly is LLVM?

According to 'Getting Started With LLVM Core Libraries' book (c):

In fact, the name LLVM might refer to any of the following:

  • The LLVM project/infrastructure: This is an umbrella for several projects that, together, form a complete compiler: frontends, backends, optimizers, assemblers, linkers, libc++, compiler-rt, and a JIT engine. The word "LLVM" has this meaning, for example, in the following sentence: "LLVM is comprised of several projects".

  • An LLVM-based compiler: This is a compiler built partially or completely with the LLVM infrastructure. For example, a compiler might use LLVM for the frontend and backend but use GCC and GNU system libraries to perform the final link. LLVM has this meaning in the following sentence, for example: "I used LLVM to compile C programs to a MIPS platform".

  • LLVM libraries: This is the reusable code portion of the LLVM infrastructure. For example, LLVM has this meaning in the sentence: "My project uses LLVM to generate code through its Just-in-Time compilation framework".

  • LLVM core: The optimizations that happen at the intermediate language level and the backend algorithms form the LLVM core where the project started. LLVM has this meaning in the following sentence: "LLVM and Clang are two different projects".

  • The LLVM IR: This is the LLVM compiler intermediate representation. LLVM has this meaning when used in sentences such as "I built a frontend that translates my own language to LLVM".

How can I display a list view in an Android Alert Dialog?

Isn't it smoother to make a method to be called after the creation of the EditText unit in an AlertDialog, for general use?

public static void EditTextListPicker(final Activity activity, final EditText EditTextItem, final String SelectTitle, final String[] SelectList) {
    EditTextItem.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle(SelectTitle);
            builder.setItems(SelectList, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int item) {
                    EditTextItem.setText(SelectList[item]);
                }
            });
            builder.create().show();
            return false;
        }
    });
}

Recursive directory listing in DOS

You can use:

dir /s

If you need the list without all the header/footer information try this:

dir /s /b

(For sure this will work for DOS 6 and later; might have worked prior to that, but I can't recall.)

What are the lesser known but useful data structures?

I personally find sparse matrix data structures to be very interesting. http://www.netlib.org/linalg/html_templates/node90.html

The famous BLAS libraries use these. And when you deal with linear systems that contain 100,000's of rows and columns, it becomes critical to use these. Some of these also resemble the compact grid (basically like a bucket-sorted grid) which is common in computer graphics. http://www.cs.kuleuven.be/~ares/publications/LD08CFRGRT/LD08CFRGRT.pdf

Also as far as computer graphics is concerned, MAC grids are somewhat interesting, but only because they're clever. http://www.seas.upenn.edu/~cis665/projects/Liquation_665_Report.pdf

Using Python's list index() method on a list of tuples or objects?

z = list(zip(*tuple_list))
z[1][z[0].index('persimon')]

CSS content property: is it possible to insert HTML instead of Text?

Unfortunately, this is not possible. Per the spec:

Generated content does not alter the document tree. In particular, it is not fed back to the document language processor (e.g., for reparsing).

In other words, for string values this means the value is always treated literally. It is never interpreted as markup, regardless of the document language in use.

As an example, using the given CSS with the following HTML:

<h1 class="header">Title</h1>

... will result in the following output:

<a href="#top">Back</a>Title

CMake complains "The CXX compiler identification is unknown"

I just had this problem setting up my new laptop. The issue for me was that my toolchain (CodeSourcery) is 32bit and I had not installed the 32bit libs.

sudo apt-get install ia32-libs

psql: FATAL: Peer authentication failed for user "dev"

For people in the future seeing this, postgres is in the /usr/lib/postgresql/10/bin on my Ubuntu server.

I added it to the PATH in my .bashrc file, and add this line at the end

PATH=$PATH:/usr/lib/postgresql/10/bin

then on the command line

$> source ./.bashrc

I refreshed my bash environment. Now I can use postgres -D /wherever from any directory

MySQL: How to add one day to datetime field in query

You can use the DATE_ADD() function:

... WHERE DATE(DATE_ADD(eventdate, INTERVAL -1 DAY)) = CURRENT_DATE

It can also be used in the SELECT statement:

SELECT DATE_ADD('2010-05-11', INTERVAL 1 DAY) AS Tomorrow;
+------------+
| Tomorrow   |
+------------+
| 2010-05-12 |
+------------+
1 row in set (0.00 sec)

Pagination response payload from a RESTful API

just add in your backend API new property's into response body. from example .net core:

[Authorize]
[HttpGet]
public async Task<IActionResult> GetUsers([FromQuery]UserParams userParams)
{
  var users = await _repo.GetUsers(userParams);
  var usersToReturn = _mapper.Map<IEnumerable<UserForListDto>>(users);


  // create new object and add into it total count param etc
  var UsersListResult = new
  {
    usersToReturn,
    currentPage = users.CurrentPage,
    pageSize = users.PageSize,
    totalCount = users.TotalCount,
    totalPages = users.TotalPages
  };

  return Ok(UsersListResult);
}

In body response it look like this

{
"usersToReturn": [
    {
        "userId": 1,
        "username": "[email protected]",
        "firstName": "Joann",
        "lastName": "Wilson",
        "city": "Armstrong",
        "phoneNumber": "+1 (893) 515-2172"
    },
    {
        "userId": 2,
        "username": "[email protected]",
        "firstName": "Booth",
        "lastName": "Drake",
        "city": "Franks",
        "phoneNumber": "+1 (800) 493-2168"
    }
],
// metadata to pars in client side
"currentPage": 1,
"pageSize": 2,
"totalCount": 87,
"totalPages": 44

}

How to install plugin for Eclipse from .zip

The accepted answer from Konstantin worked, but there were a few additional steps. After restarting Eclipse, you still have to go into software updates, find your newly available software, check the box(es) for it, and click the "install" button. Then it'll prompt you to restart again and only then will you see your new views or functionality.

Additionally, you can check the "Error Log" view for any problems with your new plugin that eclipse is complaining about.

wait() or sleep() function in jquery?

delay() will not do the job. The problem with delay() is it's part of the animation system, and only applies to animation queues.

What if you want to wait before executing something outside of animation??

Use this:

window.setTimeout(function(){
                 // do whatever you want to do     
                  }, 600);

What happens?: In this scenario it waits 600 miliseconds before executing the code specified within the curly braces.

This helped me a great deal once I figured it out and hope it will help you as well!

IMPORTANT NOTICE: 'window.setTimeout' happens asynchronously. Keep that in mind when writing your code!

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

Here is the easiest way that I have used in my applications. Add given below 3 lines of code in App_Start\\WebApiConfig.cs in Register function

    var formatters = GlobalConfiguration.Configuration.Formatters;

    formatters.Remove(formatters.XmlFormatter);

    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));

Asp.net web API will automatically serialize your returning object to JSON and as the application/json is added in the header so the browser or the receiver will understand that you are returning JSON result.

Eclipse error "Could not find or load main class"

I just encountered the same problem as yours and I followed Kumar's directions and it worked out. One thing to add: you need to make sure that after you go to the correct main class, check the "Classpath" and your project name should be existed under the "User Entries". If not, add your project to the directory then you're good to go.

What is a simple command line program or script to backup SQL server databases?

If you can find the DB files... "cp DBFiles backup/"

Almost for sure not advisable in most cases, but it's simple as all getup.

How do I copy the contents of a String to the clipboard in C#?

You can use System.Windows.Forms.Clipboard.SetText(...).

How can I call a shell command in my Perl script?

There are a lot of ways you can call a shell command from a Perl script, such as:

  1. back tick ls which captures the output and gives back to you.
  2. system system('ls');
  3. open

Refer #17 here: Perl programming tips

How to show git log history (i.e., all the related commits) for a sub directory of a git repo?

The other answers only show the changed files.

git log -p DIR is very useful, if you need the full diff of all changed files in a specific subdirectory.

Example: Show all detailed changes in a specific version range

git log -p 8a5fb..HEAD -- A B

commit 62ad8c5d
Author: Scott Tiger
Date:   Mon Nov 27 14:25:29 2017 +0100

    My comment

...
@@ -216,6 +216,10 @@ public class MyClass {

+  Added
-  Deleted

What is a singleton in C#?

You asked for C#. Trivial example:


public class Singleton
{
    private Singleton()
    {
        // Prevent outside instantiation
    }

    private static readonly Singleton _singleton = new Singleton();

    public static Singleton GetSingleton()
    {
        return _singleton;
    }
}

Redirecting 404 error with .htaccess via 301 for SEO etc

You will need to know something about the URLs, like do they have a specific directory or some query string element because you have to match for something. Otherwise you will have to redirect on the 404. If this is what is required then do something like this in your .htaccess:

ErrorDocument 404 /index.php

An error page redirect must be relative to root so you cannot use www.mydomain.com.

If you have a pattern to match too then use 301 instead of 302 because 301 is permanent and 302 is temporary. A 301 will get the old URLs removed from the search engines and the 302 will not.

Mod Rewrite Reference: http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html

SQL Server - Create a copy of a database table and place it in the same database?

You need to write SSIS to copy the table and its data, constraints and triggers. We have in our organization a software called Kal Admin by kalrom Systems that has a free version for downloading (I think that the copy tables feature is optional)

CSS "and" and "or"

AND (&&):

.registration_form_right input:not([type="radio"]):not([type="checkbox"])

OR (||):

.registration_form_right input:not([type="radio"]), 
   .registration_form_right input:not([type="checkbox"])

What is the difference between using constructor vs getInitialState in React / React Native?

OK, the big difference is start from where they are coming from, so constructor is the constructor of your class in JavaScript, on the other side, getInitialState is part of the lifecycle of React.

constructor is where your class get initialised...

Constructor

The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method.

A constructor can use the super keyword to call the constructor of a parent class.

In the React v16 document, they didn't mentioned any preference, but you need to getInitialState if you using createReactClass()...

Setting the Initial State

In ES6 classes, you can define the initial state by assigning this.state in the constructor:

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: props.initialCount};
  }
  // ...
}

With createReactClass(), you have to provide a separate getInitialState method that returns the initial state:

var Counter = createReactClass({
  getInitialState: function() {
    return {count: this.props.initialCount};
  },
  // ...
});

Visit here for more information.

Also created the image below to show few lifecycles of React Compoenents:

React lifecycle

How to reference a local XML Schema file correctly?

If you work in MS Visual Studio just do following

  1. Put WSDL file and XSD file at the same folder.
  2. Correct WSDL file like this YourSchemeFile.xsd

  3. Use visual Studio using this great example How to generate service reference with only physical wsdl file

Notice that you have to put the path to your WSDL file manually. There is no way to use Open File dialog box out there.

pros and cons between os.path.exists vs os.path.isdir

os.path.isdir() checks if the path exists and is a directory and returns TRUE for the case.

Similarly, os.path.isfile() checks if the path exists and is a file and returns TRUE for the case.

And, os.path.exists() checks if the path exists and doesn’t care if the path points to a file or a directory and returns TRUE in either of the cases.

SQL Query To Obtain Value that Occurs more than once

For MySQL:

SELECT lastname AS ln 
    FROM 
    (SELECT lastname, count(*) as Counter 
     FROM `students` 
     GROUP BY `lastname`) AS tbl WHERE Counter > 2

How to substring in jquery

No jQuery needed! Just use the substring method:

var gorge = name.substring(4);

Or if the text you want to remove isn't static:

var name = 'nameGorge';
var toRemove = 'name';
var gorge = name.replace(toRemove,'');

lvalue required as left operand of assignment error when using C++

It is just a typo(I guess)-

p+=1;

instead of p +1=p; is required .

As name suggest lvalue expression should be left-hand operand of the assignment operator.

Is it valid to define functions in JSON results?

although eval is not recommended, this works:

<!DOCTYPE html>
<html>
<body>

<h2>Convert a string written in JSON format, into a JavaScript function.</h2>

<p id="demo"></p>

<script>
    function test(val){return val + " it's OK;}
    var someVar = "yup";
    var myObj = { "func": "test(someVar);" };
    document.getElementById("demo").innerHTML = eval(myObj.func);
</script>

</body>
</html>

Rename all files in a folder with a prefix in a single command

Also works for items with spaces and ignores directories

for f in *; do [[ -f "$f" ]] && mv "$f" "unix_$f"; done

Clear android application user data

If you want to do manually then You also can clear your user data by clicking “Clear Data” button in Settings–>Applications–>Manage Aplications–> YOUR APPLICATION

or Is there any other way to do that?

Then Download code here

enter image description here

How to get the python.exe location programmatically?

sys.executable is not reliable if working in an embedded python environment. My suggestions is to deduce it from

import os
os.__file__

ActionBar text color

I found a way that works well with any flavor of ActionBar (Sherlock, Compat, and Native):

Just use html to set the title, and specify the text color. For example, to set the ActionBar text color to red, simply do this:

getActionBar()/* or getSupportActionBar() */.setTitle(Html.fromHtml("<font color=\"red\">" + getString(R.string.app_name) + "</font>"));

You can also use the red hex code #FF0000 instead of the word red. If you are having trouble with this, see Android Html.fromHtml(String) doesn't work for <font color='#'>text</font>.


Additionally, if you want to use a color resource, this code can be used to get the correct HEX String, and removing the alpha if needed (the font tag does not support alpha):

int orange = getResources().getColor(R.color.orange);
String htmlColor = String.format(Locale.US, "#%06X", (0xFFFFFF & Color.argb(0, Color.red(orange), Color.green(orange), Color.blue(orange))));

Format decimal for percentage values?

This code may help you:

double d = double.Parse(input_value);
string output= d.ToString("F2", CultureInfo.InvariantCulture) + "%";

How to compare the contents of two string objects in PowerShell

You can do it in two different ways.

Option 1: The -eq operator

>$a = "is"
>$b = "fission"
>$c = "is"
>$a -eq $c
True
>$a -eq $b
False

Option 2: The .Equals() method of the string object. Because strings in PowerShell are .Net System.String objects, any method of that object can be called directly.

>$a.equals($b)
False
>$a.equals($c)
True
>$a|get-member -membertype method

List of System.String methods follows.

How can I check if an argument is defined when starting/calling a batch file?

IF "%~1"=="" GOTO :Usage

~ will de-quote %1 if %1 itself is quoted.

" " will protect from special characters passed. for example calling the script with &ping

How to align matching values in two columns in Excel, and bring along associated values in other columns

assuming the item numbers are unique, a VLOOKUP should get you the information you need.

first value would be =VLOOKUP(E1,A:B,2,FALSE), and the same type of formula to retrieve the second value would be =VLOOKUP(E1,C:D,2,FALSE). Wrap them in an IFERROR if you want to return anything other than #N/A if there is no corresponding value in the item column(s)

Tool to generate JSON schema from JSON data

You might be looking for this:

http://www.jsonschema.net

It is an online tool that can automatically generate JSON schema from JSON string. And you can edit the schema easily.

Why there is this "clear" class before footer?

Most likely, as mentioned by others, it is a class carrying the css values:

.clear{clear: both;} 

in order to prevent any more page elements from extending into the footer element. It is a quick and easy way of making sure that pages with columns of varying heights don't cause the footer to render oddly, by possibly setting its top position at the end of a shorter column.

In many cases it is not necessary, but if you are using best-practice standards it is a good idea to use, if you are floating page elements left and right. It functions with page elements similar to the way a horizontal rule works with text, to ensure proper and complete sepperation.

URL encoding in Android

try {
                    query = URLEncoder.encode(query, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

I know this is not an answer, but I'd like to contribute to this matter for what it's worth. It would be great if they could release justify-self for flexbox to make it truly flexible.

It's my belief that when there are multiple items on the axis, the most logical way for justify-self to behave is to align itself to its nearest neighbours (or edge) as demonstrated below.

I truly hope, W3C takes notice of this and will at least consider it. =)

enter image description here

This way you can have an item that is truly centered regardless of the size of the left and right box. When one of the boxes reaches the point of the center box it will simply push it until there is no more space to distribute.

enter image description here

The ease of making awesome layouts are endless, take a look at this "complex" example.

enter image description here

How to find whether MySQL is installed in Red Hat?

Usually you can find a program under a subdirectory "../bin". System programs are under /usr/bin or /bin. To check where files of mysql package are placed, on RHEL 6 type like this :

rpm -ql mysql (which is the main part of the package)

and the result is a list of "exe" files such as "mysqladmin" tool. About to know the version of the server, run the command:

mysqladmin -u "valid-user" version

C# 4.0 optional out/ref arguments

No, but another great alternative is having the method use a generic template class for optional parameters as follows:

public class OptionalOut<Type>
{
    public Type Result { get; set; }
}

Then you can use it as follows:

public string foo(string value, OptionalOut<int> outResult = null)
{
    // .. do something

    if (outResult != null) {
        outResult.Result = 100;
    }

    return value;
}

public void bar ()
{
    string str = "bar";

    string result;
    OptionalOut<int> optional = new OptionalOut<int> ();

    // example: call without the optional out parameter
    result = foo (str);
    Console.WriteLine ("Output was {0} with no optional value used", result);

    // example: call it with optional parameter
    result = foo (str, optional);
    Console.WriteLine ("Output was {0} with optional value of {1}", result, optional.Result);

    // example: call it with named optional parameter
    foo (str, outResult: optional);
    Console.WriteLine ("Output was {0} with optional value of {1}", result, optional.Result);
}

Masking password input from the console : Java

If you're dealing with a Java character array (such as password characters that you read from the console), you can convert it to a JRuby string with the following Ruby code:

# GIST: "pw_from_console.rb" under "https://gist.github.com/drhuffman12"

jconsole = Java::java.lang.System.console()
password = jconsole.readPassword()
ruby_string = ''
password.to_a.each {|c| ruby_string << c.chr}

# .. do something with 'password' variable ..    
puts "password_chars: #{password_chars.inspect}"
puts "password_string: #{password_string}"

See also "https://stackoverflow.com/a/27628738/4390019" and "https://stackoverflow.com/a/27628756/4390019"

How to generate a HTML page dynamically using PHP?

As per your requirement you dont have to generate a html page dynamicaly. It can be done by .htaccess file .

Still this is sample code to generate HTML Page

<?php

 $filename = 'test.html';
 header("Cache-Control: public");
 header("Content-Description: File Transfer");
 header("Content-Disposition: attachment; filename=$filename");
 header("Content-Type: application/octet-stream; ");
 header("Content-Transfer-Encoding: binary");
?>

you can create any .html , .php file just change extention in file name

ArrayAdapter in android to create simple listview

But again main doubt why TextView resource id it needs?

Look at the constructor and the params.

public ArrayAdapter (Context context, int resource, int textViewResourceId, T[] objects)

Added in API level 1 Constructor

Parameters

context The current context.

resource The resource ID for a layout file containing a layout to use when instantiating views.

textViewResourceId The id of the TextView within the layout resource to be populated objects The objects to represent in the ListView.

android.R.id.text1 refers to the id of text in android resource. So you need not have the one in your activity.

Here's the full list

http://developer.android.com/reference/android/R.id.html

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, android.R.id.text1, values);

this refers to activity context

android.R.layout.simple_list_item_1 simple_list_item_1 is the layout in android.R.layout.

android.R.id.text1 refers to the android resource id.

values is a string array from the link you provided

http://developer.android.com/reference/android/R.layout.html

Bootstrap Columns Not Working

While this does not address the OP's question, I had trouble with my bootstrap rows / columns while trying to use them in conjunction with Kendo ListView (even with the bootstrap-kendo css).

Adding the following css fixed the problem for me:

#myListView.k-widget, #catalog-items.k-widget * {
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

Pandas merge two dataframes with different columns

I think in this case concat is what you want:

In [12]:

pd.concat([df,df1], axis=0, ignore_index=True)
Out[12]:
   attr_1  attr_2  attr_3  id  quantity
0       0       1     NaN   1        20
1       1       1     NaN   2        23
2       1       1     NaN   3        19
3       0       0     NaN   4        19
4       1     NaN       0   5         8
5       0     NaN       1   6        13
6       1     NaN       1   7        20
7       1     NaN       1   8        25

by passing axis=0 here you are stacking the df's on top of each other which I believe is what you want then producing NaN value where they are absent from their respective dfs.

How to get the value from the GET parameters?

Elegant, functional style solution

Let's create an object containing URL param names as keys, then we can easily extract the parameter by its name:

// URL: https://example.com/?test=true&orderId=9381  

// Build an object containing key-value pairs
export const queryStringParams = window.location.search
  .split('?')[1]
  .split('&')
  .map(keyValue => keyValue.split('='))
  .reduce<QueryStringParams>((params, [key, value]) => {
    params[key] = value;
    return params;
  }, {});

type QueryStringParams = {
  [key: string]: string;
};


// Return URL parameter called "orderId"
return queryStringParams.orderId;

Kill process by name?

Assuming you're on a Unix-like platform (so that ps -A exists),

>>> import subprocess, signal
>>> import os
>>> p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
>>> out, err = p.communicate()

gives you ps -A's output in the out variable (a string). You can break it down into lines and loop on them...:

>>> for line in out.splitlines():
...   if 'iChat' in line:
...     pid = int(line.split(None, 1)[0])
...     os.kill(pid, signal.SIGKILL)
... 

(you could avoid importing signal, and use 9 instead of signal.SIGKILL, but I just don't particularly like that style, so I'd rather used the named constant this way).

Of course you could do much more sophisticated processing on these lines, but this mimics what you're doing in shell.

If what you're after is avoiding ps, that's hard to do across different Unix-like systems (ps is their common API to get a process list, in a sense). But if you have a specific Unix-like system in mind, only (not requiring any cross-platform portability), it may be possible; in particular, on Linux, the /proc pseudo-filesystem is very helpful. But you'll need to clarify your exact requirements before we can help on this latter part.

How to get a value inside an ArrayList java

The list may contain several elements, so the get method takes an argument : the index of the element you want to retrieve. If you want the first one, then it's 0.

The list contains Car instances, so you just have to do

Car firstCar = car.get(0);
String price = firstCar.getPrice();

or just

String price = car.get(0).getPrice();

The car variable should be named cars, since it's a list and thus contains several cars.

Read the tutorial about collections. And learn to use the javadoc: all the classes and methods are documented.

How to add local jar files to a Maven project?

Install the JAR into your local Maven repository as follows:

mvn install:install-file \
   -Dfile=<path-to-file> \
   -DgroupId=<group-id> \
   -DartifactId=<artifact-id> \
   -Dversion=<version> \
   -Dpackaging=<packaging> \
   -DgeneratePom=true

Where each refers to:

<path-to-file>: the path to the file to load e.g ? c:\kaptcha-2.3.jar

<group-id>: the group that the file should be registered under e.g ? com.google.code

<artifact-id>: the artifact name for the file e.g ? kaptcha

<version>: the version of the file e.g ? 2.3

<packaging>: the packaging of the file e.g. ? jar

Reference

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

This is not a great answer, but it should lead you to the proper one. I haven't written VBA in a solid minute so I can't recall the exact syntax, but here's some 'psudeo code' for you -- I know you can easily implement this in a VBA macro

for all worksheet.rows
    if cell.value == 0
        then cell.value = " "
    endif
endfor

Basically, have VBA run through each row. If a cell in that row is an integer and equal to zero, simply replace it with a " ". It won't be blank but it'll seem to be. I think there's also a property called cell.value is empty that might clear cell contents. Use the library in VBA, I'm sure there's something in there you can use.

Alternatively, if this is a one time job, you can use a special filter. Just select filter from the ribbon and replace all 0 s by row with a space.

I hope that helps to get you started.

Unit test naming best practices

In VS + NUnit I usually create folders in my project to group functional tests together. Then I create unit test fixture classes and name them after the type of functionality I'm testing. The [Test] methods are named along the lines of Can_add_user_to_domain:

- MyUnitTestProject   
  + FTPServerTests <- Folder
   + UserManagerTests <- Test Fixture Class
     - Can_add_user_to_domain  <- Test methods
     - Can_delete_user_from_domain
     - Can_reset_password

How to move table from one tablespace to another in oracle 11g

Use sql from sql:

spool output of this to a file:

select 'alter index '||owner||'.'||index_name||' rebuild tablespace TO_TABLESPACE_NAME;' from all_indexes where owner='OWNERNAME';

spoolfile will have something like this:

alter index OWNER.PK_INDEX rebuild tablespace CORRECT_TS_NAME;

Delay/Wait in a test case of Xcode UI testing

The following code just works with Objective C.

- (void)wait:(NSUInteger)interval {

    XCTestExpectation *expectation = [self expectationWithDescription:@"wait"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(interval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [expectation fulfill];
    });
    [self waitForExpectationsWithTimeout:interval handler:nil];
}

Just make call to this function as given below.

[self wait: 10];

Add new element to an existing object

You can use Extend to add new objects to an existing one.

Display unescaped HTML in Vue.js

You have to use v-html directive for displaying html content inside a vue component

<div v-html="html content data property"></div>

Moving Panel in Visual Studio Code to right side

I'm using Visual Studio Code v1.24.0 on a Mac.

By default, the Panel will appear on the bottom (You can change the default as well. Please refer to @Forres' answer: Moving Panel in Visual Studio Code to right side)

Here's the bottom/right toggle button for VS Code Panel:

enter image description here

Once I click on this button, the Panel moves to the right.

enter image description here

Moving it back is a little tricky though. As you can see, some of the buttons are hidden. This is because the width of the panel when it's aligned right is too small. We need to expand the column to see all the buttons.

This is how it'll look upon expansion:

enter image description here

Now, if you want to move the Panel back to the bottom, click on the toggle bottom/top button again.

PHP String to Float

You want the non-locale-aware floatval function:

float floatval ( mixed $var ) - Gets the float value of a string.

Example:

$string = '122.34343The';
$float  = floatval($string);
echo $float; // 122.34343

How can I get a list of all values in select box?

Change:

x.length

to:

x.options.length

Link to fiddle

And I agree with Abraham - you might want to use text instead of value

Update
The reason your fiddle didn't work was because you chose the option: "onLoad" instead of: "No wrap - in "

MS-access reports - The search key was not found in any record - on save

These are the steps which i follows may be it is useful for you,

  1. Go to menu-tools-database utilities-compact and repair database.

  2. when repairing database delete or update that record.

  3. it is working finely.

Can't draw Histogram, 'x' must be numeric

Use the dec argument to set "," as the decimal point by adding:

 ce <- read.table("file.txt", header = TRUE, dec = ",")

Attach Authorization header for all axios requests

If you use "axios": "^0.17.1" version you can do like this:

Create instance of axios:

// Default config options
  const defaultOptions = {
    baseURL: <CHANGE-TO-URL>,
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // Create instance
  let instance = axios.create(defaultOptions);

  // Set the AUTH token for any request
  instance.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    config.headers.Authorization =  token ? `Bearer ${token}` : '';
    return config;
  });

Then for any request the token will be select from localStorage and will be added to the request headers.

I'm using the same instance all over the app with this code:

import axios from 'axios';

const fetchClient = () => {
  const defaultOptions = {
    baseURL: process.env.REACT_APP_API_PATH,
    method: 'get',
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // Create instance
  let instance = axios.create(defaultOptions);

  // Set the AUTH token for any request
  instance.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    config.headers.Authorization =  token ? `Bearer ${token}` : '';
    return config;
  });

  return instance;
};

export default fetchClient();

Good luck.

Get column index from column name in python pandas

DSM's solution works, but if you wanted a direct equivalent to which you could do (df.columns == name).nonzero()

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

If you are using .NET 4.0 and later then you can just use dynamic as method argument and check in runtime that the passed dynamic argument type is numeric/integer type.

If the type of the passed dynamic is not numeric/integer type then throw exception.

An example short code that implements the idea is something like:

using System;
public class InvalidArgumentException : Exception
{
    public InvalidArgumentException(string message) : base(message) {}
}
public class InvalidArgumentTypeException : InvalidArgumentException
{
    public InvalidArgumentTypeException(string message) : base(message) {}
}
public class ArgumentTypeNotIntegerException : InvalidArgumentTypeException
{
    public ArgumentTypeNotIntegerException(string message) : base(message) {}
}
public static class Program
{
    private static bool IntegerFunction(dynamic n)
    {
        if (n.GetType() != typeof(Int16) &&
            n.GetType() != typeof(Int32) &&
            n.GetType() != typeof(Int64) &&
            n.GetType() != typeof(UInt16) &&
            n.GetType() != typeof(UInt32) &&
            n.GetType() != typeof(UInt64))
            throw new ArgumentTypeNotIntegerException("argument type is not integer type");
        //code that implements IntegerFunction goes here
    }
    private static void Main()
    {
         Console.WriteLine("{0}",IntegerFunction(0)); //Compiles, no run time error and first line of output buffer is either "True" or "False" depends on the code that implements "Program.IntegerFunction" static method.
         Console.WriteLine("{0}",IntegerFunction("string")); //Also compiles but it is run time error and exception of type "ArgumentTypeNotIntegerException" is thrown here.
         Console.WriteLine("This is the last Console.WriteLine output"); //Never reached and executed due the run time error and the exception thrown on the second line of Program.Main static method.
    }

Of course that this solution works in run time only but never in compile time.

If you want a solution that always works in compile time and never in run time then you will have to wrap the dynamic with a public struct/class whose overloaded public constructors accept arguments of the desired types only and give the struct/class appropriate name.

It makes sense that the wrapped dynamic is always private member of the class/struct and it is the only member of the struct/class and the name of the only member of the struct/class is "value".

You will also have to define and implement public methods and/or operators that work with the desired types for the private dynamic member of the class/struct if necessary.

It also makes sense that the struct/class has special/unique constructor that accepts dynamic as argument that initializes it's only private dynamic member called "value" but the modifier of this constructor is private of course.

Once the class/struct is ready define the argument's type of IntegerFunction to be that class/struct that has been defined.

An example long code that implements the idea is something like:

using System;
public struct Integer
{
    private dynamic value;
    private Integer(dynamic n) { this.value = n; }
    public Integer(Int16 n) { this.value = n; }
    public Integer(Int32 n) { this.value = n; }
    public Integer(Int64 n) { this.value = n; }
    public Integer(UInt16 n) { this.value = n; }
    public Integer(UInt32 n) { this.value = n; }
    public Integer(UInt64 n) { this.value = n; }
    public Integer(Integer n) { this.value = n.value; }
    public static implicit operator Int16(Integer n) { return n.value; }
    public static implicit operator Int32(Integer n) { return n.value; }
    public static implicit operator Int64(Integer n) { return n.value; }
    public static implicit operator UInt16(Integer n) { return n.value; }
    public static implicit operator UInt32(Integer n) { return n.value; }
    public static implicit operator UInt64(Integer n) { return n.value; }
    public static Integer operator +(Integer x, Int16 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, Int32 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, Int64 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, UInt16 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, UInt32 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, UInt64 y) { return new Integer(x.value + y); }
    public static Integer operator -(Integer x, Int16 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, Int32 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, Int64 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, UInt16 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, UInt32 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, UInt64 y) { return new Integer(x.value - y); }
    public static Integer operator *(Integer x, Int16 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, Int32 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, Int64 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, UInt16 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, UInt32 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, UInt64 y) { return new Integer(x.value * y); }
    public static Integer operator /(Integer x, Int16 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, Int32 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, Int64 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, UInt16 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, UInt32 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, UInt64 y) { return new Integer(x.value / y); }
    public static Integer operator %(Integer x, Int16 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, Int32 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, Int64 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, UInt16 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, UInt32 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, UInt64 y) { return new Integer(x.value % y); }
    public static Integer operator +(Integer x, Integer y) { return new Integer(x.value + y.value); }
    public static Integer operator -(Integer x, Integer y) { return new Integer(x.value - y.value); }
    public static Integer operator *(Integer x, Integer y) { return new Integer(x.value * y.value); }
    public static Integer operator /(Integer x, Integer y) { return new Integer(x.value / y.value); }
    public static Integer operator %(Integer x, Integer y) { return new Integer(x.value % y.value); }
    public static bool operator ==(Integer x, Int16 y) { return x.value == y; }
    public static bool operator !=(Integer x, Int16 y) { return x.value != y; }
    public static bool operator ==(Integer x, Int32 y) { return x.value == y; }
    public static bool operator !=(Integer x, Int32 y) { return x.value != y; }
    public static bool operator ==(Integer x, Int64 y) { return x.value == y; }
    public static bool operator !=(Integer x, Int64 y) { return x.value != y; }
    public static bool operator ==(Integer x, UInt16 y) { return x.value == y; }
    public static bool operator !=(Integer x, UInt16 y) { return x.value != y; }
    public static bool operator ==(Integer x, UInt32 y) { return x.value == y; }
    public static bool operator !=(Integer x, UInt32 y) { return x.value != y; }
    public static bool operator ==(Integer x, UInt64 y) { return x.value == y; }
    public static bool operator !=(Integer x, UInt64 y) { return x.value != y; }
    public static bool operator ==(Integer x, Integer y) { return x.value == y.value; }
    public static bool operator !=(Integer x, Integer y) { return x.value != y.value; }
    public override bool Equals(object obj) { return this == (Integer)obj; }
    public override int GetHashCode() { return this.value.GetHashCode(); }
    public override string ToString() { return this.value.ToString(); }
    public static bool operator >(Integer x, Int16 y) { return x.value > y; }
    public static bool operator <(Integer x, Int16 y) { return x.value < y; }
    public static bool operator >(Integer x, Int32 y) { return x.value > y; }
    public static bool operator <(Integer x, Int32 y) { return x.value < y; }
    public static bool operator >(Integer x, Int64 y) { return x.value > y; }
    public static bool operator <(Integer x, Int64 y) { return x.value < y; }
    public static bool operator >(Integer x, UInt16 y) { return x.value > y; }
    public static bool operator <(Integer x, UInt16 y) { return x.value < y; }
    public static bool operator >(Integer x, UInt32 y) { return x.value > y; }
    public static bool operator <(Integer x, UInt32 y) { return x.value < y; }
    public static bool operator >(Integer x, UInt64 y) { return x.value > y; }
    public static bool operator <(Integer x, UInt64 y) { return x.value < y; }
    public static bool operator >(Integer x, Integer y) { return x.value > y.value; }
    public static bool operator <(Integer x, Integer y) { return x.value < y.value; }
    public static bool operator >=(Integer x, Int16 y) { return x.value >= y; }
    public static bool operator <=(Integer x, Int16 y) { return x.value <= y; }
    public static bool operator >=(Integer x, Int32 y) { return x.value >= y; }
    public static bool operator <=(Integer x, Int32 y) { return x.value <= y; }
    public static bool operator >=(Integer x, Int64 y) { return x.value >= y; }
    public static bool operator <=(Integer x, Int64 y) { return x.value <= y; }
    public static bool operator >=(Integer x, UInt16 y) { return x.value >= y; }
    public static bool operator <=(Integer x, UInt16 y) { return x.value <= y; }
    public static bool operator >=(Integer x, UInt32 y) { return x.value >= y; }
    public static bool operator <=(Integer x, UInt32 y) { return x.value <= y; }
    public static bool operator >=(Integer x, UInt64 y) { return x.value >= y; }
    public static bool operator <=(Integer x, UInt64 y) { return x.value <= y; }
    public static bool operator >=(Integer x, Integer y) { return x.value >= y.value; }
    public static bool operator <=(Integer x, Integer y) { return x.value <= y.value; }
    public static Integer operator +(Int16 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(Int32 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(Int64 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(UInt16 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(UInt32 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(UInt64 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator -(Int16 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(Int32 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(Int64 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(UInt16 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(UInt32 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(UInt64 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator *(Int16 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(Int32 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(Int64 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(UInt16 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(UInt32 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(UInt64 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator /(Int16 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(Int32 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(Int64 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(UInt16 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(UInt32 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(UInt64 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator %(Int16 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(Int32 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(Int64 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(UInt16 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(UInt32 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(UInt64 x, Integer y) { return new Integer(x % y.value); }
    public static bool operator ==(Int16 x, Integer y) { return x == y.value; }
    public static bool operator !=(Int16 x, Integer y) { return x != y.value; }
    public static bool operator ==(Int32 x, Integer y) { return x == y.value; }
    public static bool operator !=(Int32 x, Integer y) { return x != y.value; }
    public static bool operator ==(Int64 x, Integer y) { return x == y.value; }
    public static bool operator !=(Int64 x, Integer y) { return x != y.value; }
    public static bool operator ==(UInt16 x, Integer y) { return x == y.value; }
    public static bool operator !=(UInt16 x, Integer y) { return x != y.value; }
    public static bool operator ==(UInt32 x, Integer y) { return x == y.value; }
    public static bool operator !=(UInt32 x, Integer y) { return x != y.value; }
    public static bool operator ==(UInt64 x, Integer y) { return x == y.value; }
    public static bool operator !=(UInt64 x, Integer y) { return x != y.value; }
    public static bool operator >(Int16 x, Integer y) { return x > y.value; }
    public static bool operator <(Int16 x, Integer y) { return x < y.value; }
    public static bool operator >(Int32 x, Integer y) { return x > y.value; }
    public static bool operator <(Int32 x, Integer y) { return x < y.value; }
    public static bool operator >(Int64 x, Integer y) { return x > y.value; }
    public static bool operator <(Int64 x, Integer y) { return x < y.value; }
    public static bool operator >(UInt16 x, Integer y) { return x > y.value; }
    public static bool operator <(UInt16 x, Integer y) { return x < y.value; }
    public static bool operator >(UInt32 x, Integer y) { return x > y.value; }
    public static bool operator <(UInt32 x, Integer y) { return x < y.value; }
    public static bool operator >(UInt64 x, Integer y) { return x > y.value; }
    public static bool operator <(UInt64 x, Integer y) { return x < y.value; }
    public static bool operator >=(Int16 x, Integer y) { return x >= y.value; }
    public static bool operator <=(Int16 x, Integer y) { return x <= y.value; }
    public static bool operator >=(Int32 x, Integer y) { return x >= y.value; }
    public static bool operator <=(Int32 x, Integer y) { return x <= y.value; }
    public static bool operator >=(Int64 x, Integer y) { return x >= y.value; }
    public static bool operator <=(Int64 x, Integer y) { return x <= y.value; }
    public static bool operator >=(UInt16 x, Integer y) { return x >= y.value; }
    public static bool operator <=(UInt16 x, Integer y) { return x <= y.value; }
    public static bool operator >=(UInt32 x, Integer y) { return x >= y.value; }
    public static bool operator <=(UInt32 x, Integer y) { return x <= y.value; }
    public static bool operator >=(UInt64 x, Integer y) { return x >= y.value; }
    public static bool operator <=(UInt64 x, Integer y) { return x <= y.value; }
}
public static class Program
{
    private static bool IntegerFunction(Integer n)
    {
        //code that implements IntegerFunction goes here
        //note that there is NO code that checks the type of n in rum time, because it is NOT needed anymore 
    }
    private static void Main()
    {
        Console.WriteLine("{0}",IntegerFunction(0)); //compile error: there is no overloaded METHOD for objects of type "int" and no implicit conversion from any object, including "int", to "Integer" is known.
        Console.WriteLine("{0}",IntegerFunction(new Integer(0))); //both compiles and no run time error
        Console.WriteLine("{0}",IntegerFunction("string")); //compile error: there is no overloaded METHOD for objects of type "string" and no implicit conversion from any object, including "string", to "Integer" is known.
        Console.WriteLine("{0}",IntegerFunction(new Integer("string"))); //compile error: there is no overloaded CONSTRUCTOR for objects of type "string"
    }
}

Note that in order to use dynamic in your code you must Add Reference to Microsoft.CSharp

If the version of the .NET framework is below/under/lesser than 4.0 and dynamic is undefined in that version then you will have to use object instead and do casting to the integer type, which is trouble, so I recommend that you use at least .NET 4.0 or newer if you can so you can use dynamic instead of object.

What is the difference between public, private, and protected?

For me, this is the most useful way to understand the three property types:

Public: Use this when you are OK with this variable being directly accessed and changed from anywhere in your code.

Example usage from outside of the class:

$myObject = new MyObject()
$myObject->publicVar = 'newvalue';
$pubVar = $myObject->publicVar;

Protected: Use this when you want to force other programmers (and yourself) to use getters/setters outside of the class when accessing and setting variables (but you should be consistent and use the getters and setters inside the class as well). This or private tend to be the default way you should set up all class properties.

Why? Because if you decide at some point in the future (maybe even in like 5 minutes) that you want to manipulate the value that is returned for that property or do something with it before getting/setting, you can do that without refactoring everywhere you have used it in your project.

Example usage from outside of the class:

$myObject = new MyObject()
$myObject->setProtectedVar('newvalue');
$protectedVar = $myObject->getProtectedVar();

Private: private properties are very similar to protected properties. But the distinguishing feature/difference is that making it private also makes it inaccessible to child classes without using the parent class's getter or setter.

So basically, if you are using getters and setters for a property (or if it is used only internally by the parent class and it isn't meant to be accessible anywhere else) you might as well make it private, just to prevent anyone from trying to use it directly and introducing bugs.

Example usage inside a child class (that extends MyObject):

$this->setPrivateVar('newvalue');
$privateVar = $this->getPrivateVar();

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

It might be worth verifying that the gmail account hasn't been locked out due to several unsuccessful login attempts, you may need to reset your password. I had the same problem as you, and this turned out to be the solution.

Disabling and enabling a html input button

You can do this fairly easily with just straight JavaScript, no libraries required.

Enable a button

document.getElementById("Button").disabled=false;

Disable a button

 document.getElementById("Button").disabled=true;

No external libraries necessary.

Using VBA code, how to export Excel worksheets as image in Excel 2003?

Based on the link provided by Philip I got this to working

Worksheets("Final Analysis Sheet").Range("A4:G112").CopyPicture xlScreen, xlBitmap

    Application.DisplayAlerts = False
    Set oCht = Charts.Add
    With oCht
        .Paste
        .Export Filename:="C:\FTPDailycheck\TodaysImages\SavedRange.jpg", Filtername:="JPG"
        .Delete
    End With

How to check if a service is running on Android?

onDestroy isn't always called in the service so this is useless!

For example: Just run the app again with one change from Eclipse. The application is forcefully exited using SIG: 9.

css ellipsis on second line

If anyone is trying to get line-clamp to work in flexbox, it's slightly trickier - especially once you are torture testing with really long words. The only real differences in this code snippet are min-width: 0; in the flex item containing truncated text, and word-wrap: break-word;. A hat-tip to https://css-tricks.com/flexbox-truncated-text/ for the insight. Disclaimer: this is still webkit only as far as I know.

_x000D_
_x000D_
.flex-parent {
  display: flex;
}

.short-and-fixed {
  width: 30px;
  height: 30px;
  background: lightgreen;
}

.long-and-truncated {
  margin: 0 20px;
  flex: 1;
  min-width: 0;/* Important for long words! */
}

.long-and-truncated span {
  display: inline;
  -webkit-line-clamp: 3;
  text-overflow: ellipsis;
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  word-wrap: break-word;/* Important for long words! */
}
_x000D_
<div class="flex-parent">
  <div class="flex-child short-and-fixed">
  </div>
  <div class="flex-child long-and-truncated">
    <span>asdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasd</span>
  </div>
  <div class="flex-child short-and-fixed">
  </div>
</div>
_x000D_
_x000D_
_x000D_

http://codepen.io/AlgeoMA/pen/JNvJdx (codepen version)

How to display image with JavaScript?

You could make use of the Javascript DOM API. In particular, look at the createElement() method.

You could create a re-usable function that will create an image like so...

function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);
}

Then you could use it like this...

<button onclick=
    "show_image('http://google.com/images/logo.gif', 
                 276, 
                 110, 
                 'Google Logo');">Add Google Logo</button> 

See a working example on jsFiddle: http://jsfiddle.net/Bc6Et/

New Line Issue when copying data from SQL Server 2012 to Excel

In order to be able to copy and paste results from SQL Server Management Studio 2012 to Excel or to export to Csv with list separators you must first change the query option.

  1. Click on Query then options.

  2. Under Results click on the Grid.

  3. Check the box next to:

    Quote strings containing list separators when saving .csv results.

This should solve the problem.

How to link an image and target a new window

Assuming you want to show an Image thumbnail which is 50x50 pixels and link to the the actual image you can do

<a href="path/to/image.jpg" alt="Image description" target="_blank" style="display: inline-block; width: 50px; height; 50px; background-image: url('path/to/image.jpg');"></a>

Of course it's best to give that link a class or id and put it in your css

How to set a JavaScript breakpoint from code in Chrome?

There are many ways to debug JavaScript code. Following two approaches are widely used to debug JavaScript via code

  1. Using console.log() to print out the values in the browser console. (This will help you understand the values at certain points of your code)

  2. Debugger keyword. Add debugger; to the locations you want to debug, and open the browser's developer console and navigate to the sources tab.

For more tools and ways in which you debug JavaScript Code, are given in this link by W3School.

Why use Gradle instead of Ant or Maven?

This isn't my answer, but it definitely resonates with me. It's from ThoughtWorks' Technology Radar from October 2012:

Two things have caused fatigue with XML-based build tools like Ant and Maven: too many angry pointy braces and the coarseness of plug-in architectures. While syntax issues can be dealt with through generation, plug-in architectures severely limit the ability for build tools to grow gracefully as projects become more complex. We have come to feel that plug-ins are the wrong level of abstraction, and prefer language-based tools like Gradle and Rake instead, because they offer finer-grained abstractions and more flexibility long term.

Create dynamic URLs in Flask with url_for()

url_for in Flask is used for creating a URL to prevent the overhead of having to change URLs throughout an application (including in templates). Without url_for, if there is a change in the root URL of your app then you have to change it in every page where the link is present.

Syntax: url_for('name of the function of the route','parameters (if required)')

It can be used as:

@app.route('/index')
@app.route('/')
def index():
    return 'you are in the index page'

Now if you have a link the index page:you can use this:

<a href={{ url_for('index') }}>Index</a>

You can do a lot o stuff with it, for example:

@app.route('/questions/<int:question_id>'):    #int has been used as a filter that only integer will be passed in the url otherwise it will give a 404 error
def find_question(question_id):  
    return ('you asked for question{0}'.format(question_id))

For the above we can use:

<a href = {{ url_for('find_question' ,question_id=1) }}>Question 1</a>

Like this you can simply pass the parameters!

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

Try adding this in build.gradle (gradle version 4.10.x) file and check it out com.xxx.MainClass this is the class where your main method resides:

plugins {
  id "ua.eshepelyuk.ManifestClasspath" version "1.0.0"
}
apply plugin: 'application'
application {
    mainClassName = "com.xxx.MainClass"
}

The above change must resolve the issue, there is another way using script run.sh below could fix this issue, but it will be more of command-line fix, not in IntelliJ to launch gradle bootRun.

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

It's never wise to rely on defaults being set to a particular value, IMHO, whether it's for date formats, currency formats, optimiser modes or whatever. You should always set the value of date format that you need, in the server, the client, or the application.

In particular, never rely on defaults when converting date or numeric data types for display purposes, because a single change to the database can break your application. Always use an explicit conversion format. For years I worked on Oracle systems where the out of the box default date display format was MM/DD/RR, which drove me nuts but at least forced me to always use an explicit conversion.

Reload an iframe with jQuery

you can do it like this

$('.refrech-iframe').click(function(){
        $(".myiframe").attr("src", function(index, attr){ 
            return attr;
        });
    });

Fatal error: Call to undefined function mb_strlen()

PHP 7.2 Ubuntu 18.04

sudo apt install php-mbstring

How can I flush GPU memory using CUDA (physical reset is unavailable)

First type

nvidia-smi

then select the PID that you want to kill

sudo kill -9 PID

Pandas DataFrame column to list

You can use pandas.Series.tolist

e.g.:

import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})

Run:

>>> df['a'].tolist()

You will get

>>> [1, 2, 3]

Playing mp3 song on python

You are trying to play a .mp3 as if it were a .wav.

You could try using pydub to convert it to .wav format, and then feed that into pyAudio.

Example:

from pydub import AudioSegment

song = AudioSegment.from_mp3("original.mp3")
song.export("final.wav", format="wav")

Alternatively, use pygame, as mentioned in the other answer.

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

In my case, the service failed to start because I didn't set Platform='x64' in the wix file.

I saw these errors in Event Viewer:

Service cannot be started.

System.BadImageFormatException: Could not load file or assembly 'SOME_LIBRARY_FILE, Version=5.0.0.0, Culture=neutral, PublicKeyToken=33345856ad364e35' or one of its dependencies.

I tried checking the bitness of all service related files using CorFlags.exe. When I changed my installer to be 64 bit, everything started working fine.

How many socket connections can a web server handle?

Note that HTTP doesn't typically keep TCP connections open for any longer than it takes to transmit the page to the client; and it usually takes much more time for the user to read a web page than it takes to download the page... while the user is viewing the page, he adds no load to the server at all.

So the number of people that can be simultaneously viewing your web site is much larger than the number of TCP connections that it can simultaneously serve.

Check if number is prime number

You can also try this:

bool isPrime(int number)
    {
        return (Enumerable.Range(1, number).Count(x => number % x == 0) == 2);
    }

"No rule to make target 'install'"... But Makefile exists

I was receiving the same error message, and my issue was that I was not in the correct directory when running the command make install. When I changed to the directory that had my makefile it worked.

So possibly you aren't in the right directory.

What is the use of the @ symbol in PHP?

It suppresses error messages — see Error Control Operators in the PHP manual.

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

Here is how I solved my problem:

instead of

compile project(':library_name')
compile project(':library_name')

in app gradle I have used

implementation project(':library_name')
implementation project(':library_name')

And in my build types for example

demoTest {
 .........
}

I added this line

demoTest {
   matchingFallbacks = ['debug', 'release']
}

Why use argparse rather than optparse?

As of python 2.7, optparse is deprecated, and will hopefully go away in the future.

argparse is better for all the reasons listed on its original page (https://code.google.com/archive/p/argparse/):

  • handling positional arguments
  • supporting sub-commands
  • allowing alternative option prefixes like + and /
  • handling zero-or-more and one-or-more style arguments
  • producing more informative usage messages
  • providing a much simpler interface for custom types and actions

More information is also in PEP 389, which is the vehicle by which argparse made it into the standard library.

How to join three table by laravel eloquent model

$articles =DB::table('articles')
                ->join('categories','articles.id', '=', 'categories.id')
                ->join('user', 'articles.user_id', '=', 'user.id')
                ->select('articles.id','articles.title','articles.body','user.user_name', 'categories.category_name')
                ->get();
return view('myarticlesview',['articles'=>$articles]);

Git: Permission denied (publickey) fatal - Could not read from remote repository. while cloning Git repository

fix for hub cli tool:

  • git config --global hub.protocol https for long term
  • git remote add OOPS https://github.com/isomorphisms/go.git && git push OOPS for immediate fix

This error occurs with the hub command line tool because of their wrong default hub.protocol git-config value. They set repos to

git://github.com/schacon/ticgit.git

instead of what github actually accepts, namely https://github.com/schacon/ticgit.git.


Reading LESS=+/"HTTPS instead" man hub will explain where the above "long-term fix" command comes from.

Exporting the values in List to excel

Exporting values List to Excel

  1. Install in nuget next reference
  2. Install-Package Syncfusion.XlsIO.Net.Core -Version 17.2.0.35
  3. Install-Package ClosedXML -Version 0.94.2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClosedXML;
using ClosedXML.Excel;
using Syncfusion.XlsIO;

namespace ExporteExcel
{
    class Program
    {
        public class Auto
        {
            public string Marca { get; set; }

            public string Modelo { get; set; }
            public int Ano { get; set; }

            public string Color { get; set; }
            public int Peronsas { get; set; }
            public int Cilindros { get; set; }
        }
        static void Main(string[] args)
        {
            //Lista Estatica
            List<Auto> Auto = new List<Program.Auto>()
            {
                new Auto{Marca = "Chevrolet", Modelo = "Sport", Ano = 2019, Color= "Azul", Cilindros=6, Peronsas= 4 },
                new Auto{Marca = "Chevrolet", Modelo = "Sport", Ano = 2018, Color= "Azul", Cilindros=6, Peronsas= 4 },
                new Auto{Marca = "Chevrolet", Modelo = "Sport", Ano = 2017, Color= "Azul", Cilindros=6, Peronsas= 4 }
            };
            //Inizializar Librerias
            var workbook = new XLWorkbook();
            workbook.AddWorksheet("sheetName");
            var ws = workbook.Worksheet("sheetName");
            //Recorrer el objecto
            int row = 1;
            foreach (var c in Auto)
            {
                //Escribrie en Excel en cada celda
                ws.Cell("A" + row.ToString()).Value = c.Marca;
                ws.Cell("B" + row.ToString()).Value = c.Modelo;
                ws.Cell("C" + row.ToString()).Value = c.Ano;
                ws.Cell("D" + row.ToString()).Value = c.Color;
                ws.Cell("E" + row.ToString()).Value = c.Cilindros;
                ws.Cell("F" + row.ToString()).Value = c.Peronsas;
                row++;

            }
            //Guardar Excel 
            //Ruta = Nombre_Proyecto\bin\Debug
            workbook.SaveAs("Coches.xlsx");
        }
    }
}

Cannot get a text value from a numeric cell “Poi”

If you are processing in rows with cellIterator....then this worked for me ....

  DataFormatter formatter = new DataFormatter();   
  while(cellIterator.hasNext())
  {                         
        cell = cellIterator.next();
        String val = "";            
        switch(cell.getCellType()) 
        {
            case Cell.CELL_TYPE_NUMERIC:
                val = String.valueOf(formatter.formatCellValue(cell));
                break;
            case Cell.CELL_TYPE_STRING:
                val = formatter.formatCellValue(cell);
                break;
        }
    .....
    .....
  }

Matplotlib scatter plot with different text at each data point

I would love to add that you can even use arrows /text boxes to annotate the labels. Here is what I mean:

import random
import matplotlib.pyplot as plt


y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]

fig, ax = plt.subplots()
ax.scatter(z, y)

ax.annotate(n[0], (z[0], y[0]), xytext=(z[0]+0.05, y[0]+0.3), 
    arrowprops=dict(facecolor='red', shrink=0.05))

ax.annotate(n[1], (z[1], y[1]), xytext=(z[1]-0.05, y[1]-0.3), 
    arrowprops = dict(  arrowstyle="->",
                        connectionstyle="angle3,angleA=0,angleB=-90"))

ax.annotate(n[2], (z[2], y[2]), xytext=(z[2]-0.05, y[2]-0.3), 
    arrowprops = dict(arrowstyle="wedge,tail_width=0.5", alpha=0.1))

ax.annotate(n[3], (z[3], y[3]), xytext=(z[3]+0.05, y[3]-0.2), 
    arrowprops = dict(arrowstyle="fancy"))

ax.annotate(n[4], (z[4], y[4]), xytext=(z[4]-0.1, y[4]-0.2),
    bbox=dict(boxstyle="round", alpha=0.1), 
    arrowprops = dict(arrowstyle="simple"))

plt.show()

Which will generate the following graph: enter image description here

How to use range-based for() loop with std::map?

In C++17 this is called structured bindings, which allows for the following:

std::map< foo, bar > testing = { /*...blah...*/ };
for ( const auto& [ k, v ] : testing )
{
  std::cout << k << "=" << v << "\n";
}

printf format specifiers for uint32_t and size_t

If you don't want to use the PRI* macros, another approach for printing ANY integer type is to cast to intmax_t or uintmax_t and use "%jd" or %ju, respectively. This is especially useful for POSIX (or other OS) types that don't have PRI* macros defined, for instance off_t.

Print string and variable contents on the same line in R

The {glue} package offers string interpolation. In the example, {wd} is substituted with the contents of the variable. Complex expressions are also supported.

library(glue)

wd <- getwd()
glue("Current working dir: {wd}")
#> Current working dir: /tmp/RtmpteMv88/reprex46156826ee8c

Created on 2019-05-13 by the reprex package (v0.2.1)

Note how the printed output doesn't contain the [1] artifacts and the " quotes, for which other answers use cat().

Read and write a String from text file

Latest swift3 code
You can read data from text file just use bellow code This my text file

     {
"NumberOfSlices": "8",
"NrScenes": "5",
"Scenes": [{
           "dataType": "label1",
           "image":"http://is3.mzstatic.com/image/thumb/Purple19/v4/6e/81/31/6e8131cf-2092-3cd3-534c-28e129897ca9/mzl.syvaewyp.png/53x53bb-85.png",

           "value": "Hello",
           "color": "(UIColor.red)"
           }, {
           "dataType": "label2",
           "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png",
           "value": "Hi There",
           "color": "(UIColor.blue)"
           }, {
           "dataType": "label3",
           "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png",

           "value": "hi how r u ",
           "color": "(UIColor.green)"
           }, {
           "dataType": "label4",
           "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png",
           "value": "what are u doing  ",
           "color": "(UIColor.purple)"
           }, {
           "dataType": "label5",
          "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png",
           "value": "how many times ",
           "color": "(UIColor.white)"
           }, {
           "dataType": "label6",
           "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/5a/f3/06/5af306b0-7cac-1808-f440-bab7a0d18ec0/mzl.towjvmpm.png/53x53bb-85.png",
           "value": "hi how r u ",
           "color": "(UIColor.blue)"
           }, {
           "dataType": "label7",
           "image":"http://is5.mzstatic.com/image/thumb/Purple71/v4/a8/dc/eb/a8dceb29-6daf-ca0f-d037-df9f34cdc476/mzl.ukhhsxik.png/53x53bb-85.png",
           "value": "hi how r u ",
           "color": "(UIColor.gry)"
           }, {
           "dataType": "label8",
           "image":"http://is2.mzstatic.com/image/thumb/Purple71/v4/15/23/e0/1523e03c-fff2-291e-80a7-73f35d45c7e5/mzl.zejcvahm.png/53x53bb-85.png",
           "value": "hi how r u ",
           "color": "(UIColor.brown)"
           }]

}

You can use this code you get data from text json file in swift3

     let filePath = Bundle.main.path(forResource: "nameoftheyourjsonTextfile", ofType: "json")


    let contentData = FileManager.default.contents(atPath: filePath!)
    let content = NSString(data: contentData!, encoding: String.Encoding.utf8.rawValue) as? String

    print(content)
    let json = try! JSONSerialization.jsonObject(with: contentData!) as! NSDictionary
    print(json)
    let app = json.object(forKey: "Scenes") as! NSArray!
    let _ : NSDictionary
    for dict in app! {
        let colorNam = (dict as AnyObject).object(forKey: "color") as! String
        print("colors are \(colorNam)")

       // let colour = UIColor(hexString: colorNam) {
       // colorsArray.append(colour.cgColor)
       // colorsArray.append(colorNam  as! UIColor)

        let value = (dict as AnyObject).object(forKey: "value") as! String
        print("the values are \(value)")
        valuesArray.append(value)

        let images = (dict as AnyObject).object(forKey: "image") as! String
        let url = URL(string: images as String)
        let data = try? Data(contentsOf: url!)
        print(data)
        let image1 = UIImage(data: data!)! as UIImage
        imagesArray.append(image1)
         print(image1)
            }

Display Back Arrow on Toolbar

maybe it will help someone,I didn't find in the answares the thing I did by the end: with ActionBarDrawerToggle mDrawerToggle; to show the back arrow in toolbar set: mDrawerToggle.setDrawerIndicatorEnabled(false);

and if you want it to show the hamburger in the toolbar:

mDrawerToggle.setDrawerIndicatorEnabled(true);

Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

If you are trying to create mapping in your edmx file to a "function Imports", this can result this error. Just clear the fields for insert, update and delete that is located in Mapping Details for a given entity in your edmx, and it should work. I hope I made it clear.

Replace negative values in an numpy array

You are halfway there. Try:

In [4]: a[a < 0] = 0

In [5]: a
Out[5]: array([1, 2, 3, 0, 5])

Is it possible to change a UIButtons background color?

add a second target for the UIButton for UIControlEventTouched and change the UIButton background color. Then change it back in the UIControlEventTouchUpInside target;

Convert HTML to NSAttributedString in iOS

This is a String extension written in Swift to return a HTML string as NSAttributedString.

extension String {
    func htmlAttributedString() -> NSAttributedString? {
        guard let data = self.dataUsingEncoding(NSUTF16StringEncoding, allowLossyConversion: false) else { return nil }
        guard let html = try? NSMutableAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) else { return nil }
        return html
    }
}

To use,

label.attributedText = "<b>Hello</b> \u{2022} babe".htmlAttributedString()

In the above, I have purposely added a unicode \u2022 to show that it renders unicode correctly.

A trivial: The default encoding that NSAttributedString uses is NSUTF16StringEncoding (not UTF8!).

Query to get only numbers from a string

Just a little modification to @Epsicron 's answer

SELECT SUBSTRING(string, PATINDEX('%[0-9]%', string), PATINDEX('%[0-9][^0-9]%', string + 't') - PATINDEX('%[0-9]%', 
                    string) + 1) AS Number
FROM (values ('003Preliminary Examination Plan'),
    ('Coordination005'),
    ('Balance1000sheet')) as a(string)

no need for a temporary variable

Want to download a Git repository, what do I need (windows machine)?

To change working directory in GitMSYS's Git Bash you can just use cd

cd /path/do/directory

Note that:

  • Directory separators use the forward-slash (/) instead of backslash.
  • Drives are specified with a lower case letter and no colon, e.g. "C:\stuff" should be represented with "/c/stuff".
  • Spaces can be escaped with a backslash (\)
  • Command line completion is your friend. Press TAB at anytime to expand stuff, including Git options, branches, tags, and directories.

Also, you can right click in Windows Explorer on a directory and "Git Bash here".

How to Navigate from one View Controller to another using Swift

Swift 3

let secondviewController:UIViewController =  self.storyboard?.instantiateViewController(withIdentifier: "StoryboardIdOfsecondviewController") as? SecondViewController

self.navigationController?.pushViewController(secondviewController, animated: true)

How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

In my case, i had copied a plugins folder into workspace from a collegue. Becaouse it was an unzipped folder, the structure was like 'pluginsfolder inside a plugins folder2 . so make sure that all the plugins are directly located under the toppest plugins folder at the workspace.

PHP - concatenate or directly insert variables in string

Between those two syntaxes, you should really choose the one you prefer :-)

Personally, I would go with your second solution in such a case (Variable interpolation), which I find easier to both write and read.

The result will be the same; and even if there are performance implications, those won't matter 1.


As a sidenote, so my answer is a bit more complete: the day you'll want to do something like this:

echo "Welcome $names!";

PHP will interpret your code as if you were trying to use the $names variable -- which doesn't exist. - note that it will only work if you use "" not '' for your string.

That day, you'll need to use {}:

echo "Welcome {$name}s!"

No need to fallback to concatenations.


Also note that your first syntax:

echo "Welcome ".$name."!";

Could probably be optimized, avoiding concatenations, using:

echo "Welcome ", $name, "!";

(But, as I said earlier, this doesn't matter much...)


1 - Unless you are doing hundreds of thousands of concatenations vs interpolations -- and it's probably not quite the case.

Javascript: The prettiest way to compare one value against multiple values

I like the pretty form of testing indexOf with an array, but be aware, this doesn't work in all browsers (because Array.prototype.indexOf is not present in old IExplorers).

However, there is a similar way by using jQuery with the $.inArray() function :

if ($.inArray(field, ['value1', 'value2', 'value3']) > -1) {
    alert('value ' + field + ' is into the list'); 
}

It could be better, so you should not test if indexOf exists.

Be careful with the comparison (don't use == true/false), because $.inArray returns the index of matching position where the value has been found, and if the index is 0, it would be false when it really exist into the array.

How to fix "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" error?

Try this:

 Select 
    Id, 
    Salt, 
    Password, 
    BannedEndDate, 
    (Select Count(*) 
        From LoginFails 
        Where username = '" + LoginModel.Username + "' And IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "')
 From Users 
 Where username = '" + LoginModel.Username + "'

And I recommend you strongly to use parameters in your query to avoid security risks with sql injection attacks!

Hope that helps!

Is it good practice to use the xor operator for boolean checks?

!= is OK to compare two variables. It doesn't work, though, with multiple comparisons.

How to check if user input is not an int value

Try this one:

    for (;;) {
        if (!sc.hasNextInt()) {
            System.out.println(" enter only integers!: ");
            sc.next(); // discard
            continue;
        }
        choose = sc.nextInt();
        if (choose >= 0) {
            System.out.print("no problem with input");

        } else {
            System.out.print("invalid inputs");

        }
    break;
  }

Adding integers to an int array

org.apache.commons.lang.ArrayUtils can do this

num = (int []) ArrayUtils.add(num, 12);     // builds new array with 12 appended

sass :first-child not working

I think that it is better (for my expirience) to use: :first-of-type, :nth-of-type(), :last-of-type. It can be done whit a little changing of rules, but I was able to do much more than whit *-of-type, than *-child selectors.

insert/delete/update trigger in SQL server

Not possible, per MSDN:

You can have the same code execute for multiple trigger types, but the syntax does not allow for multiple code blocks in one trigger:

Trigger on an INSERT, UPDATE, or DELETE statement to a table or view (DML Trigger)

CREATE TRIGGER [ schema_name . ]trigger_name 
ON { table | view } 
[ WITH <dml_trigger_option> [ ,...n ] ]
{ FOR | AFTER | INSTEAD OF } 
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } 
[ NOT FOR REPLICATION ] 
AS { sql_statement  [ ; ] [ ,...n ] | EXTERNAL NAME <method specifier [ ; ] > }

Download a file with Android, and showing the progress in a ProgressDialog

Use Android Query library, very cool indeed.You can change it to use ProgressDialog as you see in other examples, this one will show progress view from your layout and hide it after completion.

File target = new File(new File(Environment.getExternalStorageDirectory(), "ApplicationName"), "tmp.pdf");
new AQuery(this).progress(R.id.progress_view).download(_competition.qualificationScoreCardsPdf(), target, new AjaxCallback<File>() {
    public void callback(String url, File file, AjaxStatus status) {
        if (file != null) {
            // do something with file  
        } 
    }
});

Bootstrap Modal immediately disappearing

I had the same issue because I was toggling my modal twice as shown below:

statusCode: {
    410: function (request, status, error) { //custom error code

        document.getElementById('modalbody').innerHTML = error;
        $('#myErrorModal').modal('toggle')
    }
},
error: function (request, error) {

    document.getElementById('modalbody').innerHTML = error;
    $('#myErrorModal').modal('toggle')
}

I removed one occurrence of:

$('#myErrorModal').modal('toggle')

and it worked like magic!

Iframe transparent background

I've used this creating an IFrame through Javascript and it worked for me:

// IFrame points to the IFrame element, obviously
IFrame.src = 'about: blank';
IFrame.style.backgroundColor = "transparent";
IFrame.frameBorder = "0";
IFrame.allowTransparency="true";

Not sure if it makes any difference, but I set those properties before adding the IFrame to the DOM. After adding it to the DOM, I set its src to the real URL.

Secure hash and salt for PHP passwords

I usually use SHA1 and salt with the user ID (or some other user-specific piece of information), and sometimes I additionally use a constant salt (so I have 2 parts to the salt).

SHA1 is now also considered somewhat compromised, but to a far lesser degree than MD5. By using a salt (any salt), you're preventing the use of a generic rainbow table to attack your hashes (some people have even had success using Google as a sort of rainbow table by searching for the hash). An attacker could conceivably generate a rainbow table using your salt, so that's why you should include a user-specific salt. That way, they will have to generate a rainbow table for each and every record in your system, not just one for your entire system! With that type of salting, even MD5 is decently secure.

Only on Firefox "Loading failed for the <script> with source"

I had the same problem (different web app though) with the error message and it turned out to be the MIME-Type for .js files was text/x-js instead of application/javascript due to a duplicate entry in mime.types on the server that was responsible for serving the js files. It seems that this is happening if the header X-Content-Type-Options: nosniff is set, which makes Firefox (and Chrome) block the content of the js files.

Git undo local branch delete

If you know the last SHA1 of the branch, you can try

git branch branchName <SHA1>

You can find the SHA1 using git reflog, described in the solution --defect link--.

Access iframe elements in JavaScript

If your iframe is in the same domain as your parent page you can access the elements using document.frames collection.

// replace myIFrame with your iFrame id
// replace myIFrameElemId with your iFrame's element id
// you can work on document.frames['myIFrame'].document like you are working on
// normal document object in JS
window.frames['myIFrame'].document.getElementById('myIFrameElemId')

If your iframe is not in the same domain the browser should prevent such access for security reasons.

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

I have tried to make note about these and have collected and written examples from a java perspective.

HTTP for Java Developers

Reverse Ajax - Old style

Async Handling on server side

Reverse Ajax - New style

Server Sent Events

Putting it here for any java developer who is looking into the same subject.

How to thoroughly purge and reinstall postgresql on ubuntu?

I know an answer has already been provided, but dselect didn't work for me. Here is what worked to find the packages to remove:

# search postgr  | grep ^i
i   postgresql                      - object-relational SQL database (supported 
i A postgresql-8.4                  - object-relational SQL database, version 8.
i A postgresql-client-8.4           - front-end programs for PostgreSQL 8.4     
i A postgresql-client-common        - manager for multiple PostgreSQL client ver
i A postgresql-common               - PostgreSQL database-cluster manager       

# aptitude purge postgresql-8.4 postgresql-client-8.4 postgresql-client-common postgresql-common postgresql

rm -r /etc/postgresql/
rm -r /etc/postgresql-common/
rm -r /var/lib/postgresql/

Finally, editing /etc/passwd and /etc/group

Double precision - decimal places

It is actually 53 binary places, which translates to 15 stable decimal places, meaning that if you round a start out with a number with 15 decimal places, convert it to a double, and then round the double back to 15 decimal places you'll get the same number. To uniquely represent a double you need 17 decimal places (meaning that for every number with 17 decimal places, there's a unique closest double) which is why 17 places are showing up, but not all 17-decimal numbers map to different double values (like in the examples in the other answers).

How to reset par(mfrow) in R

You can reset the plot by doing this:

dev.off()

TypeError: no implicit conversion of Symbol into Integer

myHash.each{|item|..} is returning you array object for item iterative variable like the following :--

[:company_name, "MyCompany"]
[:street, "Mainstreet"]
[:postcode, "1234"]
[:city, "MyCity"]
[:free_seats, "3"]

You should do this:--

def format
  output = Hash.new
  myHash.each do |k, v|
    output[k] = cleanup(v)
  end
  output
end

Is there a “not in” operator in JavaScript for checking object properties?

As already said by Jordão, just negate it:

if (!(id in tutorTimes)) { ... }

Note: The above test if tutorTimes has a property with the name specified in id, anywhere in the prototype chain. For example "valueOf" in tutorTimes returns true because it is defined in Object.prototype.

If you want to test if a property doesn't exist in the current object, use hasOwnProperty:

if (!tutorTimes.hasOwnProperty(id)) { ... }

Or if you might have a key that is hasOwnPropery you can use this:

if (!Object.prototype.hasOwnProperty.call(tutorTimes,id)) { ... }

How to parse json string in Android?

Below is the link which guide in parsing JSON string in android.

http://www.ibm.com/developerworks/xml/library/x-andbene1/?S_TACT=105AGY82&S_CMP=MAVE

Also according to your json string code snippet must be something like this:-

JSONObject mainObject = new JSONObject(yourstring);

JSONObject universityObject = mainObject.getJSONObject("university");
JSONString name = universityObject.getString("name");  
JSONString url = universityObject.getString("url");

Following is the API reference for JSOnObject: https://developer.android.com/reference/org/json/JSONObject.html#getString(java.lang.String)

Same for other object.

Error: Uncaught (in promise): Error: Cannot match any routes Angular 2

I also had the same issue. Tried all ways and it didn't work out until I added the following in app.module.ts

import { Ng4LoadingSpinnerModule } from 'ng4-loading-spinner';

And add the following in your imports in app.module.ts

Ng4LoadingSpinnerModule.forRoot()

This case might be rare but I hope this helps someone out there

How can I combine two HashMap objects containing the same types?

One-liner using Java 8 Stream API:

map3 = Stream.of(map1, map2).flatMap(m -> m.entrySet().stream())
       .collect(Collectors.toMap(Entry::getKey, Entry::getValue))

Among the benefits of this method is ability to pass a merge function, which will deal with values that have the same key, for example:

map3 = Stream.of(map1, map2).flatMap(m -> m.entrySet().stream())
       .collect(Collectors.toMap(Entry::getKey, Entry::getValue, Math::max))

Have a div cling to top of screen if scrolled down past it

The trick is that you have to set it as position:fixed, but only after the user has scrolled past it.

This is done with something like this, attaching a handler to the window.scroll event

   // Cache selectors outside callback for performance. 
   var $window = $(window),
       $stickyEl = $('#the-sticky-div'),
       elTop = $stickyEl.offset().top;

   $window.scroll(function() {
        $stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
    });

This simply adds a sticky CSS class when the page has scrolled past it, and removes the class when it's back up.

And the CSS class looks like this

  #the-sticky-div.sticky {
     position: fixed;
     top: 0;
  }

EDIT- Modified code to cache jQuery objects, faster now.

Unique Key constraints for multiple columns in Entity Framework

In the accepted answer by @chuck, there is a comment saying it will not work in the case of FK.

it worked for me, case of EF6 .Net4.7.2

public class OnCallDay
{
     public int Id { get; set; }
    //[Key]
    [Index("IX_OnCallDateEmployee", 1, IsUnique = true)]
    public DateTime Date { get; set; }
    [ForeignKey("Employee")]
    [Index("IX_OnCallDateEmployee", 2, IsUnique = true)]
    public string EmployeeId { get; set; }
    public virtual ApplicationUser Employee{ get; set; }
}

Function inside a function.?

X returns (value +3), while Y returns (value*2)

Given a value of 4, this means (4+3) * (4*2) = 7 * 8 = 56.

Although functions are not limited in scope (which means that you can safely 'nest' function definitions), this particular example is prone to errors:

1) You can't call y() before calling x(), because function y() won't actually be defined until x() has executed once.

2) Calling x() twice will cause PHP to redeclare function y(), leading to a fatal error:

Fatal error: Cannot redeclare y()

The solution to both would be to split the code, so that both functions are declared independent of each other:

function x ($y) 
{
  return($y+3);
}

function y ($z)
{
  return ($z*2);
}

This is also a lot more readable.

PHP expects T_PAAMAYIM_NEKUDOTAYIM?

From Wikipedia:

In PHP, the scope resolution operator is also called Paamayim Nekudotayim (Hebrew: ?????? ?????????), which means “double colon” in Hebrew.

The name "Paamayim Nekudotayim" was introduced in the Israeli-developed Zend Engine 0.5 used in PHP 3. Although it has been confusing to many developers who do not speak Hebrew, it is still being used in PHP 5, as in this sample error message:

$ php -r :: Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM

As of PHP 5.4, error messages concerning the scope resolution operator still include this name, but have clarified its meaning somewhat:

$ php -r :: Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)

From the official PHP documentation:

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

When referencing these items from outside the class definition, use the name of the class.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon. However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team decided to call it. It actually does mean double-colon - in Hebrew!

Set bootstrap modal body height by percentage

Instead of using a %, the units vh set it to a percent of the viewport (browser window) size.

I was able to set a modal with an image and text beneath to be responsive to the browser window size using vh.

If you just want the content to scroll, you could leave out the part that limits the size of the modal body.

/*When the modal fills the screen it has an even 2.5% on top and bottom*/
/*Centers the modal*/
.modal-dialog {
  margin: 2.5vh auto;
}

/*Sets the maximum height of the entire modal to 95% of the screen height*/
.modal-content {
  max-height: 95vh;
  overflow: scroll;
}

/*Sets the maximum height of the modal body to 90% of the screen height*/
.modal-body {
  max-height: 90vh;
}
/*Sets the maximum height of the modal image to 69% of the screen height*/
.modal-body img {
  max-height: 69vh;
}

Arguments to main in C

Had made just a small change to @anthony code so we can get nicely formatted output with argument numbers and values. Somehow easier to read on output when you have multiple arguments:

#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("The following arguments were passed to main():\n");
    printf("argnum \t value \n");
    for (int i = 0; i<argc; i++) printf("%d \t %s \n", i, argv[i]);
    printf("\n");

    return 0;
} 

And output is similar to:

The following arguments were passed to main():
0        D:\Projects\test\vcpp\bcppcomp1\Debug\bcppcomp.exe
1        -P
2        TestHostAttoshiba
3        _http._tcp
4        local
5        80
6        MyNewArgument
7        200.124.211.235
8        type=NewHost
9        test=yes
10       result=output

Rename specific column(s) in pandas

Use the pandas.DataFrame.rename funtion. Check this link for description.

data.rename(columns = {'gdp': 'log(gdp)'}, inplace = True)

If you intend to rename multiple columns then

data.rename(columns = {'gdp': 'log(gdp)', 'cap': 'log(cap)', ..}, inplace = True)

How can I get a JavaScript stack trace when I throw an exception?

In Firefox it seems that you don't need to throw the exception. It's sufficient to do

e = new Error();
console.log(e.stack);

How to inject a Map using the @Value Spring Annotation?

To get this working with YAML, do this:

property-name: '{
  key1: "value1",
  key2: "value2"
}'

Char array in a struct - incompatible assignment?

Or you could just use dynamic allocation, e.g.:

struct name {
  char *first;
  char *last;
};

struct name sara;
sara.first = "Sara";
sara.last = "Black";
printf("first: %s, last: %s\n", sara.first, sara.last);

What is declarative programming?

It's a method of programming based around describing what something should do or be instead of describing how it should work.

In other words, you don't write algorithms made of expressions, you just layout how you want things to be. Two good examples are HTML and WPF.

This Wikipedia article is a good overview: http://en.wikipedia.org/wiki/Declarative_programming

How to throw RuntimeException ("cannot find symbol")

throw new RuntimeException(msg);

You need the new in there. It's creating an instance and throwing it, not calling a method.

MVC 3: How to render a view without its layout page when loaded via ajax?

Just put the following code on the top of the page

@{
    Layout = "";
}

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

You can define foreign key by:

public class Parent
{
   public int Id { get; set; }
   public virtual ICollection<Child> Childs { get; set; }
}

public class Child
{
   public int Id { get; set; }
   // This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
   public int ParentId { get; set; } 
   public virtual Parent Parent { get; set; }
}

Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.

If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation

Data annotation:

// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }

Fluent API:

modelBuilder.Entity<Child>()
            .HasRequired(c => c.Parent)
            .WithMany(p => p.Childs)
            .HasForeignKey(c => c.ParentId);

Other types of constraints can be enforced by data annotations and model validation.

Edit:

You will get an exception if you don't set ParentId. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.

The order of keys in dictionaries

>>> print sorted(d.keys())
['a', 'b', 'c']

Use the sorted function, which sorts the iterable passed in.

The .keys() method returns the keys in an arbitrary order.

Throwing exceptions in a PHP Try Catch block

throw $e->getMessage();

You try to throw a string

As a sidenote: Exceptions are usually to define exceptional states of the application and not for error messages after validation. Its not an exception, when a user gives you invalid data

How to run a script at a certain time on Linux?

Look at the following:

echo "ls -l" | at 07:00

This code line executes "ls -l" at a specific time. This is an example of executing something (a command in my example) at a specific time. "at" is the command you were really looking for. You can read the specifications here:

http://manpages.ubuntu.com/manpages/precise/en/man1/at.1posix.html http://manpages.ubuntu.com/manpages/xenial/man1/at.1posix.html

Hope it helps!

What does 'git blame' do?

From git-blame:

Annotates each line in the given file with information from the revision which last modified the line. Optionally, start annotating from the given revision.

When specified one or more times, -L restricts annotation to the requested lines.

Example:

[email protected]:~# git blame .htaccess
...
^e1fb2d7 (John Doe 2015-07-03 06:30:25 -0300  4) allow from all
^72fgsdl (Arthur King 2015-07-03 06:34:12 -0300  5)
^e1fb2d7 (John Doe 2015-07-03 06:30:25 -0300  6) <IfModule mod_rewrite.c>
^72fgsdl (Arthur King 2015-07-03 06:34:12 -0300  7)     RewriteEngine On
...

Please note that git blame does not show the per-line modifications history in the chronological sense. It only shows who was the last person to have changed a line in a document up to the last commit in HEAD.

That is to say that in order to see the full history/log of a document line, you would need to run a git blame path/to/file for each commit in your git log.

Jquery Date picker Default Date

$( ".selector" ).datepicker({ defaultDate: null });

and return empty string from backend

How to check version of a CocoaPods framework

pod outdated

When you run pod outdated, CocoaPods will list all pods that have newer versions that the ones listed in the Podfile.lock (the versions currently installed for each pod) and that could be updated (as long as it matches the restrictions like pod 'MyPod', '~>x.y' set in your Podfile)

json.dumps vs flask.jsonify

The choice of one or another depends on what you intend to do. From what I do understand:

  • jsonify would be useful when you are building an API someone would query and expect json in return. E.g: The REST github API could use this method to answer your request.

  • dumps, is more about formating data/python object into json and work on it inside your application. For instance, I need to pass an object to my representation layer where some javascript will display graph. You'll feed javascript with the Json generated by dumps.

Horizontal Scroll Table in Bootstrap/CSS

@Ciwan. You're right. The table goes to full width (much too wide). Not a good solution. Better to do this:

css:

.scrollme {
    overflow-x: auto;
}

html:

<div class="scrollme">                        
  <table class="table table-responsive"> ...
  </table>
</div>

Edit: changing scroll-y to scroll-x

How to make <a href=""> link look like a button?

Like so many others, but with explanation in the css.

_x000D_
_x000D_
/* select all <a> elements with class "button" */
a.button {
  /* use inline-block because it respects padding */
  display: inline-block;
  /* padding creates clickable area around text (top/bottom, left/right) */
  padding: 1em 3em;
  /* round corners */
  border-radius: 5px;
  /* remove underline */
  text-decoration: none;
  /* set colors */
  color: white;
  background-color: #4E9CAF;
}
_x000D_
<a class="button" href="#">Add a problem</a>
_x000D_
_x000D_
_x000D_