Programs & Examples On #Iphone 3gs

The iPhone 3GS is the third version of the iPhone released by Apple, Inc. Use this tag for questions specific to this platform. Don't confuse with the iphone-3g tag.

How can I limit ngFor repeat to some number of items in Angular?

You can directly apply slice() to the variable. StackBlitz Demo

<li *ngFor="let item of list.slice(0, 10);">
   {{item.text}}
</li>

Comma separated results in SQL

Use FOR XML PATH('') - which is converting the entries to a comma separated string and STUFF() -which is to trim the first comma- as follows Which gives you the same comma separated result

SELECT  STUFF((SELECT  ',' + INSTITUTIONNAME
            FROM EDUCATION EE
            WHERE  EE.STUDENTNUMBER=E.STUDENTNUMBER
            ORDER BY sortOrder
        FOR XML PATH('')), 1, 1, '') AS listStr

FROM EDUCATION E
GROUP BY E.STUDENTNUMBER

Here is the FIDDLE

How to create a shortcut using PowerShell

Beginning PowerShell 5.0 New-Item, Remove-Item, and Get-ChildItem have been enhanced to support creating and managing symbolic links. The ItemType parameter for New-Item accepts a new value, SymbolicLink. Now you can create symbolic links in a single line by running the New-Item cmdlet.

New-Item -ItemType SymbolicLink -Path "C:\temp" -Name "calc.lnk" -Value "c:\windows\system32\calc.exe"

Be Carefull a SymbolicLink is different from a Shortcut, shortcuts are just a file. They have a size (A small one, that just references where they point) and they require an application to support that filetype in order to be used. A symbolic link is filesystem level, and everything sees it as the original file. An application needs no special support to use a symbolic link.

Anyway if you want to create a Run As Administrator shortcut using Powershell you can use

$file="c:\temp\calc.lnk"
$bytes = [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON (Use –bor to set RunAsAdministrator option and –bxor to unset)
[System.IO.File]::WriteAllBytes($file, $bytes)

If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.

Change the default base url for axios

Putting my two cents here. I wanted to do the same without hardcoding the URL for my specific request. So i came up with this solution.

To append 'api' to my baseURL, I have my default baseURL set as,

axios.defaults.baseURL = '/api/';

Then in my specific request, after explicitly setting the method and url, i set the baseURL to '/'

axios({
    method:'post',
    url:'logout',
    baseURL: '/',
   })
   .then(response => {
      window.location.reload();
   })
   .catch(error => {
       console.log(error);
   });

Activity has leaked window that was originally added

Dismiss the dialog when activity destroy

@Override
protected void onDestroy()
{
    super.onDestroy();
    if (pDialog!=null && pDialog.isShowing()){
        pDialog.dismiss();
    }
}

Finding blocking/locking queries in MS SQL (mssql)

I found this query which helped me find my locked table and query causing the issue.

SELECT  L.request_session_id AS SPID, 
        DB_NAME(L.resource_database_id) AS DatabaseName,
        O.Name AS LockedObjectName, 
        P.object_id AS LockedObjectId, 
        L.resource_type AS LockedResource, 
        L.request_mode AS LockType,
        ST.text AS SqlStatementText,        
        ES.login_name AS LoginName,
        ES.host_name AS HostName,
        TST.is_user_transaction as IsUserTransaction,
        AT.name as TransactionName,
        CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
        JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
        JOIN sys.objects O ON O.object_id = P.object_id
        JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
        JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
        JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
        JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
        CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id

What does -z mean in Bash?

-z string True if the string is null (an empty string)

UnicodeEncodeError: 'latin-1' codec can't encode character

I hope your database is at least UTF-8. Then you will need to run yourstring.encode('utf-8') before you try putting it into the database.

File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?

System.getProperties() can be overridden by calls to System.setProperty(String key, String value) or with command line parameters -Dfile.separator=/

File.separator gets the separator for the default filesystem.

FileSystems.getDefault() gets you the default filesystem.

FileSystem.getSeparator() gets you the separator character for the filesystem. Note that as an instance method you can use this to pass different filesystems to your code other than the default, in cases where you need your code to operate on multiple filesystems in the one JVM.

What is the difference between Select and Project Operations

Project will effects Columns in the table while Select effects the Rows. on other hand Project is use to select the columns with specefic properties rather than Select the all of columns data

error C2065: 'cout' : undeclared identifier

Include the std library by inserting the following line at the top of your code:

using namespace std;

Processing Symbol Files in Xcode

xCode just copy all crashes logs. If you want to speed-up: delete number of crash reports after you analyze it, directly in this window.

Devices -> View Device Logs -> All Logs

screenshot

In the shell, what does " 2>&1 " mean?

Some tricks about redirection

Some syntax particularity about this may have important behaviours. There is some little samples about redirections, STDERR, STDOUT, and arguments ordering.

1 - Overwriting or appending?

Symbol > means redirection.

  • > means send to as a whole completed file, overwriting target if exist (see noclobber bash feature at #3 later).
  • >> means send in addition to would append to target if exist.

In any case, the file would be created if they not exist.

2 - The shell command line is order dependent!!

For testing this, we need a simple command which will send something on both outputs:

$ ls -ld /tmp /tnt
ls: cannot access /tnt: No such file or directory
drwxrwxrwt 118 root root 196608 Jan  7 11:49 /tmp

$ ls -ld /tmp /tnt >/dev/null
ls: cannot access /tnt: No such file or directory

$ ls -ld /tmp /tnt 2>/dev/null
drwxrwxrwt 118 root root 196608 Jan  7 11:49 /tmp

(Expecting you don't have a directory named /tnt, of course ;). Well, we have it!!

So, let's see:

$ ls -ld /tmp /tnt >/dev/null
ls: cannot access /tnt: No such file or directory

$ ls -ld /tmp /tnt >/dev/null 2>&1

$ ls -ld /tmp /tnt 2>&1 >/dev/null
ls: cannot access /tnt: No such file or directory

The last command line dumps STDERR to the console, and it seem not to be the expected behaviour... But...

If you want to make some post filtering about standard output, error output or both:

$ ls -ld /tmp /tnt | sed 's/^.*$/<-- & --->/'
ls: cannot access /tnt: No such file or directory
<-- drwxrwxrwt 118 root root 196608 Jan  7 12:02 /tmp --->

$ ls -ld /tmp /tnt 2>&1 | sed 's/^.*$/<-- & --->/'
<-- ls: cannot access /tnt: No such file or directory --->
<-- drwxrwxrwt 118 root root 196608 Jan  7 12:02 /tmp --->

$ ls -ld /tmp /tnt >/dev/null | sed 's/^.*$/<-- & --->/'
ls: cannot access /tnt: No such file or directory

$ ls -ld /tmp /tnt >/dev/null 2>&1 | sed 's/^.*$/<-- & --->/'

$ ls -ld /tmp /tnt 2>&1 >/dev/null | sed 's/^.*$/<-- & --->/'
<-- ls: cannot access /tnt: No such file or directory --->

Notice that the last command line in this paragraph is exactly same as in previous paragraph, where I wrote seem not to be the expected behaviour (so, this could even be an expected behaviour).

Well, there is a little tricks about redirections, for doing different operation on both outputs:

$ ( ls -ld /tmp /tnt | sed 's/^/O: /' >&9 ) 9>&2  2>&1  | sed 's/^/E: /'
O: drwxrwxrwt 118 root root 196608 Jan  7 12:13 /tmp
E: ls: cannot access /tnt: No such file or directory

Note: &9 descriptor would occur spontaneously because of ) 9>&2.

Addendum: nota! With the new version of (>4.0) there is a new feature and more sexy syntax for doing this kind of things:

$ ls -ld /tmp /tnt 2> >(sed 's/^/E: /') > >(sed 's/^/O: /')
O: drwxrwxrwt 17 root root 28672 Nov  5 23:00 /tmp
E: ls: cannot access /tnt: No such file or directory

And finally for such a cascading output formatting:

$ ((ls -ld /tmp /tnt |sed 's/^/O: /' >&9 ) 2>&1 |sed 's/^/E: /') 9>&1| cat -n
     1  O: drwxrwxrwt 118 root root 196608 Jan  7 12:29 /tmp
     2  E: ls: cannot access /tnt: No such file or directory

Addendum: nota! Same new syntax, in both ways:

$ cat -n <(ls -ld /tmp /tnt 2> >(sed 's/^/E: /') > >(sed 's/^/O: /'))
     1  O: drwxrwxrwt 17 root root 28672 Nov  5 23:00 /tmp
     2  E: ls: cannot access /tnt: No such file or directory

Where STDOUT go through a specific filter, STDERR to another and finally both outputs merged go through a third command filter.

3 - A word about noclobber option and >| syntax

That's about overwriting:

While set -o noclobber instruct bash to not overwrite any existing file, the >| syntax let you pass through this limitation:

$ testfile=$(mktemp /tmp/testNoClobberDate-XXXXXX)

$ date > $testfile ; cat $testfile
Mon Jan  7 13:18:15 CET 2013

$ date > $testfile ; cat $testfile
Mon Jan  7 13:18:19 CET 2013

$ date > $testfile ; cat $testfile
Mon Jan  7 13:18:21 CET 2013

The file is overwritten each time, well now:

$ set -o noclobber

$ date > $testfile ; cat $testfile
bash: /tmp/testNoClobberDate-WW1xi9: cannot overwrite existing file
Mon Jan  7 13:18:21 CET 2013

$ date > $testfile ; cat $testfile
bash: /tmp/testNoClobberDate-WW1xi9: cannot overwrite existing file
Mon Jan  7 13:18:21 CET 2013

Pass through with >|:

$ date >| $testfile ; cat $testfile
Mon Jan  7 13:18:58 CET 2013

$ date >| $testfile ; cat $testfile
Mon Jan  7 13:19:01 CET 2013

Unsetting this option and/or inquiring if already set.

$ set -o | grep noclobber
noclobber           on

$ set +o noclobber

$ set -o | grep noclobber
noclobber           off

$ date > $testfile ; cat $testfile
Mon Jan  7 13:24:27 CET 2013

$ rm $testfile

4 - Last trick and more...

For redirecting both output from a given command, we see that a right syntax could be:

$ ls -ld /tmp /tnt >/dev/null 2>&1

for this special case, there is a shortcut syntax: &> ... or >&

$ ls -ld /tmp /tnt &>/dev/null

$ ls -ld /tmp /tnt >&/dev/null

Nota: if 2>&1 exist, 1>&2 is a correct syntax too:

$ ls -ld /tmp /tnt 2>/dev/null 1>&2

4b- Now, I will let you think about:

$ ls -ld /tmp /tnt 2>&1 1>&2  | sed -e s/^/++/
++/bin/ls: cannot access /tnt: No such file or directory
++drwxrwxrwt 193 root root 196608 Feb  9 11:08 /tmp/

$ ls -ld /tmp /tnt 1>&2 2>&1  | sed -e s/^/++/
/bin/ls: cannot access /tnt: No such file or directory
drwxrwxrwt 193 root root 196608 Feb  9 11:08 /tmp/

4c- If you're interested in more information

You could read the fine manual by hitting:

man -Len -Pless\ +/^REDIRECTION bash

in a console ;-)

How do I find the PublicKeyToken for a particular dll?

As @CRice said you can use the below method to get a list of dependent assembly with publicKeyToken

public static int DependencyInfo(string args) 
{
    Console.WriteLine(Assembly.LoadFile(args).FullName);
    Console.WriteLine(Assembly.LoadFile(args).GetCustomAttributes(typeof(System.Runtime.Versioning.TargetFrameworkAttribute), false).SingleOrDefault());
    try {
        var assemblies = Assembly.LoadFile(args).GetReferencedAssemblies(); 

        if (assemblies.GetLength(0) > 0)
        {
            foreach (var assembly in assemblies)
            {
                Console.WriteLine(" - " + assembly.FullName + ", ProcessorArchitecture=" + assembly.ProcessorArchitecture);             
            }
            return 0;
        }
    }
    catch(Exception e) {
        Console.WriteLine("An exception occurred: {0}", e.Message);
        return 1;
    } 
    finally{}

    return 1;
}

i generally use it as a LinqPad script you can call it as

DependencyInfo("@c:\MyAssembly.dll"); from the code

How to set locale in DatePipe in Angular 2?

On app.module.ts add the following imports. There is a list of LOCALE options here.

import es from '@angular/common/locales/es';
import { registerLocaleData } from '@angular/common';
registerLocaleData(es);

Then add the provider

@NgModule({
  providers: [
    { provide: LOCALE_ID, useValue: "es-ES" }, //your locale
  ]
})

Use pipes in html. Here is the angular documentation for this.

{{ dateObject | date: 'medium' }}

Why do we use web.xml?

The web.xml file is the deployment descriptor for a Servlet-based Java web application (which most Java web apps are). Among other things, it declares which Servlets exist and which URLs they handle.

The part you cite defines a Servlet Filter. Servlet filters can do all kinds of preprocessing on requests. Your specific example is a filter had the Wicket framework uses as its entry point for all requests because filters are in some way more powerful than Servlets.

How can I remove duplicate rows?

For the table structure

MyTable

RowID int not null identity(1,1) primary key,
Col1 varchar(20) not null,
Col2 varchar(2048) not null,
Col3 tinyint not null

The query for removing duplicates:

DELETE t1
FROM MyTable t1
INNER JOIN MyTable t2
WHERE t1.RowID > t2.RowID
  AND t1.Col1 = t2.Col1
  AND t1.Col2=t2.Col2
  AND t1.Col3=t2.Col3;

I am assuming that RowID is kind of auto-increment and rest of the columns have duplicate values.

Changing default encoding of Python?

A) To control sys.getdefaultencoding() output:

python -c 'import sys; print(sys.getdefaultencoding())'

ascii

Then

echo "import sys; sys.setdefaultencoding('utf-16-be')" > sitecustomize.py

and

PYTHONPATH=".:$PYTHONPATH" python -c 'import sys; print(sys.getdefaultencoding())'

utf-16-be

You could put your sitecustomize.py higher in your PYTHONPATH.

Also you might like to try reload(sys).setdefaultencoding by @EOL

B) To control stdin.encoding and stdout.encoding you want to set PYTHONIOENCODING:

python -c 'import sys; print(sys.stdin.encoding, sys.stdout.encoding)'

ascii ascii

Then

PYTHONIOENCODING="utf-16-be" python -c 'import sys; 
print(sys.stdin.encoding, sys.stdout.encoding)'

utf-16-be utf-16-be

Finally: you can use A) or B) or both!

The listener supports no services

The database registers its service name(s) with the listener when it starts up. If it is unable to do so then it tries again periodically - so if the listener starts after the database then there can be a delay before the service is recognised.

If the database isn't running, though, nothing will have registered the service, so you shouldn't expect the listener to know about it - lsnrctl status or lsnrctl services won't report a service that isn't registered yet.

You can start the database up without the listener; from the Oracle account and with your ORACLE_HOME, ORACLE_SID and PATH set you can do:

sqlplus /nolog

Then from the SQL*Plus prompt:

connect / as sysdba
startup

Or through the Grid infrastructure, from the grid account, use the srvctl start database command:

srvctl start database -d db_unique_name [-o start_options] [-n node_name]

You might want to look at whether the database is set to auto-start in your oratab file, and depending on what you're using whether it should have started automatically. If you're expecting it to be running and it isn't, or you try to start it and it won't come up, then that's a whole different scenario - you'd need to look at the error messages, alert log, possibly trace files etc. to see exactly why it won't start, and if you can't figure it out, maybe ask on Database Adminsitrators rather than on Stack Overflow.


If the database can't see +DATA then ASM may not be running; you can see how to start that here; or using srvctl start asm. As the documentation says, make sure you do that from the grid home, not the database home.

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

If you are using Jersey 2.x use following dependency:

<dependency>
   <groupId>org.glassfish.jersey.containers</groupId>
   <artifactId>jersey-container-servlet-core</artifactId>
   <version>2.XX</version>
</dependency>  

Where XX could be any particular version you look for. Jersey Containers.

Insert ellipsis (...) into HTML tag if content too wide

There's actually a pretty straightforward way to do this in CSS exploiting the fact that IE extends this with non-standards and FF supports :after

You can also do this in JS if you wish by inspecting the scrollWidth of the target and comparing it to it's parents width, but imho this is less robust.

Edit: this is apparently more developed than I thought. CSS3 support may soon exist, and some imperfect extensions are available for you to try.

That last one is good reading.

How can I calculate the difference between two ArrayLists?

THIS WORK ALSO WITH Arraylist

    // Create a couple ArrayList objects and populate them
    // with some delicious fruits.
    ArrayList<String> firstList = new ArrayList<String>() {/**
         * 
         */
        private static final long serialVersionUID = 1L;

    {
        add("apple");
        add("orange");
        add("pea");
    }};

    ArrayList<String> secondList = new ArrayList<String>() {

    /**
         * 
         */
        private static final long serialVersionUID = 1L;

    {
        add("apple");
        add("orange");
        add("banana");
        add("strawberry");
    }};

    // Show the "before" lists
    System.out.println("First List: " + firstList);
    System.out.println("Second List: " + secondList);

    // Remove all elements in firstList from secondList
    secondList.removeAll(firstList);

    // Show the "after" list
    System.out.println("Result: " + secondList);

How do I set a ViewModel on a window in XAML using DataContext property?

In addition to the solution that other people provided (which are good, and correct), there is a way to specify the ViewModel in XAML, yet still separate the specific ViewModel from the View. Separating them is useful for when you want to write isolated test cases.

In App.xaml:

<Application
    x:Class="BuildAssistantUI.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:BuildAssistantUI.ViewModels"
    StartupUri="MainWindow.xaml"
    >
    <Application.Resources>
        <local:MainViewModel x:Key="MainViewModel" />
    </Application.Resources>
</Application>

In MainWindow.xaml:

<Window x:Class="BuildAssistantUI.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DataContext="{StaticResource MainViewModel}"
    />

Removing an item from a select box

I just want to suggest another way to add an option. Instead of setting the value and text as a string one can also do:

var option = $('<option/>')
                  .val('option5')
                  .text('option5');

$('#selectBox').append(option);

This is a less error-prone solution when adding options' values and texts dynamically.

Cast Double to Integer in Java

I think it's impossible to understand the other answers without covering the pitfalls and reasoning behind it.

You cannot directly cast an Integer to a Double object. Also Double and Integer are immutable objects, so you cannot modify them in any way.

Each numeric class has a primitive alternative (Double vs double, Integer vs int, ...). Note that these primitives start with a lowercase character (e.g. int). That tells us that they aren't classes/objects. Which also means that they don't have methods. By contrast, the classes (e.g. Integer) act like boxes/wrappers around these primitives, which makes it possible to use them like objects.

Strategy:

To convert a Double to an Integer you would need to follow this strategy:

  1. Convert the Double object to a primitive double. (= "unboxing")
  2. Convert the primitive double to a primitive int. (= "casting")
  3. Convert the primitive int back to an Integer object. (= "boxing")

In code:

// starting point
Double myDouble = Double.valueOf(10.0);

// step 1: unboxing
double dbl = myDouble.doubleValue();

// step 2: casting
int intgr = (int) dbl;

// step 3: boxing
Integer val = Integer.valueOf(intgr);

Actually there is a shortcut. You can unbox immediately from a Double straight to a primitive int. That way, you can skip step 2 entirely.

Double myDouble = Double.valueOf(10.0);
Integer val = Integer.valueOf(myDouble.intValue()); // the simple way

Pitfalls:

However, there are a lot of things that are not covered in the code above. The code-above is not null-safe.

Double myDouble = null;
Integer val = Integer.valueOf(myDouble.intValue()); // will throw a NullPointerException

// a null-safe solution:
Integer val = (myDouble == null)? null : Integer.valueOf(myDouble.intValue());

Now it works fine for most values. However integers have a very small range (min/max value) compared to a Double. On top of that, doubles can also hold "special values", that integers cannot:

  • 1/0 = +infinity
  • -1/0 = -infinity
  • 0/0 = undefined (NaN)

So, depending on the application, you may want to add some filtering to avoid nasty Exceptions.

Then, the next shortcoming is the rounding strategy. By default Java will always round down. Rounding down makes perfect sense in all programming languages. Basically Java is just throwing away some of the bytes. In financial applications you will surely want to use half-up rounding (e.g.: round(0.5) = 1 and round(0.4) = 0).

// null-safe and with better rounding
long rounded = (myDouble == null)? 0L: Math.round(myDouble.doubleValue());
Integer val = Integer.valueOf(rounded);

Auto-(un)boxing

You could be tempted to use auto-(un)boxing in this, but I wouldn't. If you're already stuck now, then the next examples will not be that obvious neither. If you don't understand the inner workings of auto-(un)boxing then please don't use it.

Integer val1 = 10; // works
Integer val2 = 10.0; // doesn't work

Double val3 = 10; // doesn't work
Double val4 = 10.0; // works

Double val5 = null; 
double val6 = val5; // doesn't work (throws a NullPointerException)

I guess the following shouldn't be a surprise. But if it is, then you may want to read some article about casting in Java.

double val7 = (double) 10; // works
Double val8 = (Double) Integer.valueOf(10); // doesn't work
Integer val9 = (Integer) 9; // pure nonsense

Prefer valueOf:

Also, don't be tempted to use new Integer() constructor (as some other answers propose). The valueOf() methods are better because they use caching. It's a good habit to use these methods, because from time to time they will save you some memory.

long rounded = (myDouble == null)? 0L: Math.round(myDouble.doubleValue());
Integer val = new Integer(rounded); // waste of memory

How to round a number to n decimal places in Java

I have used bellow like in java 8. it is working for me

    double amount = 1000.431;        
    NumberFormat formatter = new DecimalFormat("##.00");
    String output = formatter.format(amount);
    System.out.println("output = " + output);

Output:

output = 1000.43

Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

I just ran into this problem myself.

First, modify your code slightly:

var download = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                  +"<"+this.gamesave.tagName+">"
                  +this.xml.firstChild.innerHTML
                  +"</"+this.gamesave.tagName+">";

this.loader.src = "data:application/x-forcedownload;base64,"+
                  btoa(download);

Then use your favorite web inspector, put a breakpoint on the line of code that assigns this.loader.src, then execute this code:

for (var i = 0; i < download.length; i++) {
  if (download[i].charCodeAt(0) > 255) {
    console.warn('found character ' + download[i].charCodeAt(0) + ' "' + download[i] + '" at position ' + i);
  }
}

Depending on your application, replacing the characters that are out of range may or may not work, since you'll be modifying the data. See the note on MDN about unicode characters with the btoa method:

https://developer.mozilla.org/en-US/docs/Web/API/window.btoa

What is a stored procedure?

for simple,

Stored Procedure are Stored Programs, A program/function stored into database.

Each stored program contains a body that consists of an SQL statement. This statement may be a compound statement made up of several statements separated by semicolon (;) characters.

CREATE PROCEDURE dorepeat(p1 INT)
BEGIN
  SET @x = 0;
  REPEAT SET @x = @x + 1; UNTIL @x > p1 END REPEAT;
END;

Convert UTF-8 encoded NSData to NSString

If the data is not null-terminated, you should use -initWithData:encoding:

NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];

If the data is null-terminated, you should instead use -stringWithUTF8String: to avoid the extra \0 at the end.

NSString* newStr = [NSString stringWithUTF8String:[theData bytes]];

(Note that if the input is not properly UTF-8-encoded, you will get nil.)


Swift variant:

let newStr = String(data: data, encoding: .utf8)
// note that `newStr` is a `String?`, not a `String`.

If the data is null-terminated, you could go though the safe way which is remove the that null character, or the unsafe way similar to the Objective-C version above.

// safe way, provided data is \0-terminated
let newStr1 = String(data: data.subdata(in: 0 ..< data.count - 1), encoding: .utf8)
// unsafe way, provided data is \0-terminated
let newStr2 = data.withUnsafeBytes(String.init(utf8String:))

How to list all tags along with the full message in git?

Use --format option

git tag -l --format='%(tag) %(subject)'

Android button with icon and text

This is what you really want.

<Button
       android:id="@+id/settings"
       android:layout_width="190dp"
       android:layout_height="wrap_content"
       android:layout_gravity="center_horizontal"
       android:background="@color/colorAccent"
       android:drawableStart="@drawable/ic_settings_black_24dp"
       android:paddingStart="40dp"
       android:paddingEnd="40dp"
       android:text="settings"
       android:textColor="#FFF" />

Can I use multiple "with"?

Try:

With DependencedIncidents AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
),
lalala AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
)

And yes, you can reference common table expression inside common table expression definition. Even recursively. Which leads to some very neat tricks.

Fragment onCreateView and onActivityCreated called twice

The two upvoted answers here show solutions for an Activity with navigation mode NAVIGATION_MODE_TABS, but I had the same issue with a NAVIGATION_MODE_LIST. It caused my Fragments to inexplicably lose their state when the screen orientation changed, which was really annoying. Thankfully, due to their helpful code I managed to figure it out.

Basically, when using a list navigation, ``onNavigationItemSelected()is automatically called when your activity is created/re-created, whether you like it or not. To prevent your Fragment'sonCreateView()from being called twice, this initial automatic call toonNavigationItemSelected()should check whether the Fragment is already in existence inside your Activity. If it is, return immediately, because there is nothing to do; if it isn't, then simply construct the Fragment and add it to the Activity like you normally would. Performing this check prevents your Fragment from needlessly being created again, which is what causesonCreateView()` to be called twice!

See my onNavigationItemSelected() implementation below.

public class MyActivity extends FragmentActivity implements ActionBar.OnNavigationListener
{
    private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";

    private boolean mIsUserInitiatedNavItemSelection;

    // ... constructor code, etc.

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);

        if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM))
        {
            getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState)
    {
        outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar().getSelectedNavigationIndex());

        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean onNavigationItemSelected(int position, long id)
    {    
        Fragment fragment;
        switch (position)
        {
            // ... choose and construct fragment here
        }

        // is this the automatic (non-user initiated) call to onNavigationItemSelected()
        // that occurs when the activity is created/re-created?
        if (!mIsUserInitiatedNavItemSelection)
        {
            // all subsequent calls to onNavigationItemSelected() won't be automatic
            mIsUserInitiatedNavItemSelection = true;

            // has the same fragment already replaced the container and assumed its id?
            Fragment existingFragment = getSupportFragmentManager().findFragmentById(R.id.container);
            if (existingFragment != null && existingFragment.getClass().equals(fragment.getClass()))
            {
                return true; //nothing to do, because the fragment is already there 
            }
        }

        getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
        return true;
    }
}

I borrowed inspiration for this solution from here.

Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

@aimme's answer should be accepted!

I would extend his answer with @david-baucum's comment because his explanation is clear!

I would also extend his answer that you can run multiple PHP versions at the same time using ppa:ondrej/php.

Then you don't need to change the PHP version simple call the composer like this: /usr/bin/php7.2 /usr/local/bin/composer install

Preloading CSS Images

For preloading background images set with CSS, the most efficient answer i came up with was a modified version of some code I found that did not work:

$(':hidden').each(function() {
  var backgroundImage = $(this).css("background-image");
  if (backgroundImage != 'none') {
    tempImage = new Image();
    tempImage.src = backgroundImage;
  }
});

The massive benefit of this is that you don't need to update it when you bring in new background images in the future, it will find the new ones and preload them!

How to force addition instead of concatenation in javascript

Should also be able to do this:

total += eval(myInt1) + eval(myInt2) + eval(myInt3);

This helped me in a different, but similar, situation.

Difference between uint32 and uint32_t

uint32_t is defined in the standard, in

18.4.1 Header <cstdint> synopsis [cstdint.syn]

namespace std {
//...
typedef unsigned integer type uint32_t; // optional
//...
}

uint32 is not, it's a shortcut provided by some compilers (probably as typedef uint32_t uint32) for ease of use.

Display Animated GIF

I think the better library to handle gif files is this one: by koral

Used it and i'm successful and this library is dedicated to GIF'S; but where as the picasso and glide are general purpose image framework; so i think the developers of this library have entirely concentrated on gif files

How to restore the permissions of files and directories within git if they have been modified?

Git keeps track of filepermission and exposes permission changes when creating patches using git diff -p. So all we need is:

  1. create a reverse patch
  2. include only the permission changes
  3. apply the patch to our working copy

As a one-liner:

git diff -p -R --no-ext-diff --no-color \
    | grep -E "^(diff|(old|new) mode)" --color=never  \
    | git apply

you can also add it as an alias to your git config...

git config --global --add alias.permission-reset '!git diff -p -R --no-ext-diff --no-color | grep -E "^(diff|(old|new) mode)" --color=never | git apply'

...and you can invoke it via:

git permission-reset

Note, if you shell is bash, make sure to use ' instead of " quotes around the !git, otherwise it gets substituted with the last git command you ran.

Thx to @Mixologic for pointing out that by simply using -R on git diff, the cumbersome sed command is no longer required.

How to build and fill pandas dataframe from for loop?

Make a list of tuples with your data and then create a DataFrame with it:

d = []
for p in game.players.passing():
    d.append((p, p.team, p.passer_rating()))

pd.DataFrame(d, columns=('Player', 'Team', 'Passer Rating'))

A list of tuples should have less overhead than a list dictionaries. I tested this below, but please remember to prioritize ease of code understanding over performance in most cases.

Testing functions:

def with_tuples(loop_size=1e5):
    res = []

    for x in range(int(loop_size)):
        res.append((x-1, x, x+1))

    return pd.DataFrame(res, columns=("a", "b", "c"))

def with_dict(loop_size=1e5):
    res = []

    for x in range(int(loop_size)):
        res.append({"a":x-1, "b":x, "c":x+1})

    return pd.DataFrame(res)

Results:

%timeit -n 10 with_tuples()
# 10 loops, best of 3: 55.2 ms per loop

%timeit -n 10 with_dict()
# 10 loops, best of 3: 130 ms per loop

What is SYSNAME data type in SQL Server?

sysname is a built in datatype limited to 128 Unicode characters that, IIRC, is used primarily to store object names when creating scripts. Its value cannot be NULL

It is basically the same as using nvarchar(128) NOT NULL

EDIT

As mentioned by @Jim in the comments, I don't think there is really a business case where you would use sysname to be honest. It is mainly used by Microsoft when building the internal sys tables and stored procedures etc within SQL Server.

For example, by executing Exec sp_help 'sys.tables' you will see that the column name is defined as sysname this is because the value of this is actually an object in itself (a table)

I would worry too much about it.

It's also worth noting that for those people still using SQL Server 6.5 and lower (are there still people using it?) the built in type of sysname is the equivalent of varchar(30)

Documentation

sysname is defined with the documentation for nchar and nvarchar, in the remarks section:

sysname is a system-supplied user-defined data type that is functionally equivalent to nvarchar(128), except that it is not nullable. sysname is used to reference database object names.

To clarify the above remarks, by default sysname is defined as NOT NULL it is certainly possible to define it as nullable. It is also important to note that the exact definition can vary between instances of SQL Server.

Using Special Data Types

The sysname data type is used for table columns, variables, and stored procedure parameters that store object names. The exact definition of sysname is related to the rules for identifiers. Therefore, it can vary between instances of SQL Server. sysname is functionally the same as nvarchar(128) except that, by default, sysname is NOT NULL. In earlier versions of SQL Server, sysname is defined as varchar(30).

Some further information about sysname allowing or disallowing NULL values can be found here https://stackoverflow.com/a/52290792/300863

Just because it is the default (to be NOT NULL) does not guarantee that it will be!

ORA-00979 not a group by expression

If you do grouping by virtue of including GROUP BY clause, any expression in SELECT, which is not group function (or aggregate function or aggregated column) such as COUNT, AVG, MIN, MAX, SUM and so on (List of Aggregate functions) should be present in GROUP BY clause.

Example (correct way) (here employee_id is not group function (non-aggregated column), so it must appear in GROUP BY. By contrast, sum(salary) is a group function (aggregated column), so it is not required to appear in the GROUP BYclause.

   SELECT employee_id, sum(salary) 
   FROM employees
   GROUP BY employee_id; 

Example (wrong way) (here employee_id is not group function and it does not appear in GROUP BY clause, which will lead to the ORA-00979 Error .

   SELECT employee_id, sum(salary) 
   FROM employees;

To correct you need to do one of the following :

  • Include all non-aggregated expressions listed in SELECT clause in the GROUP BY clause
  • Remove group (aggregate) function from SELECT clause.

How to remove unused dependencies from composer?

Just run composer install - it will make your vendor directory reflect dependencies in composer.lock file.

In other words - it will delete any vendor which is missing in composer.lock.

Please update the composer itself before running this.

null check in jsf expression language

Use empty (it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"

If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"

Update: as per the comments, the Map turns out to actually be a List (please work on your naming conventions). To check if a List contains an item the "normal" EL way, use JSTL fn:contains (although not explicitly documented, it works for List as well).

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"

Javascript form validation with password confirming

add this to your form:

<form  id="regform" action="insert.php" method="post">

add this to your function:

<script>
    function myFunction() {
        var pass1 = document.getElementById("pass1").value;
        var pass2 = document.getElementById("pass2").value;
        if (pass1 != pass2) {
            //alert("Passwords Do not match");
            document.getElementById("pass1").style.borderColor = "#E34234";
            document.getElementById("pass2").style.borderColor = "#E34234";
        }
        else {
            alert("Passwords Match!!!");
            document.getElementById("regForm").submit();
        }
    }
</script>

how to change language for DataTable

If you are using Angular and Firebase, you can also use the DTOptionsBuilder :

angular.module('your_module', [
'ui.router',
'oc.lazyLoad',
'ui.bootstrap',
'ngSanitize',
'firebase']).controller("your_controller", function ($scope, $firebaseArray, DTOptionsBuilder) {

var ref = firebase.database().ref().child("your_database_table");

// create a synchronized array
$scope.your_database_table = $firebaseArray(ref);

ref.on('value', snap => {

    $scope.dtOptions = DTOptionsBuilder.newOptions()
        .withOption('language',
        {
            "sProcessing": "Traitement en cours...",
            "sSearch": "Rechercher&nbsp;:",
            "sLengthMenu": "Afficher _MENU_ &eacute;l&eacute;ments",
            "sInfo": "Affichage de l'&eacute;l&eacute;ment _START_ &agrave; _END_ sur _TOTAL_ &eacute;l&eacute;ments",
            "sInfoEmpty": "Affichage de l'&eacute;l&eacute;ment 0 &agrave; 0 sur 0 &eacute;l&eacute;ment",
            "sInfoFiltered": "(filtr&eacute; de _MAX_ &eacute;l&eacute;ments au total)",
            "sInfoPostFix": "",
            "sLoadingRecords": "Chargement en cours...",
            "sZeroRecords": "Aucun &eacute;l&eacute;ment &agrave; afficher",
            "sEmptyTable": "Aucune donn&eacute;e disponible dans le tableau",
            "oPaginate": {
                "sFirst": "Premier",
                "sPrevious": "Pr&eacute;c&eacute;dent",
                "sNext": "Suivant",
                "sLast": "Dernier"
            },
            "oAria": {
                "sSortAscending": ": activer pour trier la colonne par ordre croissant",
                "sSortDescending": ": activer pour trier la colonne par ordre d&eacute;croissant"
            }
        }
        )

});})

I hope this will help.

Add an object to an Array of a custom class

If you want to create a garage and fill it up with new cars that can be accessed later, use this code:

for (int i = 0; i < garage.length; i++)
     garage[i] = new Car("argument");

Also, the cars are later accessed using:

garage[0];
garage[1];
garage[2];
etc.

Counting the number of option tags in a select tag in jQuery

The W3C solution:

var len = document.getElementById("input1").length;

Case-insensitive search in Rails model

Quoting from the SQLite documentation:

Any other character matches itself or its lower/upper case equivalent (i.e. case-insensitive matching)

...which I didn't know.But it works:

sqlite> create table products (name string);
sqlite> insert into products values ("Blue jeans");
sqlite> select * from products where name = 'Blue Jeans';
sqlite> select * from products where name like 'Blue Jeans';
Blue jeans

So you could do something like this:

name = 'Blue jeans'
if prod = Product.find(:conditions => ['name LIKE ?', name])
    # update product or whatever
else
    prod = Product.create(:name => name)
end

Not #find_or_create, I know, and it may not be very cross-database friendly, but worth looking at?

JS jQuery - check if value is in array

You are comparing a jQuery object (jQuery('input:first')) to strings (the elements of the array).
Change the code in order to compare the input's value (wich is a string) to the array elements:

if (jQuery.inArray(jQuery("input:first").val(), ar) != -1)

The inArray method returns -1 if the element wasn't found in the array, so as your bonus answer to how to determine if an element is not in an array, use this :

if(jQuery.inArray(el,arr) == -1){
    // the element is not in the array
};

How to convert webpage into PDF by using Python

You also can use pdfkit:

Usage

import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')

Install

MacOS: brew install Caskroom/cask/wkhtmltopdf

Debian/Ubuntu: apt-get install wkhtmltopdf

Windows: choco install wkhtmltopdf

See official documentation for MacOS/Ubuntu/other OS: https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf

MATLAB, Filling in the area between two sets of data, lines in one figure

Personally, I find it both elegant and convenient to wrap the fill function. To fill between two equally sized row vectors Y1 and Y2 that share the support X (and color C):

fill_between_lines = @(X,Y1,Y2,C) fill( [X fliplr(X)],  [Y1 fliplr(Y2)], C );

How do I redirect a user when a button is clicked?

It has been my experience that ASP MVC really does not like traditional use of button so much. Instead I use:

  <input type="button" class="addYourCSSClassHere" value="WordsOnButton" onclick="window.location= '@Url.Action( "ActionInControllerHere", "ControllerNameHere")'" />

Returning a stream from File.OpenRead()

You forgot to seek:

str.CopyTo(data);
data.Seek(0, SeekOrigin.Begin); // <-- missing line
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

Instead of:

input:not(disabled)not:[type="submit"]:focus {}

Use:

input:not([disabled]):not([type="submit"]):focus {}

disabled is an attribute so it needs the brackets, and you seem to have mixed up/missing colons and parentheses on the :not() selector.

Demo: http://jsfiddle.net/HSKPx/

One thing to note: I may be wrong, but I don't think disabled inputs can normally receive focus, so that part may be redundant.

Alternatively, use :enabled

input:enabled:not([type="submit"]):focus { /* styles here */ }

Again, I can't think of a case where disabled input can receive focus, so it seems unnecessary.

Make XAMPP / Apache serve file outside of htdocs folder

You can set Apache to serve pages from anywhere with any restrictions but it's normally distributed in a more secure form.

Editing your apache files (http.conf is one of the more common names) will allow you to set any folder so it appears in your webroot.

EDIT:

alias myapp c:\myapp\

I've edited my answer to include the format for creating an alias in the http.conf file which is sort of like a shortcut in windows or a symlink under un*x where Apache 'pretends' a folder is in the webroot. This is probably going to be more useful to you in the long term.

Matrix multiplication in OpenCV

You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.

Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple * operator:

C = A * B

Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul() function:

output = A.mul(B);

What does "export" do in shell programming?

it makes the assignment visible to subprocesses.

$ foo=bar
$ bash -c 'echo $foo'

$ export foo
$ bash -c 'echo $foo'
bar

Android Viewpager as Image Slide Gallery

Hi if your are looking for simple android image sliding with circle indicator you can download the complete code from here http://javaant.com/viewpager-with-circle-indicator-in-android/#.VysQQRV96Hs . please check the live demo which will give the clear idea.

How to use onClick with divs in React.js

This also works:

I just changed with this.state.color==='white'?'black':'white'.

You can also pick the color from drop-down values and update in place of 'black';

(CodePen)

Vim clear last search highlighting

Disable search highlighting permanently

Matches won't be highlighted whenever you do a search using /

:set nohlsearch

Clear highlight until next search

:noh

or :nohlsearch (clears until n or N is pressed)


Clear highlight on pressing ESC

nnoremap <esc> :noh<return><esc>

Clear highlight on pressing another key or custom map

  • Clear highlights on pressing \ (backslash)

    nnoremap \ :noh<return>
    
  • Clear highlights on hitting ESC twice

    nnoremap <esc><esc> :noh<return>
    

How to change Visual Studio 2012,2013 or 2015 License Key?

For those of you using Visual Studio 2017 Professional, the registry key is:

HKCR\Licenses\5C505A59-E312-4B89-9508-E162F8150517

I also recommend you first export the registry key, before you delete it, so you'll have a backup if you accidentally delete the wrong key.

Copy Files from Windows to the Ubuntu Subsystem

You should only access Linux files system (those located in lxss folder) from inside WSL; DO NOT create/modify any files in lxss folder in Windows - it's dangerous and WSL will not see these files.

Files can be shared between WSL and Windows, though; put the file outside of lxss folder. You can access them via drvFS (/mnt) such as /mnt/c/Users/yourusername/files within WSL. These files stay synced between WSL and Windows.

For details and why, see: https://blogs.msdn.microsoft.com/commandline/2016/11/17/do-not-change-linux-files-using-windows-apps-and-tools/

What is the right way to write my script 'src' url for a local development environment?

Write the src tag for calling the js file as

<script type='text/javascript' src='../Users/myUserName/Desktop/myPage.js'></script>

This should work.

How do I generate a random int number?

The numbers generated by the inbuilt Random class (System.Random) generates pseudo random numbers.

If you want true random numbers, the closest we can get is "secure Pseudo Random Generator" which can be generated by using the Cryptographic classes in C# such as RNGCryptoServiceProvider.

Even so, if you still need true random numbers you will need to use an external source such as devices accounting for radioactive decay as a seed for an random number generator. Since, by definition, any number generated by purely algorithmic means cannot be truly random.

Why should I use core.autocrlf=true in Git?

I am a .NET developer, and have used Git and Visual Studio for years. My strong recommendation is set line endings to true. And do it as early as you can in the lifetime of your Repository.

That being said, I HATE that Git changes my line endings. A source control should only save and retrieve the work I do, it should NOT modify it. Ever. But it does.

What will happen if you don't have every developer set to true, is ONE developer eventually will set to true. This will begin to change the line endings of all of your files to LF in your repo. And when users set to false check those out, Visual Studio will warn you, and ask you to change them. You will have 2 things happen very quickly. One, you will get more and more of those warnings, the bigger your team the more you get. The second, and worse thing, is that it will show that every line of every modified file was changed(because the line endings of every line will be changed by the true guy). Eventually you won't be able to track changes in your repo reliably anymore. It is MUCH easier and cleaner to make everyone keep to true, than to try to keep everyone false. As horrible as it is to live with the fact that your trusted source control is doing something it should not. Ever.

How to save picture to iPhone photo library?

I created a UIImageView category for this, based on some of the answers above.

Header File:

@interface UIImageView (SaveImage) <UIActionSheetDelegate>
- (void)addHoldToSave;
@end

Implementation

@implementation UIImageView (SaveImage)
- (void)addHoldToSave{
    UILongPressGestureRecognizer* longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    longPress.minimumPressDuration = 1.0f;
    [self addGestureRecognizer:longPress];
}

-  (void)handleLongPress:(UILongPressGestureRecognizer*)sender {
    if (sender.state == UIGestureRecognizerStateEnded) {

        UIActionSheet* _attachmentMenuSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                                          delegate:self
                                                                 cancelButtonTitle:@"Cancel"
                                                            destructiveButtonTitle:nil
                                                                 otherButtonTitles:@"Save Image", nil];
        [_attachmentMenuSheet showInView:[[UIView alloc] initWithFrame:self.frame]];
    }
    else if (sender.state == UIGestureRecognizerStateBegan){
        //Do nothing
    }
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if  (buttonIndex == 0) {
        UIImageWriteToSavedPhotosAlbum(self.image, nil,nil, nil);
    }
}


@end

Now simply call this function on your imageview:

[self.imageView addHoldToSave];

Optionally you can alter the minimumPressDuration parameter.

Multiple "order by" in LINQ

Add "new":

var movies = _db.Movies.OrderBy( m => new { m.CategoryID, m.Name })

That works on my box. It does return something that can be used to sort. It returns an object with two values.

Similar, but different to sorting by a combined column, as follows.

var movies = _db.Movies.OrderBy( m => (m.CategoryID.ToString() + m.Name))

Get value of a string after last slash in JavaScript

Try;

var str = "foo/bar/test.html";
var tmp = str.split("/");
alert(tmp.pop());

How to initialize const member variable in a class?

If you don't want to make the const data member in class static, You can initialize the const data member using the constructor of the class. For example:

class Example{
      const int x;
    public:
      Example(int n);
};

Example::Example(int n):x(n){
}

if there are multiple const data members in class you can use the following syntax to initialize the members:

Example::Example(int n, int z):x(n),someOtherConstVariable(z){}

How do I convert a factor into date format?

You were close. format= needs to be added to the as.Date call:

mydate <- factor("1/15/2006 0:00:00")
as.Date(mydate, format = "%m/%d/%Y")
## [1] "2006-01-15"

Can I bind an array to an IN() condition?

Is it so important to use IN statement? Try to use FIND_IN_SET op.

For example, there is a query in PDO like that

SELECT * FROM table WHERE FIND_IN_SET(id, :array)

Then you only need to bind an array of values, imploded with comma, like this one

$ids_string = implode(',', $array_of_smth); // WITHOUT WHITESPACES BEFORE AND AFTER THE COMMA
$stmt->bindParam('array', $ids_string);

and it's done.

UPD: As some people pointed out in comments to this answer, there are some issues which should be stated explciitly.

  1. FIND_IN_SET doesn't use index in a table, and it is still not implemented yet - see this record in the MYSQL bug tracker. Thanks to @BillKarwin for the notice.
  2. You can't use a string with comma inside as a value of the array for search. It is impossible to parse such string in the right way after implode since you use comma symbol as a separator. Thanks to @VaL for the note.

In fine, if you are not heavily dependent on indexes and do not use strings with comma for search, my solution will be much easier, simpler, and faster than solutions listed above.

Efficient way to remove keys with empty strings from a dict

It can get even shorter than BrenBarn's solution (and more readable I think)

{k: v for k, v in metadata.items() if v}

Tested with Python 2.7.3.

Get values from label using jQuery

Firstly, I don't think spaces for an id is valid.

So i'd change the id to not include spaces.

<label year="2010" month="6" id="currentMonth"> June &nbsp;2010</label>

then the jquery code is simple (keep in mind, its better to fetch the jquery object once and use over and over agian)

var label = $('#currentMonth');
var month = label.attr('month');
var year = label.attr('year');
var text = label.text();

How to deserialize a list using GSON or another JSON library in Java?

I recomend this one-liner

List<Video> videos = Arrays.asList(new Gson().fromJson(json, Video[].class));

Warning: the list of videos, returned by Arrays.asList is immutable - you can't insert new values. If you need to modify it, wrap in new ArrayList<>(...).


Reference:

  1. Method Arrays#asList
  2. Constructor Gson
  3. Method Gson#fromJson (source json may be of type JsonElement, Reader, or String)
  4. Interface List
  5. JLS - Arrays
  6. JLS - Generic Interfaces

What to return if Spring MVC controller method doesn't return value?

There is nothing wrong with returning a void @ResponseBody and you should for POST requests.

Use HTTP status codes to define errors within exception handler routines instead as others are mentioning success status. A normal method as you have will return a response code of 200 which is what you want, any exception handler can then return an error object and a different code (i.e. 500).

How to read data from a zip file without having to unzip the entire file

DotNetZip is your friend here.

As easy as:

using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
  ZipEntry e = zip["MyReport.doc"];
  e.Extract(OutputStream);
}

(you can also extract to a file or other destinations).

Reading the zip file's table of contents is as easy as:

using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
  foreach (ZipEntry e in zip)
  {
    if (header)
    {
      System.Console.WriteLine("Zipfile: {0}", zip.Name);
      if ((zip.Comment != null) && (zip.Comment != "")) 
        System.Console.WriteLine("Comment: {0}", zip.Comment);
      System.Console.WriteLine("\n{1,-22} {2,8}  {3,5}   {4,8}  {5,3} {0}",
                               "Filename", "Modified", "Size", "Ratio", "Packed", "pw?");
      System.Console.WriteLine(new System.String('-', 72));
      header = false;
    }
    System.Console.WriteLine("{1,-22} {2,8} {3,5:F0}%   {4,8}  {5,3} {0}",
                             e.FileName,
                             e.LastModified.ToString("yyyy-MM-dd HH:mm:ss"),
                             e.UncompressedSize,
                             e.CompressionRatio,
                             e.CompressedSize,
                             (e.UsesEncryption) ? "Y" : "N");

  }
}

Edited To Note: DotNetZip used to live at Codeplex. Codeplex has been shut down. The old archive is still available at Codeplex. It looks like the code has migrated to Github:


Convert named list to vector with values only

This can be done by using unlist before as.vector. The result is the same as using the parameter use.names=FALSE.

as.vector(unlist(myList))

Android - Get value from HashMap

Note: If you know Key, use this code

String value=meMap.get(key);

Sniffing/logging your own Android Bluetooth traffic

Also, this might help finding the actual location the btsnoop_hci.log is being saved:

adb shell "cat /etc/bluetooth/bt_stack.conf | grep FileName"

How to send email via Django?

Late, but:

In addition to the DEFAULT_FROM_EMAIL fix others have mentioned, and allowing less-secure apps to access the account, I had to navigate to https://accounts.google.com/DisplayUnlockCaptcha while signed in as the account in question to get Django to finally authenticate.

I went to that URL through a SSH tunnel to the web server to make sure the IP address was the same; I'm not totally sure if that's necessary but it can't hurt. You can do that like so: ssh -D 8080 -fN <username>@<host>, then set your web browser to use localhost:8080 as a SOCKS proxy.

support FragmentPagerAdapter holds reference to old fragments

I solved this issue by accessing my fragments directly through the FragmentManager instead of via the FragmentPagerAdapter like so. First I need to figure out the tag of the fragment auto generated by the FragmentPagerAdapter...

private String getFragmentTag(int pos){
    return "android:switcher:"+R.id.viewpager+":"+pos;
}

Then I simply get a reference to that fragment and do what I need like so...

Fragment f = this.getSupportFragmentManager().findFragmentByTag(getFragmentTag(1));
((MyFragmentInterface) f).update(id, name);
viewPager.setCurrentItem(1, true);

Inside my fragments I set the setRetainInstance(false); so that I can manually add values to the savedInstanceState bundle.

@Override
public void onSaveInstanceState(Bundle outState) {
    if(this.my !=null)
        outState.putInt("myId", this.my.getId());

    super.onSaveInstanceState(outState);
}

and then in the OnCreate i grab that key and restore the state of the fragment as necessary. An easy solution which was hard (for me at least) to figure out.

jinja2.exceptions.TemplateNotFound error

I think you shouldn't prepend themesDir. You only pass the filename of the template to flask, it will then look in a folder called templates relative to your python file.

Hash function for a string

First, it usually does not matter that much in practice. Most hash functions are "good enough".

But if you really care, you should know that it is a research subject by itself. There are thousand of papers about that. You can still get a PhD today by studying & designing hashing algorithms.

Your second hash function might be slightly better, because it probably should separate the string "ab" from the string "ba". On the other hand, it is probably less quick than the first hash function. It may, or may not, be relevant for your application.

I'll guess that hash functions used for genome strings are quite different than those used to hash family names in telephone databases. Perhaps even some string hash functions are better suited for German, than for English or French words.

Many software libraries give you good enough hash functions, e.g. Qt has qhash, and C++11 has std::hash in <functional>, Glib has several hash functions in C, and POCO has some hash function.

I quite often have hashing functions involving primes (see Bézout's identity) and xor, like e.g.

#define A 54059 /* a prime */
#define B 76963 /* another prime */
#define C 86969 /* yet another prime */
#define FIRSTH 37 /* also prime */
unsigned hash_str(const char* s)
{
   unsigned h = FIRSTH;
   while (*s) {
     h = (h * A) ^ (s[0] * B);
     s++;
   }
   return h; // or return h % C;
}

But I don't claim to be an hash expert. Of course, the values of A, B, C, FIRSTH should preferably be primes, but you could have chosen other prime numbers.

Look at some MD5 implementation to get a feeling of what hash functions can be.

Most good books on algorithmics have at least a whole chapter dedicated to hashing. Start with wikipages on hash function & hash table.

Array Length in Java

Arrays are static memory allocation, so if you initialize an array of integers:

int[] intArray = new int[15];

The length will be always 15, no matter how many indexes are filled.

And another thing, when you intialize an array of integers, all the indexes will be filled with "0".

Indent starting from the second line of a paragraph with CSS

There is a CSS3 working draft that will (hopefully soon) allow you to write just:

p { text-indent: 200px hanging; }

Keep an eye on: https://developer.mozilla.org/en-US/docs/Web/CSS/text-indent

C Linking Error: undefined reference to 'main'

You're not including the C file that contains main() when compiling, so the linker isn't seeing it.

You need to add it:

$ gcc -o runexp runexp.c scd.o data_proc.o -lm -fopenmp

Properties file in python (similar to Java Properties)

If you need to read all values from a section in properties file in a simple manner:

Your config.properties file layout :

[SECTION_NAME]  
key1 = value1  
key2 = value2  

You code:

   import configparser

   config = configparser.RawConfigParser()
   config.read('path_to_config.properties file')

   details_dict = dict(config.items('SECTION_NAME'))

This will give you a dictionary where keys are same as in config file and their corresponding values.

details_dict is :

{'key1':'value1', 'key2':'value2'}

Now to get key1's value : details_dict['key1']

Putting it all in a method which reads that section from config file only once(the first time the method is called during a program run).

def get_config_dict():
    if not hasattr(get_config_dict, 'config_dict'):
        get_config_dict.config_dict = dict(config.items('SECTION_NAME'))
    return get_config_dict.config_dict

Now call the above function and get the required key's value :

config_details = get_config_dict()
key_1_value = config_details['key1'] 

-------------------------------------------------------------

Extending the approach mentioned above, reading section by section automatically and then accessing by section name followed by key name.

def get_config_section():
    if not hasattr(get_config_section, 'section_dict'):
        get_config_section.section_dict = dict()

        for section in config.sections():
            get_config_section.section_dict[section] = 
                             dict(config.items(section))

    return get_config_section.section_dict

To access:

config_dict = get_config_section()

port = config_dict['DB']['port'] 

(here 'DB' is a section name in config file and 'port' is a key under section 'DB'.)

iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”

Even though allowing arbitrary loads (NSAllowsArbitraryLoads = true) is a good workaround, you shouldn't entirely disable ATS but rather enable the HTTP connection you want to allow:

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

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

I'll try to make you understand with the help of an example. Suppose you had a relational table (STUDENT) with two columns and ID(int) and NAME(String). Now as ORM you would've made an entity class somewhat like as follows:-

package com.kashyap.default;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author vaibhav.kashyap
 *
 */
@Entity
@Table(name = "STUDENT")
public class Student implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -1354919370115428781L;

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "NAME")
    private String name;

    public Student(){

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Lets assume table already had entries. Now if somebody asks you add another column of "AGE" (int)

ALTER TABLE STUDENT ADD AGE int NULL

You'll have to set default values as NULL to add another column in a pre-filled table. This makes you add another field in the class. Now the question arises whether you'll be using a primitive data type or non primitive wrapper data type for declaring the field.

@Column(name = "AGE")
private int age;

or

@Column(name = "AGE")
private INTEGER age;

you'll have to declare the field as non primitive wrapper data type because the container will try to map the table with the entity. Hence it wouldn't able to map NULL values (default) if you won't declare field as wrapper & would eventually throw "Null value was assigned to a property of primitive type setter" Exception.

How to convert string to XML using C#

// using System.Xml;

String rawXml =
      @"<root>
          <person firstname=""Riley"" lastname=""Scott"" />
          <person firstname=""Thomas"" lastname=""Scott"" />
      </root>";

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(rawXml);

I think this should work.

What ports does RabbitMQ use?

PORT 4369: Erlang makes use of a Port Mapper Daemon (epmd) for resolution of node names in a cluster. Nodes must be able to reach each other and the port mapper daemon for clustering to work.

PORT 35197 set by inet_dist_listen_min/max Firewalls must permit traffic in this range to pass between clustered nodes

RabbitMQ Management console:

  • PORT 15672 for RabbitMQ version 3.x
  • PORT 55672 for RabbitMQ pre 3.x

PORT 5672 RabbitMQ main port.

For a cluster of nodes, they must be open to each other on 35197, 4369 and 5672.

For any servers that want to use the message queue, only 5672 is required.

Clear Cache in Android Application programmatically

Put this code in onStop() method of MainActivity

@Override
protected void onStop() {
    super.onStop();
    AppUtils.deleteCache(getApplicationContext());
}
public class AppUtils {
    public static void deleteCache(Context context) {
        try {
            File dir = context.getCacheDir();
            deleteDir(dir);
        } catch (Exception e) {}
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
            return dir.delete();
        } else if(dir!= null && dir.isFile()) {
            return dir.delete();
        } else {
            return false;
        }
    }
}

How do I avoid the "#DIV/0!" error in Google docs spreadsheet?

You can use an IF statement to check the referenced cell(s) and return one result for zero or blank, and otherwise return your formula result.

A simple example:

=IF(B1=0;"";A1/B1)

This would return an empty string if the divisor B1 is blank or zero; otherwise it returns the result of dividing A1 by B1.

In your case of running an average, you could check to see whether or not your data set has a value:

=IF(SUM(K23:M23)=0;"";AVERAGE(K23:M23))

If there is nothing entered, or only zeros, it returns an empty string; if one or more values are present, you get the average.

How to do associative array/hashing in JavaScript

Years ago, I implemented the following hashtable, which has had some features that have been missing to the Map class. However, that's no longer the case. Now it's possible to iterate over the entries of a Map, get an array of its keys or values or both (these operations are implemented copying to a newly allocated array, though — that's a waste of memory and its time complexity will always be as bad as O(n)), remove specific items given their key, and clear the whole map. Therefore, my hashtable implementation is only useful for compatibility purposes, though in this case it would be more appropriate to write a proper polyfill. I'd suggest to anyone who would use my hashtable implementation to change it so to make it become a polyfill for the Map class.

function Hashtable() {
    this._map = new Map();
    this._indexes = new Map();
    this._keys = [];
    this._values = [];
    this.put = function(key, value) {
        var newKey = !this.containsKey(key);
        this._map.set(key, value);
        if (newKey) {
            this._indexes.set(key, this.length);
            this._keys.push(key);
            this._values.push(value);
        }
    };
    this.remove = function(key) {
        if (!this.containsKey(key))
            return;
        this._map.delete(key);
        var index = this._indexes.get(key);
        this._indexes.delete(key);
        this._keys.splice(index, 1);
        this._values.splice(index, 1);
    };
    this.indexOfKey = function(key) {
        return this._indexes.get(key);
    };
    this.indexOfValue = function(value) {
        return this._values.indexOf(value) != -1;
    };
    this.get = function(key) {
        return this._map.get(key);
    };
    this.entryAt = function(index) {
        var item = {};
        Object.defineProperty(item, "key", {
            value: this.keys[index],
            writable: false
        });
        Object.defineProperty(item, "value", {
            value: this.values[index],
            writable: false
        });
        return item;
    };
    this.clear = function() {
        var length = this.length;
        for (var i = 0; i < length; i++) {
            var key = this.keys[i];
            this._map.delete(key);
            this._indexes.delete(key);
        }
        this._keys.splice(0, length);
    };
    this.containsKey = function(key) {
        return this._map.has(key);
    };
    this.containsValue = function(value) {
        return this._values.indexOf(value) != -1;
    };
    this.forEach = function(iterator) {
        for (var i = 0; i < this.length; i++)
            iterator(this.keys[i], this.values[i], i);
    };
    Object.defineProperty(this, "length", {
        get: function() {
            return this._keys.length;
        }
    });
    Object.defineProperty(this, "keys", {
        get: function() {
            return this._keys;
        }
    });
    Object.defineProperty(this, "values", {
        get: function() {
            return this._values;
        }
    });
    Object.defineProperty(this, "entries", {
        get: function() {
            var entries = new Array(this.length);
            for (var i = 0; i < entries.length; i++)
                entries[i] = this.entryAt(i);
            return entries;
        }
    });
}

Documentation of the class Hashtable

Methods:

  • get(key)
    Returns the value associated to the specified key.
    Parameters:
    key: The key from which to retrieve the value.

  • put(key, value)
    Associates the specified value to the specified key.
    Parameters:
    key: The key to which associate the value.
    value: The value to associate to the key.

  • remove(key)
    Removes the specified key, together with the value associated to it.
    Parameters:
    key: The key to remove.

  • clear()
    Clears the whole hashtable, by removing all its entries.

  • indexOfKey(key)
    Returns the index of the specified key, according to the order entries have been added.
    Parameters:
    key: The key of which to get the index.

  • indexOfValue(value)
    Returns the index of the specified value, according to the order entries have been added.
    Parameters:
    value: The value of which to get the index.
    Remarks:
    This information is retrieved using the indexOf() method of an array, so objects are compared by identity.

  • entryAt(index)
    Returns an object with a key and a value properties, representing the entry at the specified index.
    Parameters:
    index: The index of the entry to get.

  • containsKey(key)
    Returns whether the hashtable contains the specified key.
    Parameters: key: The key to look for.

  • containsValue(value)
    Returns whether the hashtable contains the specified value.
    Parameters:
    value: The value to look for.

  • forEach(iterator)
    Iterates through all the entries in the hashtable, calling specified iterator.
    Parameters:
    iterator: A method with three parameters, key, value and index, where index represents the index of the entry according to the order it's been added.

Properties:

  • length (Read-only)
    Gets the count of the entries in the hashtable.

  • keys (Read-only)
    Gets an array of all the keys in the hashtable.

  • values (Read-only)
    Gets an array of all the values in the hashtable.

  • entries (Read-only)
    Gets an array of all the entries in the hashtable. They're represented the same as the method entryAt() does.

Error: the entity type requires a primary key

This exception message doesn't mean it requires a primary key to be defined in your database, it means it requires a primary key to be defined in your class.

Although you've attempted to do so:

private Guid _id;
[Key]
public Guid ID
{
    get { return _id; }
}

This has no effect, as Entity Framework ignores read-only properties. It has to: when it retrieves a Fruits record from the database, it constructs a Fruit object, and then calls the property setters for each mapped property. That's never going to work for read-only properties.

You need Entity Framework to be able to set the value of ID. This means the property needs to have a setter.

ASP.NET file download from server

protected void DescargarArchivo(string strRuta, string strFile)
{
    FileInfo ObjArchivo = new System.IO.FileInfo(strRuta);
    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + strFile);
    Response.AddHeader("Content-Length", ObjArchivo.Length.ToString());
    Response.ContentType = "application/pdf";
    Response.WriteFile(ObjArchivo.FullName);
    Response.End();


}

How create table only using <div> tag and Css

In building a custom set of layout tags, I found another answer to this problem. Provided here is the custom set of tags and their CSS classes.

HTML

<layout-table>
   <layout-header> 
       <layout-column> 1 a</layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 </layout-column>
       <layout-column> 4 </layout-column>
   </layout-header>

   <layout-row> 
       <layout-column> a </layout-column>
       <layout-column> a 1</layout-column>
       <layout-column> a </layout-column>
       <layout-column> a </layout-column>
   </layout-row>

   <layout-footer> 
       <layout-column> 1 </layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 b</layout-column>
       <layout-column> 4 </layout-column>
   </layout-footer>
</layout-table>

CSS

layout-table
{
    display : table;
    clear : both;
    table-layout : fixed;
    width : 100%;
}

layout-table:unresolved
{
    color : red;
    border: 1px blue solid;
    empty-cells : show;
}

layout-header, layout-footer, layout-row 
{
    display : table-row;
    clear : both;   
    empty-cells : show;
    width : 100%;
}

layout-column 
{ 
    display : table-column;
    float : left;
    width : 25%;
    min-width : 25%;
    empty-cells : show;
    box-sizing: border-box;
    /* border: 1px solid white; */
    padding : 1px 1px 1px 1px;
}

layout-row:nth-child(even)
{ 
    background-color : lightblue;
}

layout-row:hover 
{ background-color: #f5f5f5 }

The key to getting empty cells and cells in general to be the right size, is Box-Sizing and Padding. Border will do the same thing as well, but creates a line in the row. Padding doesn't. And, while I haven't tried it, I think Margin will act the same way as Padding, in forcing and empty cell to be rendered properly.

How do I skip a header from CSV files in Spark?

You could load each file separately, filter them with file.zipWithIndex().filter(_._2 > 0) and then union all the file RDDs.

If the number of files is too large, the union could throw a StackOverflowExeption.

CSS Selector "(A or B) and C"?

I found success using the :is() selector:

*:is(.a, .b).c{...}

Android-java- How to sort a list of objects by a certain value within the object

I have a listview which shows the Information about the all clients I am sorting the clients name using this custom comparator class. They are having some extra lerret apart from english letters which i am managing with this setStrength(Collator.SECONDARY)

 public class CustomNameComparator implements Comparator<ClientInfo> {
        @Override

    public int compare(ClientInfo o1, ClientInfo o2) { 

        Locale locale=Locale.getDefault();
        Collator collator = Collator.getInstance(locale);
        collator.setStrength(Collator.SECONDARY);
        return collator.compare(o1.title, o2.title);

    }
}


PRIMARY strength: Typically, this is used to denote differences between base characters (for example, "a" < "b"). It is the strongest difference. For example, dictionaries are divided into different sections by base character. 
SECONDARY strength: Accents in the characters are considered secondary differences (for example, "as" < "às" < "at"). Other differences between letters can also be considered secondary differences, depending on the language. A secondary difference is ignored when there is a primary difference anywhere in the strings. 
TERTIARY strength: Upper and lower case differences in characters are distinguished at tertiary strength (for example, "ao" < "Ao" < "aò"). In addition, a variant of a letter differs from the base form on the tertiary strength (such as "A" and "?"). Another example is the difference between large and small Kana. A tertiary difference is ignored when there is a primary or secondary difference anywhere in the strings. 
IDENTICAL strength: When all other strengths are equal, the IDENTICAL strength is used as a tiebreaker. The Unicode code point values of the NFD form of each string are compared, just in case there is no difference. For example, Hebrew cantellation marks are only distinguished at this strength. This strength should be used sparingly, as only code point value differences between two strings are an extremely rare occurrence. Using this strength substantially decreases the performance for both comparison and collation key generation APIs. This strength also increases the size of the collation key. 

**Here is a another way to make a rule base sorting if u need it just sharing**

/*      String rules="< å,Å< ä,Ä< a,A< b,B< c,C< d,D< é< e,E< f,F< g,G< h,H< ï< i,I"+"< j,J< k,K< l,L< m,M< n,N< ö,Ö< o,O< p,P< q,Q< r,R"+"< s,S< t,T< ü< u,U< v,V< w,W< x,X< y,Y< z,Z";
        RuleBasedCollator rbc = null;
        try {
            rbc = new RuleBasedCollator(rules);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String myTitles[]={o1.title,o2.title};
        Collections.sort(Arrays.asList(myTitles), rbc);*/

How to access site through IP address when website is on a shared host?

You can access you website using your IP address and your cPanel username with ~ symbols. For Example: http://serverip/~cpusername like as https://xxx.xxx.xx.xx/~mohidul

How to find the path of Flutter SDK

How to create FLUTTER project in android studio in fedora:-

I have installed following:- 1 Android studio 2 Then do following:-

Start Android Studio. Open plugin preferences (Preferences > Plugins on macOS, File > Settings > Plugins on Windows & Linux). Select Marketplace, select the Flutter plugin and click Install. Click Yes when prompted to install the Dart plugin. Click Restart when prompted.

4:- Now create project by clicking new flutter project and do following:- * Choose Flutter Application from the list of configurations * Fill the name and other things * For flutter sdk click and install flutter sdk and specify the location of downloading and after downloading completion, choose that sdk path, this will load your FLutter sdk.

Rest do steps as per your need to create project

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

I have been able to solve this problem by calling $eval instead of $apply in places where I know that the $digest function will be running.

According to the docs, $apply basically does this:

function $apply(expr) {
  try {
    return $eval(expr);
  } catch (e) {
    $exceptionHandler(e);
  } finally {
    $root.$digest();
  }
}

In my case, an ng-click changes a variable within a scope, and a $watch on that variable changes other variables which have to be $applied. This last step causes the error "digest already in progress".

By replacing $apply with $eval inside the watch expression the scope variables get updated as expected.

Therefore, it appears that if digest is going to be running anyways because of some other change within Angular, $eval'ing is all you need to do.

Can I convert a C# string value to an escaped string literal

Code:

string someString1 = "\tHello\r\n\tWorld!\r\n";
string someString2 = @"\tHello\r\n\tWorld!\r\n";

Console.WriteLine(someString1);
Console.WriteLine(someString2);

Output:

    Hello
    World!

\tHello\r\n\tWorld!\r\n

Is this what you want?

How do I convert a list of ascii values to a string in python?

import array
def f7(list):
    return array.array('B', list).tostring()

from Python Patterns - An Optimization Anecdote

How to implement class constants?

Either use readOnly modifier with the constant one needs to declare or one might declare a constant outside the class and use it specifically only in the required class using get operator.

Angular JS POST request not sending JSON data

You can use FormData API https://developer.mozilla.org/en-US/docs/Web/API/FormData

var data = new FormData;
data.append('from', from);
data.append('to', to);

$http({
    url: '/path',
    method: 'POST',
    data: data,
    transformRequest: false,
    headers: { 'Content-Type': undefined }
})

This solution from http://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs

Programmatically scroll a UIScrollView

I'm amazed that this topic is 9 years old and the actual straightforward answer is not here!

What you're looking for is scrollRectToVisible(_:animated:).

Example:

extension SignUpView: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        scrollView.scrollRectToVisible(textField.frame, animated: true)
    }
}

What it does is exactly what you need, and it's far better than hacky contentOffset

This method scrolls the content view so that the area defined by rect is just visible inside the scroll view. If the area is already visible, the method does nothing.

From: https://developer.apple.com/documentation/uikit/uiscrollview/1619439-scrollrecttovisible

Android Gradle Could not reserve enough space for object heap

Solution for Android Studio 2.3.3 on MacOS 10.12.6

Start Android Studios with more heap memory:

export JAVA_OPTS="-Xms6144m -Xmx6144m -XX:NewSize=256m -XX:MaxNewSize=356m -XX:PermSize=256m -XX:MaxPermSize=356m"
open -a /Applications/Android\ Studio.app

Save Dataframe to csv directly to s3 Python

I found this can be done using client also and not just resource.

from io import StringIO
import boto3
s3 = boto3.client("s3",\
                  region_name=region_name,\
                  aws_access_key_id=aws_access_key_id,\
                  aws_secret_access_key=aws_secret_access_key)
csv_buf = StringIO()
df.to_csv(csv_buf, header=True, index=False)
csv_buf.seek(0)
s3.put_object(Bucket=bucket, Body=csv_buf.getvalue(), Key='path/test.csv')

How can I upload fresh code at github?

From Github guide: Getting your project to Github:(using Github desktop version)

Set up your project in GitHub Desktop

The easiest way to get your project into GitHub Desktop is to drag the folder which contains your project files onto the main application screen.

If you are dragging in an existing Git repository, you can skip ahead and push your code to GitHub.com.

If the folder isn’t a Git repository yet, GitHub Desktop will prompt you to turn it into a repository. Turning your project into a Git repository won’t delete or ruin the files in your folder—it will simply create some hidden files that allow Git to do its magic.

enter image description here

In Windows it looks like this:(GitHub desktop 3.0.5.2)

enter image description here

this is not the most geeky way but it works.

How can I convert a string to boolean in JavaScript?

One Liner

We just need to account for the "false" string since any other string (including "true") is already true.

function b(v){ return v==="false" ? false : !!v; }

Test

b(true)    //true
b('true')  //true
b(false)   //false
b('false') //false

A more exaustive version

function bool(v){ return v==="false" || v==="null" || v==="NaN" || v==="undefined" || v==="0" ? false : !!v; }

Test

bool(true)        //true
bool("true")      //true
bool(1)           //true
bool("1")         //true
bool("hello")     //true

bool(false)       //false
bool("false")     //false
bool(0)           //false
bool("0")         //false
bool(null)        //false
bool("null")      //false
bool(NaN)         //false
bool("NaN")       //false
bool(undefined)   //false
bool("undefined") //false
bool("")          //false

bool([])          //true
bool({})          //true
bool(alert)       //true
bool(window)      //true

Are there such things as variables within an Excel formula?

Now you can use the function LET to declare variables within Excel formulas. This function is available since Jun 2020 for Microsoft 365 users.

Given your example, the formula will be:

=LET(MyFunc,VLOOKUP(A1,B:B,1,0), IF(MyFunc > 10, MyFunc - 10, MyFunc ) )

The 1st argument is the variable name and the 2nd argument is the function or range. You can add more pairs of arguments variable, function/range.

After adding the variables, the last argument will be your formula of interest -- calling the variables you just created.

For more information, please access the Microsoft webpage here.

Any way to write a Windows .bat file to kill processes?

As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:

TSKILL processName

or

TSKILL PID

Have on mind that processName should not have the .exe suffix and is limited to 18 characters.

Another option is WMIC :

wmic Path win32_process Where "Caption Like 'MyProcess%.exe'" Call Terminate

wmic offer even more flexibility than taskkill with its SQL-like matchers .With wmic Path win32_process get you can see the available fileds you can filter (and % can be used as a wildcard).

Java 256-bit AES Password-Based Encryption

Consider using the Spring Security Crypto Module

The Spring Security Crypto module provides support for symmetric encryption, key generation, and password encoding. The code is distributed as part of the core module but has no dependencies on any other Spring Security (or Spring) code.

It's provides a simple abstraction for encryption and seems to match what's required here,

The "standard" encryption method is 256-bit AES using PKCS #5's PBKDF2 (Password-Based Key Derivation Function #2). This method requires Java 6. The password used to generate the SecretKey should be kept in a secure place and not be shared. The salt is used to prevent dictionary attacks against the key in the event your encrypted data is compromised. A 16-byte random initialization vector is also applied so each encrypted message is unique.

A look at the internals reveals a structure similar to erickson's answer.

As noted in the question, this also requires the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy (else you'll encounter InvalidKeyException: Illegal Key Size). It's downloadable for Java 6, Java 7 and Java 8.

Example usage

import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.security.crypto.keygen.KeyGenerators;

public class CryptoExample {
    public static void main(String[] args) {
        final String password = "I AM SHERLOCKED";  
        final String salt = KeyGenerators.string().generateKey();
        
        TextEncryptor encryptor = Encryptors.text(password, salt);      
        System.out.println("Salt: \"" + salt + "\"");
        
        String textToEncrypt = "*royal secrets*";
        System.out.println("Original text: \"" + textToEncrypt + "\"");
        
        String encryptedText = encryptor.encrypt(textToEncrypt);
        System.out.println("Encrypted text: \"" + encryptedText + "\"");
        
        // Could reuse encryptor but wanted to show reconstructing TextEncryptor
        TextEncryptor decryptor = Encryptors.text(password, salt);
        String decryptedText = decryptor.decrypt(encryptedText);
        System.out.println("Decrypted text: \"" + decryptedText + "\"");
        
        if(textToEncrypt.equals(decryptedText)) {
            System.out.println("Success: decrypted text matches");
        } else {
            System.out.println("Failed: decrypted text does not match");
        }       
    }
}

And sample output,

Salt: "feacbc02a3a697b0"
Original text: "*royal secrets*"
Encrypted text: "7c73c5a83fa580b5d6f8208768adc931ef3123291ac8bc335a1277a39d256d9a" 
Decrypted text: "*royal secrets*"
Success: decrypted text matches

printf and long double

From the printf manpage:

l (ell) A following integer conversion corresponds to a long int or unsigned long int argument, or a following n conversion corresponds to a pointer to a long int argument, or a following c conversion corresponds to a wint_t argument, or a following s conversion corresponds to a pointer to wchar_t argument.

and

L A following a, A, e, E, f, F, g, or G conversion corresponds to a long double argument. (C99 allows %LF, but SUSv2 does not.)

So, you want %Le , not %le

Edit: Some further investigation seems to indicate that Mingw uses the MSVC/win32 runtime(for stuff like printf) - which maps long double to double. So mixing a compiler (like gcc) that provides a native long double with a runtime that does not seems to .. be a mess.

MySQL default datetime through phpmyadmin

I don't think you can achieve that with mysql date. You have to use timestamp or try this approach..

CREATE TRIGGER table_OnInsert BEFORE INSERT ON `DB`.`table`
FOR EACH ROW SET NEW.dateColumn = IFNULL(NEW.dateColumn, NOW());

httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:88

With my centos 6.7 installation, not only did I have the problem starting httpd with root but also with xauth (getting /usr/bin/xauth: timeout in locking authority file /.Xauthority with underlying permission denied errors)

# setenforce 0

Fixed both issues.

Warning: A non-numeric value encountered

You can solve the problem without any new logic by just casting the thing into the number, which prevents the warning and is equivalent to the behavior in PHP 7.0 and below:

$sub_total += ((int)$item['quantity'] * (int)$product['price']);

(The answer from Daniel Schroeder is not equivalent because $sub_total would remain unset if non-numeric values are encountered. For example, if you print out $sub_total, you would get an empty string, which is probably wrong in an invoice. - by casting you make sure that $sub_total is an integer.)

CSS/HTML: What is the correct way to make text italic?

HTML italic text displays the text in italic format.

<i>HTML italic text example</i>

The emphasis and strong elements can both be used to increase the importance of certain words or sentences.

<p>This is <em>emphasized </em> text format <em>example</em></p>

The emphasis tag should be used when you want to emphasize a point in your text and not necessarily when you want to italicize that text.

See this guide for more: HTML Text Formatting

How to draw lines in Java

You can use the getGraphics method of the component on which you would like to draw. This in turn should allow you to draw lines and make other things which are available through the Graphics class

SQL JOIN vs IN performance?

The optimizer should be smart enough to give you the same result either way for normal queries. Check the execution plan and they should give you the same thing. If they don't, I would normally consider the JOIN to be faster. All systems are different, though, so you should profile the code on your system to be sure.

Disable beep of Linux Bash on Windows 10

You need add following lines to bash and vim config,

1) Turn off bell for bash

vi ~/.inputrc
set bell-style none

2) Turn off bell for vi

vi ~/.vimrc
set visualbell
set t_vb=

Setting the visual bell turns off the audio bell and clearing the visual bell length deactivates flashing.

Apache is downloading php files instead of displaying them

this solved the problem for me (I have php7 installed):

sudo apt-get install libapache2-mod-php7.0

sudo service apache2 restart

How to show PIL images on the screen?

Maybe you can use matplotlib for this, you can also plot normal images with it. If you call show() the image pops up in a window. Take a look at this:

http://matplotlib.org/users/image_tutorial.html

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

The only thing that worked for me was creating a new application in the IIS, mapping it to exactly the same physical path, and changing only the authentication to be Anonymous.

What happens if you mount to a non-empty mount point with fuse?

You need to make sure that the files on the device mounted by fuse will not have the same paths and file names as files which already existing in the nonempty mountpoint. Otherwise this would lead to confusion. If you are sure, pass -o nonempty to the mount command.

You can try what is happening using the following commands.. (Linux rocks!) .. without destroying anything..

// create 10 MB file 
dd if=/dev/zero of=partition bs=1024 count=10240

// create loopdevice from that file
sudo losetup /dev/loop0 ./partition

// create  filesystem on it
sudo e2mkfs.ext3 /dev/loop0

// mount the partition to temporary folder and create a file
mkdir test
sudo mount -o loop /dev/loop0 test
echo "bar" | sudo tee test/foo

# unmount the device
sudo umount /dev/loop0

# create the file again
echo "bar2" > test/foo

# now mount the device (having file with same name on it) 
# and see what happens
sudo mount -o loop /dev/loop0 test

How to install JSTL? The absolute uri: http://java.sun.com/jstl/core cannot be resolved

I just wanted to add the fix I found for this issue. I'm not sure why this worked. I had the correct version of jstl (1.2) and also the correct version of servlet-api (2.5)

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

I also had the correct address in my page as suggested in this thread, which is

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

What fixed this issue for me was removing the scope tag from my xml file in the pom for my jstl 1.2 dependency. Again not sure why that fixed it but just in case someone is doing the spring with JPA and Hibernate tutorial on pluralsight and has their pom setup this way, try removing the scope tag and see if that fixes it. Like I said it worked for me.

How to handle onchange event on input type=file in jQuery?

It should work fine, are you wrapping the code in a $(document).ready() call? If not use that or use live i.e.

$('#fileupload1').live('change', function(){ 
    alert("hola");
});

Here is a jsFiddle of this working against jQuery 1.4.4

Get hostname of current request in node.js Express

If you need a fully qualified domain name and have no HTTP request, on Linux, you could use:

var child_process = require("child_process");

child_process.exec("hostname -f", function(err, stdout, stderr) {
  var hostname = stdout.trim();
});

Python Sets vs Lists

Sets are faster, morover you get more functions with sets, such as lets say you have two sets :

set1 = {"Harry Potter", "James Bond", "Iron Man"}
set2 = {"Captain America", "Black Widow", "Hulk", "Harry Potter", "James Bond"}

We can easily join two sets:

set3 = set1.union(set2)

Find out what is common in both:

set3 = set1.intersection(set2)

Find out what is different in both:

set3 = set1.difference(set2)

And much more! Just try them out, they are fun! Moreover if you have to work on the different values within 2 list or common values within 2 lists, I prefer to convert your lists to sets, and many programmers do in that way. Hope it helps you :-)

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

Creating and throwing new exception

You can throw your own custom errors by extending the Exception class.

class CustomException : Exception {
    [string] $additionalData

    CustomException($Message, $additionalData) : base($Message) {
        $this.additionalData = $additionalData
    }
}

try {
    throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
    # NOTE: To access your custom exception you must use $_.Exception
    Write-Output $_.Exception.additionalData

    # This will produce the error message: Didn't catch it the second time
    throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}

Using git commit -a with vim

See this thread for an explanation: VIM for Windows - What do I type to save and exit from a file?

As I wrote there: to learn Vimming, you could use one of the quick reference cards:

Also note How can I set up an editor to work with Git on Windows? if you're not comfortable in using Vim but want to use another editor for your commit messages.

If your commit message is not too long, you could also type

git commit -a -m "your message here"

How to Get a Sublist in C#

You want List::GetRange(firstIndex, count). See http://msdn.microsoft.com/en-us/library/21k0e39c.aspx

// I have a List called list
List sublist = list.GetRange(5, 5); // (gets elements 5,6,7,8,9)
List anotherSublist = list.GetRange(0, 4); // gets elements 0,1,2,3)

Is that what you're after?

If you're looking to delete the sublist items from the original list, you can then do:

// list is our original list
// sublist is our (newly created) sublist built from GetRange()
foreach (Type t in sublist)
{
    list.Remove(t);
}

Is nested function a good approach when required by only one function?

I found this question because I wanted to pose a question why there is a performance impact if one uses nested functions. I ran tests for the following functions using Python 3.2.5 on a Windows Notebook with a Quad Core 2.5 GHz Intel i5-2530M processor

def square0(x):
    return x*x

def square1(x):
    def dummy(y):
        return y*y
    return x*x

def square2(x):
    def dummy1(y):
        return y*y
    def dummy2(y):
        return y*y
    return x*x

def square5(x):
    def dummy1(y):
        return y*y
    def dummy2(y):
        return y*y
    def dummy3(y):
        return y*y
    def dummy4(y):
        return y*y
    def dummy5(y):
        return y*y
    return x*x

I measured the following 20 times, also for square1, square2, and square5:

s=0
for i in range(10**6):
    s+=square0(i)

and got the following results

>>> 
m = mean, s = standard deviation, m0 = mean of first testcase
[m-3s,m+3s] is a 0.997 confidence interval if normal distributed

square? m     s       m/m0  [m-3s ,m+3s ]
square0 0.387 0.01515 1.000 [0.342,0.433]
square1 0.460 0.01422 1.188 [0.417,0.503]
square2 0.552 0.01803 1.425 [0.498,0.606]
square5 0.766 0.01654 1.979 [0.717,0.816]
>>> 

square0 has no nested function, square1 has one nested function, square2 has two nested functions and square5 has five nested functions. The nested functions are only declared but not called.

So if you have defined 5 nested funtions in a function that you don't call then the execution time of the function is twice of the function without a nested function. I think should be cautious when using nested functions.

The Python file for the whole test that generates this output can be found at ideone.

Load content of a div on another page

You just need to add a jquery selector after the url.

See: http://api.jquery.com/load/

Example straight from the API:

$('#result').load('ajax/test.html #container');

So what that does is it loads the #container element from the specified url.

C++ Array of pointers: delete or delete []?

For new you should use delete. For new[] use delete[]. Your second variant is correct.

How to automatically redirect HTTP to HTTPS on Apache servers?

This code work for me.

# ----------port 80----------
RewriteEngine on
# redirect http non-www to https www
RewriteCond %{HTTPS} off
RewriteCond %{SERVER_NAME} =example.com
RewriteRule ^ https://www.%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]

# redirect http www to https www
RewriteCond %{HTTPS} off
RewriteCond %{SERVER_NAME} =www.example.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]

# ----------port 443----------
RewriteEngine on
# redirect https non-www to https www
RewriteCond %{SERVER_NAME} !^www\.(.*)$ [NC]
RewriteRule ^ https://www.%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]

CORS: credentials mode is 'include'

The issue stems from your Angular code:

When withCredentials is set to true, it is trying to send credentials or cookies along with the request. As that means another origin is potentially trying to do authenticated requests, the wildcard ("*") is not permitted as the "Access-Control-Allow-Origin" header.

You would have to explicitly respond with the origin that made the request in the "Access-Control-Allow-Origin" header to make this work.

I would recommend to explicitly whitelist the origins that you want to allow to make authenticated requests, because simply responding with the origin from the request means that any given website can make authenticated calls to your backend if the user happens to have a valid session.

I explain this stuff in this article I wrote a while back.

So you can either set withCredentials to false or implement an origin whitelist and respond to CORS requests with a valid origin whenever credentials are involved

Compare two List<T> objects for equality, ignoring order

This worked for me:
If you are comparing two lists of objects depend upon single entity like ID, and you want a third list which matches that condition, then you can do the following:

var list3 = List1.Where(n => !List2.select(n1 => n1.Id).Contains(n.Id));

Refer: MSDN - C# Compare Two lists of objects

When to use dynamic vs. static libraries

If the library is static, then at link time the code is linked in with your executable. This makes your executable larger (than if you went the dynamic route).

If the library is dynamic then at link time references to the required methods are built in to your executable. This means that you have to ship your executable and the dynamic library. You also ought to consider whether shared access to the code in the library is safe, preferred load address among other stuff.

If you can live with the static library, go with the static library.

Is it possible to specify proxy credentials in your web.config?

Yes, it is possible to specify your own credentials without modifying the current code. It requires a small piece of code from your part though.

Create an assembly called SomeAssembly.dll with this class :

namespace SomeNameSpace
{
    public class MyProxy : IWebProxy
    {
        public ICredentials Credentials
        {
            get { return new NetworkCredential("user", "password"); }
            //or get { return new NetworkCredential("user", "password","domain"); }
            set { }
        }

        public Uri GetProxy(Uri destination)
        {
            return new Uri("http://my.proxy:8080");
        }

        public bool IsBypassed(Uri host)
        {
            return false;
        }
    }
}

Add this to your config file :

<defaultProxy enabled="true" useDefaultCredentials="false">
  <module type = "SomeNameSpace.MyProxy, SomeAssembly" />
</defaultProxy>

This "injects" a new proxy in the list, and because there are no default credentials, the WebRequest class will call your code first and request your own credentials. You will need to place the assemble SomeAssembly in the bin directory of your CMS application.

This is a somehow static code, and to get all strings like the user, password and URL, you might either need to implement your own ConfigurationSection, or add some information in the AppSettings, which is far more easier.

How to automatically allow blocked content in IE?

Alternatively, as long as permissions are not given, the good old <noscript> tags works. You can cover the page in css and tell them what's wrong, ... without using javascript ofcourse.

Failed to load AppCompat ActionBar with unknown error in android studio

Method 1:

Locate /res/values/styles.xml

Change

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

To

<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">

Method 2:

Modify template file(locate: android-studio/plugins/android/lib/templates/gradle-projects/NewAndroidModule/root/res/values/styles.xml.ftl)

Change

backwardsCompatibility!true>Theme.AppCompat<#else><#if

To

backwardsCompatibility!true>Base.Theme.AppCompat<#else><#if

Watch Solution On YouTube

Solution

A Parser-blocking, cross-origin script is invoked via document.write - how to circumvent it?

@niutech I was having the similar issue which is caused by Rocket Loader Module by Cloudflare. Just disable it for the website and it will sort out all your related issues.

Where are Docker images stored on the host machine?

If you keep in mind that Docker is still running in a VM, the system paths are relative to the VM and not from the Mac Osx system. As it says all is contained in a VM file :

/Users/MyUserName/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/Docker.qcow2

Try to run Alpine image with this volume option and the ls command you are able to list the VM host:

docker run --rm -it -v /:/vm-root alpine:edge ls -l /vm-root

After this just try :

docker run --rm -it -v /:/vm-root alpine:edge ls -l /vm-root/var/lib/docker

Now, you are able to list the docker folder from the VM host

Is there a GUI design app for the Tkinter / grid geometry?

Apart from the options already given in other answers, there's a current more active, recent and open-source project called pygubu.

This is the first description by the author taken from the github repository:

Pygubu is a RAD tool to enable quick & easy development of user interfaces for the python tkinter module.

The user interfaces designed are saved as XML, and by using the pygubu builder these can be loaded by applications dynamically as needed. Pygubu is inspired by Glade.


Pygubu hello world program is an introductory video explaining how to create a first project using Pygubu.

The following in an image of interface of the last version of pygubu designer on a OS X Yosemite 10.10.2:

enter image description here

I would definitely give it a try, and contribute to its development.

Find all zero-byte files in directory and subdirectories

To print the names of all files in and below $dir of size 0:

find "$dir" -size 0

Note that not all implementations of find will produce output by default, so you may need to do:

find "$dir" -size 0 -print

Two comments on the final loop in the question:

Rather than iterating over every other word in a string and seeing if the alternate values are zero, you can partially eliminate the issue you're having with whitespace by iterating over lines. eg:

printf '1 f1\n0 f 2\n10 f3\n' | while read size path; do
    test "$size" -eq 0 && echo "$path"; done

Note that this will fail in your case if any of the paths output by ls contain newlines, and this reinforces 2 points: don't parse ls, and have a sane naming policy that doesn't allow whitespace in paths.

Secondly, to output the data from the loop, there is no need to store the output in a variable just to echo it. If you simply let the loop write its output to stdout, you accomplish the same thing but avoid storing it.

Google API for location, based on user IP address

It looks like Google actively frowns on using IP-to-location mapping:

https://developers.google.com/maps/articles/geolocation?hl=en

That article encourages using the W3C geolocation API. I was a little skeptical, but it looks like almost every major browser already supports the geolocation API:

http://caniuse.com/geolocation

How to make multiple divs display in one line but still retain width?

You can use display:inline-block.

This property allows a DOM element to have all the attributes of a block element, but keeping it inline. There's some drawbacks, but most of the time it's good enough. Why it's good and why it may not work for you.

EDIT: The only modern browser that has some problems with it is IE7. See Quirksmode.org

CSS change button style after click

It is possible to do with CSS only by selecting active and focus pseudo element of the button.

button:active{
    background:olive;
}

button:focus{
    background:olive;
}

See codepen: http://codepen.io/fennefoss/pen/Bpqdqx

You could also write a simple jQuery click function which changes the background color.

HTML:

<button class="js-click">Click me!</button>

CSS:

button {
  background: none;
}

JavaScript:

  $( ".js-click" ).click(function() {
    $( ".js-click" ).css('background', 'green');
  });

Check out this codepen: http://codepen.io/fennefoss/pen/pRxrVG

Typescript interface default values

It's best practice in case you have many parameters to let the user insert only few parameters and not in specific order.

For example, bad practice:

foo(a, b, c, d, e)

Good practice:

foo({d=3})

The way to do it is through interfaces. You need to define the parameter as an interface like:

interface Arguments {
    a?;
    b?; 
    c?;
    d?;
    e?;
}

And define the function like:

foo(arguments: Arguments)

Now interfaces variables can't get default values, so how do we define default values?

Simple, we define default value for the whole interface:

foo({
        a,
        b=1,
        c=99,
        d=88,
        e                    
    }: Arguments)

Now if the user pass:

foo({d=3})

The actual parameters will be:

{
    a,
    b=1,
    c=99,
    d=3,
    e                    
}

I understood it from the following link so big credit :) https://medium.com/better-programming/named-parameters-in-typescript-e32c763d2b2e

How can I clear the content of a file?

Use FileMode.Truncate everytime you create the file. Also place the File.Create inside a try catch.

TypeError: Cannot read property 'then' of undefined

TypeError: Cannot read property 'then' of undefined when calling a Django service using AngularJS.

If you are calling a Python service, the code will look like below:

this.updateTalentSupplier=function(supplierObj){
  var promise = $http({
    method: 'POST',
      url: bbConfig.BWS+'updateTalentSupplier/',
      data:supplierObj,
      withCredentials: false,
      contentType:'application/json',
      dataType:'json'
    });
    return promise; //Promise is returned 
}

We are using MongoDB as the database(I know it doesn't matter. But if someone is searching with MongoDB + Python (Django) + AngularJS the result should come.

Set Font Color, Font Face and Font Size in PHPExcel

I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray() According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.

This will work for you:

$phpExcel = new PHPExcel();

$styleArray = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));

$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);

To apply font style to complete excel document:

 $styleArray = array(
   'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));      
 $phpExcel->getDefaultStyle()
    ->applyFromArray($styleArray);

How to start and stop android service from a adb shell?

I can start service through

am startservice com.xxx/.service.XXXService

but i don't know how to stop it yet.

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

The easiest is to use the queryout option and use union all to link a column list with the actual table content

    bcp "select 'col1', 'col2',... union all select * from myschema.dbo.myTableout" queryout myTable.csv /SmyServer01 /c /t, -T

An example:

create table Question1355876
(id int, name varchar(10), someinfo numeric)

insert into Question1355876
values (1, 'a', 123.12)
     , (2, 'b', 456.78)
     , (3, 'c', 901.12)
     , (4, 'd', 353.76)

This query will return the information with the headers as first row (note the casts of the numeric values):

select 'col1', 'col2', 'col3'
union all
select cast(id as varchar(10)), name, cast(someinfo as varchar(28))
from Question1355876

The bcp command will be:

bcp "select 'col1', 'col2', 'col3' union all select cast(id as varchar(10)), name, cast(someinfo as varchar(28)) from Question1355876" queryout myTable.csv /SmyServer01 /c /t, -T

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

How to retrieve the current value of an oracle sequence without increment it?

My original reply was factually incorrect and I'm glad it was removed. The code below will work under the following conditions a) you know that nobody else modified the sequence b) the sequence was modified by your session. In my case, I encountered a similar issue where I was calling a procedure which modified a value and I'm confident the assumption is true.

SELECT mysequence.CURRVAL INTO v_myvariable FROM DUAL;

Sadly, if you didn't modify the sequence in your session, I believe others are correct in stating that the NEXTVAL is the only way to go.

How do I connect to a MySQL Database in Python?

first install the driver

pip install MySQL-python   

Then a basic code goes like this:

#!/usr/bin/python
import MySQLdb

try:
    db = MySQLdb.connect(host="localhost",      # db server, can be a remote one 
                     db="mydb"                  # database
                     user="mydb",               # username
                     passwd="mydb123",          # password for this username
                     )        

    # Create a Cursor object
    cur = db.cursor()

    # Create a query string. It can contain variables
    query_string = "SELECT * FROM MY_TABLE"

    # Execute the query
    cur.execute(query_string)

    # Get all the rows present the database
    for each_row in cur.fetchall():
        print each_row

    # Close the connection
    db.close()
except Exception, e:
    print 'Error ', e 

Can I install/update WordPress plugins without providing FTP access?

I also recommend the SSH SFTP Updater Support plugin. Just solved all my problems too...especially in regards to getting plugins to delete through the admin. Just install it in the usual way, and the next time you're prompted by WordPress for FTP details, there'll be extra fields for you to copy/paste your private SSH key or upload your PEM file.

Only problem I have is in getting it to remember the key (tried both methods). Don't like the idea of having to find and enter it every time I need to delete a plugin. But at least it's a solid fix for now.

Modify request parameter with servlet filter

You can use Regular Expression for Sanitization. Inside filter before calling chain.doFilter(request, response) method, call this code. Here is Sample Code:

for (Enumeration en = request.getParameterNames(); en.hasMoreElements(); ) {
String name = (String)en.nextElement();
String values[] = request.getParameterValues(name);
int n = values.length;
    for(int i=0; i < n; i++) {
     values[i] = values[i].replaceAll("[^\\dA-Za-z ]","").replaceAll("\\s+","+").trim();   
    }
}

LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria

I use SingleOrDefault in situations where my logic dictates that the will be either zero or one results. If there are more, it's an error situation, which is helpful.

How to resolve "Could not find schema information for the element/attribute <xxx>"?

An XSD is included with EntLib 5, and is installed in the Visual Studio schema directory. In my case, it could be found at:

"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Xml\Schemas\EnterpriseLibrary.Configuration.xsd"

CONTEXT

  • Visual Studio 2010
  • Enterprise Library 5

STEPS TO REMOVE THE WARNINGS

  1. open app.config in your Visual Studio project
  2. right click in the XML Document editor, select "Properties"
  3. add the fully qualified path to the "EnterpriseLibrary.Configuration.xsd"

ASIDE

It is worth repeating that these "Error List" "Messages" ("Could not find schema information for the element") are only visible when you open the app.config file. If you "Close All Documents" and compile... no messages will be reported.

Drop all tables whose names begin with a certain string

I saw this post when I was looking for mysql statement to drop all WordPress tables based on @Xenph Yan here is what I did eventually:

SELECT CONCAT(  'DROP TABLE `', TABLE_NAME,  '`;' ) AS query
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE  'wp_%'

this will give you the set of drop queries for all tables begins with wp_

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

You probably have a forward declaration of the class, but haven't included the header:

#include <sstream>

//...
QString Stats_Manager::convertInt(int num)
{
    std::stringstream ss;   // <-- also note namespace qualification
    ss << num;
    return ss.str();
}

minimum double value in C/C++

Are you looking for actual infinity or the minimal finite value? If the former, use

-numeric_limits<double>::infinity()

which only works if

numeric_limits<double>::has_infinity

Otherwise, you should use

numeric_limits<double>::lowest()

which was introduces in C++11.

If lowest() is not available, you can fall back to

-numeric_limits<double>::max()

which may differ from lowest() in principle, but normally doesn't in practice.

Babel 6 regeneratorRuntime is not defined

Babel 7 Users

I had some trouble getting around this since most information was for prior babel versions. For Babel 7, install these two dependencies:

npm install --save @babel/runtime 
npm install --save-dev @babel/plugin-transform-runtime

And, in .babelrc, add:

{
    "presets": ["@babel/preset-env"],
    "plugins": [
        ["@babel/transform-runtime"]
    ]
}

Intersection and union of ArrayLists in Java

I was also working on the similar situation and reached here searching for help. Ended up finding my own solution for Arrays. ArrayList AbsentDates = new ArrayList(); // Will Store Array1-Array2

Note : Posting this if it can help someone reaching this page for help.

ArrayList<String> AbsentDates = new ArrayList<String>();//This Array will store difference
      public void AbsentDays() {
            findDates("April", "2017");//Array one with dates in Month April 2017
            findPresentDays();//Array two carrying some dates which are subset of Dates in Month April 2017

            for (int i = 0; i < Dates.size(); i++) {

                for (int j = 0; j < PresentDates.size(); j++) {

                    if (Dates.get(i).equals(PresentDates.get(j))) {

                        Dates.remove(i);
                    }               

                }              
                AbsentDates = Dates;   
            }
            System.out.println(AbsentDates );
        }

Why is setTimeout(fn, 0) sometimes useful?

Some other cases where setTimeout is useful:

You want to break a long-running loop or calculation into smaller components so that the browser doesn't appear to 'freeze' or say "Script on page is busy".

You want to disable a form submit button when clicked, but if you disable the button in the onClick handler the form will not be submitted. setTimeout with a time of zero does the trick, allowing the event to end, the form to begin submitting, then your button can be disabled.

How to do a background for a label will be without color?

You are right. but here is the simplest way for making the back color of the label transparent In the properties window of that label select Web.. In Web select Transparent :)

python: How do I know what type of exception occurred?

Use the below for both Exception type and Exception text

import sys
print(str(sys.exc_info()[0]).split(' ')[1].strip('>').strip("'")+"-"+(str(sys.exc_info()[1])))

if you want only exception type: Use -->

import sys
print(str(sys.exc_info()[0]).split(' ')[1].strip('>').strip("'"))

Thanks Rajeshwar

Tool to convert java to c# code

For your reference:

Note: I had no experience on them.

REST vs JSON-RPC?

Great answers - just wanted to clarify on a some of the comments. JSON-RPC is quick and easy to consume, but as mentioned resources and parameters are tightly coupled and it tends to rely on verbs (api/deleteUser, api/addUser) using GET/ POST where-as REST provides loosely coupled resources (api/users) that in a HTTP REST API relies on several HTTP methods (GET, POST, PUT, PATCH, DELETE). REST is slightly harder for inexperienced developers to implement, but the style has become fairly common place now and it provides much more flexibility in the long-run (giving your API a longer life).

Along with not having tightly coupled resources, REST also allows you to avoid being committed to a single content-type- this means if your client needs to receive the data in XML, or JSON, or even YAML - if built into your system you could return any of those using the content-type/ accept headers.

This lets you keep your API flexible enough to support new content types OR client requirements.

But what truly separates REST from JSON-RPC is that it follows a series of carefully thought out constraints- ensuring architectural flexibility. These constraints include ensuring that the client and server are able to evolve independently of each other (you can make changes without messing up your client's application), the calls are stateless (state is represented through hypermedia), a uniform interface is provided for interactions, the API is developed on a layered system, and the response is cacheable by the client. There's also an optional constraint for providing code on demand.

However, with all of this said - MOST APIs are not RESTful (according to Fielding) as they do not incorporate hypermedia (embedded hypertext links in the response that help navigate the API). Most APIs you will find out there are REST-like in that they follow most of the concepts of REST, but ignore this constraint. However, more and more APIs are implementing this and it is becoming more of a main-stream practice.

This also gives you some flexibility as hypermedia driven APIs (such as Stormpath) direct the client to the URIs (meaning if something changes, in certain cases you can modify the URI without negative impact), where-as with RPC URIs are required to be static. With RPC, you will also need to extensively document these different URIs and explain how they work in relation to each other.

In general, I would say REST is the way to go if you want to build an extensible, flexible API that will be long-lived. For that reason, I would say it's the route to go 99% of the time.

Good luck, Mike

How to convert integer to decimal in SQL Server query?

SELECT CAST(height AS DECIMAL(18,0)) / 10

Edit: How this works under the hood?

The result type is the same as the type of both arguments, or, if they are different, it is determined by the data type precedence table. You can therefore cast either argument to something non-integral.

Now DECIMAL(18,0), or you could equivalently write just DECIMAL, is still a kind of integer type, because that default scale of 0 means "no digits to the right of the decimal point". So a cast to it might in different circumstances work well for rounding to integers - the opposite of what we are trying to accomplish.

However, DECIMALs have their own rules for everything. They are generally non-integers, but always exact numerics. The result type of the DECIMAL division that we forced to occur is determined specially to be, in our case, DECIMAL(29,11). The result of the division will therefore be rounded to 11 places which is no concern for division by 10, but the rounding becomes observable when dividing by 3. You can control the amount of rounding by manipulating the scale of the left hand operand. You can also round more, but not less, by placing another ROUND or CAST operation around the whole expression.

Identical mechanics governs the simpler and nicer solution in the accepted answer:

  SELECT height / 10.0

In this case, the type of the divisor is DECIMAL(3,1) and the type of the result is DECIMAL(17,6). Try dividing by 3 and observe the difference in rounding.

If you just hate all this talk of precisions and scales, and just want SQL server to perform all calculations in good old double precision floating point arithmetics from some point on, you can force that, too:

SELECT height / CAST(10 AS FLOAT(53))

or equivalently just

SELECT height / CAST (10 AS FLOAT)

How to split large text file in windows?

Of course there is! Win CMD can do a lot more than just split text files :)

Split a text file into separate files of 'max' lines each:

Split text file (max lines each):
: Initialize
set input=file.txt
set max=10000

set /a line=1 >nul
set /a file=1 >nul
set out=!file!_%input%
set /a max+=1 >nul

echo Number of lines in %input%:
find /c /v "" < %input%

: Split file
for /f "tokens=* delims=[" %i in ('type "%input%" ^| find /v /n ""') do (

if !line!==%max% (
set /a line=1 >nul
set /a file+=1 >nul
set out=!file!_%input%
echo Writing file: !out!
)

REM Write next file
set a=%i
set a=!a:*]=]!
echo:!a:~1!>>out!
set /a line+=1 >nul
)

If above code hangs or crashes, this example code splits files faster (by writing data to intermediate files instead of keeping everything in memory):

eg. To split a file with 7,600 lines into smaller files of maximum 3000 lines.

  1. Generate regexp string/pattern files with set command to be fed to /g flag of findstr

list1.txt

\[[0-9]\]
\[[0-9][0-9]\]
\[[0-9][0-9][0-9]\]
\[[0-2][0-9][0-9][0-9]\]

list2.txt

\[[3-5][0-9][0-9][0-9]\]

list3.txt

\[[6-9][0-9][0-9][0-9]\]

  1. Split the file into smaller files:
type "%input%" | find /v /n "" | findstr /b /r /g:list1.txt > file1.txt
type "%input%" | find /v /n "" | findstr /b /r /g:list2.txt > file2.txt
type "%input%" | find /v /n "" | findstr /b /r /g:list3.txt > file3.txt
  1. remove prefixed line numbers for each file split:
    eg. for the 1st file:
for /f "tokens=* delims=[" %i in ('type "%cd%\file1.txt"') do (
set a=%i
set a=!a:*]=]!
echo:!a:~1!>>file_1.txt)

Notes:
Works with leading whitespace, blank lines & whitespace lines.

Tested on Win 10 x64 CMD, on 4.4GB text file, 5651982 lines.

How do I see the current encoding of a file in Sublime Text?

Another option in case you don't wanna use a plugin:

Ctrl+` or

View -> Show Console

type on the console the following command:

view.encoding()

In case you want to something more intrusive, there's a option to create an shortcut that executes the following command:

sublime.message_dialog(view.encoding())

What is the "hasClass" function with plain JavaScript?

Simply use classList.contains():

if (document.body.classList.contains('thatClass')) {
    // do some stuff
}

Other uses of classList:

document.body.classList.add('thisClass');
// $('body').addClass('thisClass');

document.body.classList.remove('thatClass');
// $('body').removeClass('thatClass');

document.body.classList.toggle('anotherClass');
// $('body').toggleClass('anotherClass');

Browser Support:

  • Chrome 8.0
  • Firefox 3.6
  • IE 10
  • Opera 11.50
  • Safari 5.1

classList Browser Support

Mockito verify order / sequence of method calls

InOrder helps you to do that.

ServiceClassA firstMock = mock(ServiceClassA.class);
ServiceClassB secondMock = mock(ServiceClassB.class);

Mockito.doNothing().when(firstMock).methodOne();   
Mockito.doNothing().when(secondMock).methodTwo();  

//create inOrder object passing any mocks that need to be verified in order
InOrder inOrder = inOrder(firstMock, secondMock);

//following will make sure that firstMock was called before secondMock
inOrder.verify(firstMock).methodOne();
inOrder.verify(secondMock).methodTwo();

Relational Database Design Patterns?

Your question is a bit vague, but I suppose UPSERT could be considered a design pattern. For languages that don't implement MERGE, a number of alternatives to solve the problem (if a suitable rows exists, UPDATE; else INSERT) exist.

'profile name is not valid' error when executing the sp_send_dbmail command

Did you enable the profile for SQL Server Agent? This a common step that is missed when creating Email profiles in DatabaseMail.

Steps:

  • Right-click on SQL Server Agent in Object Explorer (SSMS)
  • Click on Properties
  • Click on the Alert System tab in the left-hand navigation
  • Enable the mail profile
  • Set Mail System and Mail Profile
  • Click OK
  • Restart SQL Server Agent

Difference between Subquery and Correlated Subquery

when it comes to subquery and co-related query both have inner query and outer query the only difference is in subquery the inner query doesn't depend on outer query, whereas in co-related inner query depends on outer.

Center a DIV horizontally and vertically

The legitimate way to do that irrespective of size of the div for any browser size is :

   div{
    margin:auto;
    height: 200px;
    width: 200px;
    position:fixed;
    top:0;
    bottom:0;
    left:0;
    right:0;
    background:red;
   }

Live Code

Round integers to the nearest 10

if you want the algebric form and still use round for it it's hard to get simpler than:

interval = 5
n = 4
print(round(n/interval))*interval

How to set array length in c# dynamically

InputProperty[] ip = new InputProperty[nvPairs.Length]; 

Or, you can use a list like so:

List<InputProperty> list = new List<InputProperty>();
InputProperty ip = new (..);
list.Add(ip);
update.items = list.ToArray();

Another thing I'd like to point out, in C# you can delcare your int variable use in a for loop right inside the loop:

for(int i = 0; i<nvPairs.Length;i++
{
.
.
}

And just because I'm in the mood, here's a cleaner way to do this method IMO:

private Update BuildMetaData(MetaData[] nvPairs)
{
        Update update = new Update();
        var ip = new List<InputProperty>();

        foreach(var nvPair in nvPairs)
        {
            if (nvPair == null) break;
            var inputProp = new InputProperty
            {
               Name = "udf:" + nvPair.Name,
               Val = nvPair.Value
            };
            ip.Add(inputProp);
        }
        update.Items = ip.ToArray();
        return update;
}

How to provide password to a command that prompts for one in bash?

How to use autoexpect to pipe a password into a command:

These steps are illustrated with an Ubuntu 12.10 desktop. The exact commands for your distribution may be slightly different.

This is dangerous because you risk exposing whatever password you use to anyone who can read the autoexpect script file.

DO NOT expose your root password or power user passwords by piping them through expect like this. Root kits WILL find this in an instant and your box is owned.

EXPECT spawns a process, reads text that comes in then sends text predefined in the script file.

  1. Make sure you have expect and autoexpect installed:

    sudo apt-get install expect
    sudo apt-get install expect-dev
    
  2. Read up on it:

    man expect
    man autoexpect
    
  3. Go to your home directory:

    cd /home/el
    
  4. User el cannot chown a file to root and must enter a password:

    touch testfile.txt
    sudo chown root:root testfile.txt 
       [enter password to authorize the changing of the owner]
    
  5. This is the password entry we want to automate. Restart the terminal to ensure that sudo asks us for the password again. Go to /home/el again and do this:

    touch myfile.txt
    
    autoexpect -f my_test_expect.exp sudo chown root:root myfile.txt
    
        [enter password which authorizes the chown to root]
    
    autoexpect done, file is my_test_expect.exp
    
  6. You have created my_test_expect.exp file. Your super secret password is stored plaintext in this file. This should make you VERY uncomfortable. Mitigate some discomfort by restricting permissions and ownership as much as possible:

    sudo chown el my_test_expect.exp     //make el the owner.
    sudo chmod 700 my_test_expect.exp    //make file only readable by el.
    
  7. You see these sorts of commands at the bottom of my_test_expect.exp:

    set timeout -1
    spawn sudo chown root:root myfile.txt
    match_max 100000
    expect -exact "\[sudo\] password for el: "
    send -- "YourPasswordStoredInPlaintext\r"
    expect eof
    
  8. You will need to verify that the above expect commands are appropriate. If the autoexpect script is being overly sensitive or not sensitive enough then it will hang. In this case it's acceptable because the expect is waiting for text that will always arrive.

  9. Run the expect script as user el:

    expect my_test_expect.exp 
    spawn sudo chown root:root myfile.txt
    [sudo] password for el: 
    
  10. The password contained in my_test_expect.exp was piped into a chown to root by user el. To see if the password was accepted, look at myfile.txt:

    ls -l
    -rw-r--r--  1 root root          0 Dec  2 14:48 myfile.txt
    

It worked because it is root, and el never entered a password. If you expose your root, sudo, or power user password with this script, then acquiring root on your box will be easy. Such is the penalty for a security system that lets everybody in no questions asked.

Center div on the middle of screen

This should work with any div or screen size:

_x000D_
_x000D_
.center-screen {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  text-align: center;_x000D_
  min-height: 100vh;_x000D_
}
_x000D_
 <html>_x000D_
 <head>_x000D_
 </head>_x000D_
 <body>_x000D_
 <div class="center-screen">_x000D_
 I'm in the center_x000D_
 </div>_x000D_
 </body>_x000D_
 </html>
_x000D_
_x000D_
_x000D_

See more details about flex here. This should work on most of the browsers, see compatibility matrix here.

Update: If you don't want the scroll bar, make min-height smaller, for example min-height: 95vh;

Examples of Algorithms which has O(1), O(n log n) and O(log n) complexities

O(1) - most cooking procedures are O(1), that is, it takes a constant amount of time even if there are more people to cook for (to a degree, because you could run out of space in your pot/pans and need to split up the cooking)

O(logn) - finding something in your telephone book. Think binary search.

O(n) - reading a book, where n is the number of pages. It is the minimum amount of time it takes to read a book.

O(nlogn) - cant immediately think of something one might do everyday that is nlogn...unless you sort cards by doing merge or quick sort!

What is the proper way to URL encode Unicode characters?

The first question is what are your needs? UTF-8 encoding is a pretty good compromise between taking text created with a cheap editor and support for a wide variety of languages. In regards to the browser identifying the encoding, the response (from the web server) should tell the browser the encoding. Still most browsers will attempt to guess, because this is either missing or wrong in so many cases. They guess by reading some amount of the result stream to see if there is a character that does not fit in the default encoding. Currently all browser(? I did not check this, but it is pretty close to true) use utf-8 as the default.

So use utf-8 unless you have a compelling reason to use one of the many other encoding schemes.

How to use z-index in svg elements?

its easy to do it:

  1. clone your items
  2. sort cloned items
  3. replace items by cloned

_x000D_
_x000D_
function rebuildElementsOrder( selector, orderAttr, sortFnCallback ) {_x000D_
 let $items = $(selector);_x000D_
 let $cloned = $items.clone();_x000D_
 _x000D_
 $cloned.sort(sortFnCallback != null ? sortFnCallback : function(a,b) {_x000D_
    let i0 = a.getAttribute(orderAttr)?parseInt(a.getAttribute(orderAttr)):0,_x000D_
        i1 = b.getAttribute(orderAttr)?parseInt(b.getAttribute(orderAttr)):0;_x000D_
    return i0 > i1?1:-1;_x000D_
 });_x000D_
_x000D_
        $items.each(function(i, e){_x000D_
            e.replaceWith($cloned[i]);_x000D_
 })_x000D_
}_x000D_
_x000D_
$('use[order]').click(function() {_x000D_
    rebuildElementsOrder('use[order]', 'order');_x000D_
_x000D_
    /* you can use z-index property for inline css declaration_x000D_
    ** getComputedStyle always return "auto" in both Internal and External CSS decl [tested in chrome]_x000D_
    _x000D_
    rebuildElementsOrder( 'use[order]', null, function(a, b) {_x000D_
        let i0 = a.style.zIndex?parseInt(a.style.zIndex):0,_x000D_
        i1 = b.style.zIndex?parseInt(b.style.zIndex):0;_x000D_
    return i0 > i1?1:-1;_x000D_
    });_x000D_
    */_x000D_
});
_x000D_
use[order] {_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="keybContainer" viewBox="0 0 150 150" xml:space="preserve">_x000D_
<defs>_x000D_
    <symbol id="sym-cr" preserveAspectRatio="xMidYMid meet" viewBox="0 0 60 60">_x000D_
        <circle cx="30" cy="30" r="30" />_x000D_
        <text x="30" y="30" text-anchor="middle" font-size="0.45em" fill="white">_x000D_
            <tspan dy="0.2em">Click to reorder</tspan>_x000D_
        </text>_x000D_
    </symbol>_x000D_
</defs>_x000D_
    <use order="1" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="0" y="0" width="60" height="60" style="fill: #ff9700; z-index: 1;"></use>_x000D_
    <use order="4" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="50" y="20" width="50" height="50" style="fill: #0D47A1; z-index: 4;"></use>_x000D_
    <use order="5" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="15" y="30" width="50" height="40" style="fill: #9E9E9E; z-index: 5;"></use>_x000D_
    <use order="3" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="25" y="30" width="80" height="80" style="fill: #D1E163; z-index: 3;"></use>_x000D_
    <use order="2" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="30" y="0" width="50" height="70" style="fill: #00BCD4; z-index: 2;"></use>_x000D_
    <use order="0" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sym-cr" x="5" y="5" width="100" height="100" style="fill: #E91E63; z-index: 0;"></use>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Merge a Branch into Trunk

Your svn merge syntax is wrong.

You want to checkout a working copy of trunk and then use the svn merge --reintegrate option:

$ pwd
/home/user/project-trunk

$ svn update  # (make sure the working copy is up to date)
At revision <N>.

$ svn merge --reintegrate ^/project/branches/branch_1
--- Merging differences between repository URLs into '.':
U    foo.c
U    bar.c
 U   .

$ # build, test, verify, ...

$ svn commit -m "Merge branch_1 back into trunk!"
Sending        .
Sending        foo.c
Sending        bar.c
Transmitting file data ..
Committed revision <N+1>.

See the SVN book chapter on merging for more details.


Note that at the time it was written, this was the right answer (and was accepted), but things have moved on. See the answer of topek, and http://subversion.apache.org/docs/release-notes/1.8.html#auto-reintegrate

How to get just the date part of getdate()?

SELECT CONVERT(date, GETDATE())

MySQL Data - Best way to implement paging?

From the MySQL documentation:

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).

With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):

SELECT * FROM tbl LIMIT 5,10;  # Retrieve rows 6-15

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:

SELECT * FROM tbl LIMIT 95,18446744073709551615;

With one argument, the value specifies the number of rows to return from the beginning of the result set:

SELECT * FROM tbl LIMIT 5;     # Retrieve first 5 rows

In other words, LIMIT row_count is equivalent to LIMIT 0, row_count.

How to get an array of specific "key" in multidimensional array without looping

You can also use array_reduce() if you prefer a more functional approach

For instance:

$userNames = array_reduce($users, function ($carry, $user) {
    array_push($carry, $user['name']);
    return $carry;
}, []);

Or if you like to be fancy,

$userNames = [];
array_map(function ($user) use (&$userNames){
    $userNames[]=$user['name'];
}, $users);

This and all the methods above do loop behind the scenes though ;)

NLTK and Stopwords Fail #lookuperror

import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
STOPWORDS = set(stopwords.words('english'))

How do you grep a file and get the next 5 lines

Some awk version.

awk '/19:55/{c=5} c-->0'
awk '/19:55/{c=5} c && c--'

When pattern found, set c=5
If c is true, print and decrease number of c

Detecting value change of input[type=text] in jQuery

Use this: https://github.com/gilamran/JQuery-Plugin-AnyChange

It handles all the ways to change the input, including content menu (Using the mouse)