Programs & Examples On #Hierarchyid

What are the options for storing hierarchical data in a relational database?

Adjacency Model + Nested Sets Model

I went for it because I could insert new items to the tree easily (you just need a branch's id to insert a new item to it) and also query it quite fast.

+-------------+----------------------+--------+-----+-----+
| category_id | name                 | parent | lft | rgt |
+-------------+----------------------+--------+-----+-----+
|           1 | ELECTRONICS          |   NULL |   1 |  20 |
|           2 | TELEVISIONS          |      1 |   2 |   9 |
|           3 | TUBE                 |      2 |   3 |   4 |
|           4 | LCD                  |      2 |   5 |   6 |
|           5 | PLASMA               |      2 |   7 |   8 |
|           6 | PORTABLE ELECTRONICS |      1 |  10 |  19 |
|           7 | MP3 PLAYERS          |      6 |  11 |  14 |
|           8 | FLASH                |      7 |  12 |  13 |
|           9 | CD PLAYERS           |      6 |  15 |  16 |
|          10 | 2 WAY RADIOS         |      6 |  17 |  18 |
+-------------+----------------------+--------+-----+-----+
  • Every time you need all children of any parent you just query the parent column.
  • If you needed all descendants of any parent you query for items which have their lft between lft and rgt of parent.
  • If you needed all parents of any node up to the root of the tree, you query for items having lft lower than the node's lft and rgt bigger than the node's rgt and sort the by parent.

I needed to make accessing and querying the tree faster than inserts, that's why I chose this

The only problem is to fix the left and right columns when inserting new items. well I created a stored procedure for it and called it every time I inserted a new item which was rare in my case but it is really fast. I got the idea from the Joe Celko's book, and the stored procedure and how I came up with it is explained here in DBA SE https://dba.stackexchange.com/q/89051/41481

C# Equivalent of SQL Server DataTypes

SQL Server and .Net Data Type mapping

SQL Server and .Net Data Type mapping

set initial viewcontroller in appdelegate - swift

For Swift 5+


var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            let submodules = (
                home: HomeRouter.createModule(),
                search: SearchRouter.createModule(),
                exoplanets: ExoplanetsRouter.createModule()
            )
            
            let tabBarController = TabBarModuleBuilder.build(usingSubmodules: submodules)
            
            window.rootViewController = tabBarController
            self.window = window
            window.makeKeyAndVisible()
        }
    }

how to display none through code behind

Try if this works:

Panel2.Style.Add("display", "none");

How to draw circle in html page?

  • No width and height requirement (specify just whichever you prefer)
  • No SVG, canvas or Unicode

_x000D_
_x000D_
.circle {
    background: green;
    border-radius: 50%;
    width: 1rem;
    aspect-ratio: 1/1;
}
_x000D_
<div class="circle"></div>
_x000D_
_x000D_
_x000D_

Borwser support:

  • Chrome/Edge 88+
  • Firefox 83+ behind a flag

Problems with jQuery getJSON using local files in Chrome

@Mike On Mac, type this in Terminal:

open -b com.google.chrome --args --disable-web-security

Travel/Hotel API's?

Check out api.hotelsbase.org - its a free xml hotel api No images as of yet though

How can I hide a TD tag using inline JavaScript or CSS?

<td style = "display:none" >
<p> Content display none </p>
</td>

or

<td style="visibility:hidden"> Your content is hidden </td>

Notice that: 2 those ways are differnce. You should try it to check the result.

What is the proper way to re-attach detached objects in Hibernate?

Perhaps it behaves slightly different on Eclipselink. To re-attach detached objects without getting stale data, I usually do:

Object obj = em.find(obj.getClass(), id);

and as an optional a second step (to get caches invalidated):

em.refresh(obj)

How to install Jdk in centos

There are JDK versions available from the base CentOS repositories. Depending on your version of CentOS, and the JDK you want to install, the following as root should give you what you want:

OpenJDK Runtime Environment (Java SE 6)

yum install java-1.6.0-openjdk

OpenJDK Runtime Environment (Java SE 7)

yum install java-1.7.0-openjdk

OpenJDK Development Environment (Java SE 7)

yum install java-1.7.0-openjdk-devel

OpenJDK Development Environment (Java SE 6)

yum install java-1.6.0-openjdk-devel

Update for Java 8

In CentOS 6.6 or later, Java 8 is available. Similar to 6 and 7 above, the packages are as follows:

OpenJDK Runtime Environment (Java SE 8)

yum install java-1.8.0-openjdk

OpenJDK Development Environment (Java SE 8)

yum install java-1.8.0-openjdk-devel

There's also a 'headless' JRE package that is the same as the above JRE, except it doesn't contain audio/video support. This can be used for a slightly more minimal installation:

OpenJDK Runtime Environment - Headless (Java SE 8)

yum install java-1.8.0-openjdk-headless

Why there is no ConcurrentHashSet against ConcurrentHashMap

As pointed by this the best way to obtain a concurrency-able HashSet is by means of Collections.synchronizedSet()

Set s = Collections.synchronizedSet(new HashSet(...));

This worked for me and I haven't seen anybody really pointing to it.

EDIT This is less efficient than the currently aproved solution, as Eugene points out, since it just wraps your set into a synchronized decorator, while a ConcurrentHashMap actually implements low-level concurrency and it can back your Set just as fine. So thanks to Mr. Stepanenkov for making that clear.

http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedSet-java.util.Set-

Java String array: is there a size of method?

Also, it's probably useful to note that if you have a multiple dimensional Array, you can get the respective dimension just by appending a '[0]' to the array you are querying until you arrive at the appropriate axis/tuple/dimension.

This is probably better explained with the following code:

public class Test {
    public static void main(String[] args){
        String[][] moo = new String[5][12];

        System.out.println(moo.length); //Prints the size of the First Dimension in the array
        System.out.println(moo[0].length);//Prints the size of the Second Dimension in the array
    }

}

Which produces the output:

5
12

Increase days to php current Date()

<?php
$dt = new DateTime;
if(isset($_GET['year']) && isset($_GET['week'])) {
    $dt->setISODate($_GET['year'], $_GET['week']);
} else {
    $dt->setISODate($dt->format('o'), $dt->format('W'));
}
$year = $dt->format('o');
$week = $dt->format('W');
?>

<a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week-1).'&year='.$year; ?>">Pre Week</a> 
<a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week+1).'&year='.$year; ?>">Next Week</a>
<table width="100%" style="height: 75px; border: 1px solid #00A2FF;">
<tr>
<td style="display: table-cell;
    vertical-align: middle;
    cursor: pointer;
    width: 75px;
    height: 75px;
    border: 4px solid #00A2FF;
    border-radius: 50%;">Employee</td>
<?php
do {
    echo "<td>" . $dt->format('M') . "<br>" . $dt->format('d M Y') . "</td>\n";
    $dt->modify('+1 day');
} while ($week == $dt->format('W'));
?>
</tr>
</table>

How to update two tables in one statement in SQL Server 2005?

You can't update multiple tables in one statement, however, you can use a transaction to make sure that two UPDATE statements are treated atomically. You can also batch them to avoid a round trip.

BEGIN TRANSACTION;

UPDATE Table1
  SET Table1.LastName = 'DR. XXXXXX' 
FROM Table1 T1, Table2 T2
WHERE T1.id = T2.id
and T1.id = '011008';

UPDATE Table2
SET Table2.WAprrs = 'start,stop'
FROM Table1 T1, Table2 T2
WHERE T1.id = T2.id
and T1.id = '011008';

COMMIT;

How to style dt and dd so they are on the same line?

I usually start with the following when styling definition lists as tables:

dt,
dd{
    /* Override browser defaults */
    display: inline;
    margin: 0;
}

dt  {
    clear:left;
    float:left;
    line-height:1; /* Adjust this value as you see fit */
    width:33%; /* 1/3 the width of the parent. Adjust this value as you see fit */
}

dd {
    clear:right;
    float: right;
    line-height:1; /* Adjust this value as you see fit */
    width:67%; /* 2/3 the width of the parent. Adjust this value as you see fit */
}

Change collations of all columns of all tables in SQL Server

Fixed length problem nvarchar (include max), included text and added NULL/NOT NULL.

USE [put your database name here];

begin tran

DECLARE @collate nvarchar(100);
DECLARE @table nvarchar(255);
DECLARE @column_name nvarchar(255);
DECLARE @column_id int;
DECLARE @data_type nvarchar(255);
DECLARE @max_length int;
DECLARE @max_length_str nvarchar(100);
DECLARE @is_nullable bit;
DECLARE @row_id int;
DECLARE @sql nvarchar(max);
DECLARE @sql_column nvarchar(max);

SET @collate = 'Latin1_General_CI_AS';

DECLARE local_table_cursor CURSOR FOR

SELECT [name]
FROM sysobjects
WHERE OBJECTPROPERTY(id, N'IsUserTable') = 1
ORDER BY [name]

OPEN local_table_cursor
FETCH NEXT FROM local_table_cursor
INTO @table

WHILE @@FETCH_STATUS = 0
BEGIN

    DECLARE local_change_cursor CURSOR FOR

    SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS row_id
        , c.name column_name
        , t.Name data_type
        , col.CHARACTER_MAXIMUM_LENGTH
        , c.column_id
        , c.is_nullable
    FROM sys.columns c
    JOIN sys.types t ON c.system_type_id = t.system_type_id
    JOIN INFORMATION_SCHEMA.COLUMNS col on col.COLUMN_NAME = c.name and c.object_id = OBJECT_ID(col.TABLE_NAME)
    LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
    LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
    WHERE c.object_id = OBJECT_ID(@table) AND (t.Name LIKE '%char%' OR t.Name LIKE '%text%') 
    AND c.collation_name <> @collate
    ORDER BY c.column_id

    OPEN local_change_cursor
    FETCH NEXT FROM local_change_cursor
    INTO @row_id, @column_name, @data_type, @max_length, @column_id, @is_nullable

    WHILE @@FETCH_STATUS = 0
    BEGIN

        set @max_length_str = @max_length
        IF (@max_length = -1) SET @max_length_str = 'max'
        IF (@max_length > 4000) SET @max_length_str = '4000'

        BEGIN TRY
            SET @sql =
            CASE 
                WHEN @data_type like '%text%' 
                THEN 'ALTER TABLE ' + @table + ' ALTER COLUMN [' + @column_name + '] ' + @data_type + ' COLLATE ' + @collate + ' ' + CASE WHEN @is_nullable = 0 THEN 'NOT NULL' ELSE 'NULL' END
                ELSE 'ALTER TABLE ' + @table + ' ALTER COLUMN [' + @column_name + '] ' + @data_type + '(' + @max_length_str + ') COLLATE ' + @collate + ' ' + CASE WHEN @is_nullable = 0 THEN 'NOT NULL' ELSE 'NULL' END
            END
            --PRINT @sql
            EXEC sp_executesql @sql
        END TRY
        BEGIN CATCH
          PRINT 'ERROR (' + @table + '): Some index or constraint rely on the column ' + @column_name + '. No conversion possible.'
          --PRINT @sql
        END CATCH

        FETCH NEXT FROM local_change_cursor
        INTO @row_id, @column_name, @data_type, @max_length, @column_id, @is_nullable

    END

    CLOSE local_change_cursor
    DEALLOCATE local_change_cursor

    FETCH NEXT FROM local_table_cursor
    INTO @table

END

CLOSE local_table_cursor
DEALLOCATE local_table_cursor

commit tran

GO

Notice : in case when you just need to change some specific collation use condition like this :

WHERE c.object_id = OBJECT_ID(@table) AND (t.Name LIKE '%char%' OR t.Name LIKE '%text%') 
    AND c.collation_name = 'collation to change'

e.g. NOT the : AND c.collation_name <> @collate

In my case, I had correct / specified collation of some columns and didn't want to change them.

Is there a command to refresh environment variables from the command prompt in Windows?

You can capture the system environment variables with a vbs script, but you need a bat script to actually change the current environment variables, so this is a combined solution.

Create a file named resetvars.vbs containing this code, and save it on the path:

Set oShell = WScript.CreateObject("WScript.Shell")
filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat")
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set oFile = objFileSystem.CreateTextFile(filename, TRUE)

set oEnv=oShell.Environment("System")
for each sitem in oEnv 
    oFile.WriteLine("SET " & sitem)
next
path = oEnv("PATH")

set oEnv=oShell.Environment("User")
for each sitem in oEnv 
    oFile.WriteLine("SET " & sitem)
next

path = path & ";" & oEnv("PATH")
oFile.WriteLine("SET PATH=" & path)
oFile.Close

create another file name resetvars.bat containing this code, same location:

@echo off
%~dp0resetvars.vbs
call "%TEMP%\resetvars.bat"

When you want to refresh the environment variables, just run resetvars.bat


Apologetics:

The two main problems I had coming up with this solution were

a. I couldn't find a straightforward way to export environment variables from a vbs script back to the command prompt, and

b. the PATH environment variable is a concatenation of the user and the system PATH variables.

I'm not sure what the general rule is for conflicting variables between user and system, so I elected to make user override system, except in the PATH variable which is handled specifically.

I use the weird vbs+bat+temporary bat mechanism to work around the problem of exporting variables from vbs.

Note: this script does not delete variables.

This can probably be improved.

ADDED

If you need to export the environment from one cmd window to another, use this script (let's call it exportvars.vbs):

Set oShell = WScript.CreateObject("WScript.Shell")
filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat")
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set oFile = objFileSystem.CreateTextFile(filename, TRUE)

set oEnv=oShell.Environment("Process")
for each sitem in oEnv 
    oFile.WriteLine("SET " & sitem)
next
oFile.Close

Run exportvars.vbs in the window you want to export from, then switch to the window you want to export to, and type:

"%TEMP%\resetvars.bat"

How do you push a tag to a remote repository using Git?

I am using git push <remote-name> tag <tag-name> to ensure that I am pushing a tag. I use it like: git push origin tag v1.0.1. This pattern is based upon the documentation (man git-push):

OPTIONS
   ...
   <refspec>...
       ...
       tag <tag> means the same as refs/tags/<tag>:refs/tags/<tag>.

How to Auto-start an Android Application?

You have to add a manifest permission entry:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

(of course you should list all other permissions that your app uses).

Then, implement BroadcastReceiver class, it should be simple and fast executable. The best approach is to set an alarm in this receiver to wake up your service (if it's not necessary to keep it running ale the time as Prahast wrote).

public class BootUpReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context, MyService.class), PendingIntent.FLAG_UPDATE_CURRENT);
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, interval, pi);
    }
}

Then, add a Receiver class to your manifest file:

<receiver android:enabled="true" android:name=".receivers.BootUpReceiver"
    android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

How do I set adaptive multiline UILabel text?

I kind of got things working by adding auto layout constraints:

auto layout contraints

But I am not happy with this. Took a lot of trial and error and couldn't understand why this worked.

Also I had to add to use titleLabel.numberOfLines = 0 in my ViewController

What is the maximum possible length of a .NET string?

Since String.Length is an integer (that is an alias for Int32), its size is limited to Int32.MaxValue unicode characters. ;-)

Python Loop: List Index Out of Range

  1. In your for loop, you're iterating through the elements of a list a. But in the body of the loop, you're using those items to index that list, when you actually want indexes.
    Imagine if the list a would contain 5 items, a number 100 would be among them and the for loop would reach it. You will essentially attempt to retrieve the 100th element of the list a, which obviously is not there. This will give you an IndexError.

We can fix this issue by iterating over a range of indexes instead:

for i in range(len(a))

and access the a's items like that: a[i]. This won't give any errors.

  1. In the loop's body, you're indexing not only a[i], but also a[i+1]. This is also a place for a potential error. If your list contains 5 items and you're iterating over it like I've shown in the point 1, you'll get an IndexError. Why? Because range(5) is essentially 0 1 2 3 4, so when the loop reaches 4, you will attempt to get the a[5] item. Since indexing in Python starts with 0 and your list contains 5 items, the last item would have an index 4, so getting the a[5] would mean getting the sixth element which does not exist.

To fix that, you should subtract 1 from len(a) in order to get a range sequence 0 1 2 3. Since you're using an index i+1, you'll still get the last element, but this way you will avoid the error.

  1. There are many different ways to accomplish what you're trying to do here. Some of them are quite elegant and more "pythonic", like list comprehensions:

b = [a[i] + a[i+1] for i in range(len(a) - 1)]

This does the job in only one line.

Measure the time it takes to execute a t-sql query

If you want a more accurate measurement than the answer above:

set statistics time on 

-- Query 1 goes here

-- Query 2 goes here

set statistics time off

The results will be in the Messages window.

Update (2015-07-29):

By popular request, I have written a code snippet that you can use to time an entire stored procedure run, rather than its components. Although this only returns the time taken by the last run, there are additional stats returned by sys.dm_exec_procedure_stats that may also be of value:

-- Use the last_elapsed_time from sys.dm_exec_procedure_stats
-- to time an entire stored procedure.

-- Set the following variables to the name of the stored proc
-- for which which you would like run duration info
DECLARE @DbName NVARCHAR(128);
DECLARE @SchemaName SYSNAME;
DECLARE @ProcName SYSNAME=N'TestProc';

SELECT CONVERT(TIME(3),DATEADD(ms,ROUND(last_elapsed_time/1000.0,0),0)) 
       AS LastExecutionTime
FROM sys.dm_exec_procedure_stats
WHERE OBJECT_NAME(object_id,database_id)=@ProcName AND
      (OBJECT_SCHEMA_NAME(object_id,database_id)=@SchemaName OR @SchemaName IS NULL) AND
      (DB_NAME(database_id)=@DbName OR @DbName IS NULL)

CSS Vertical align does not work with float

Edited:

The vertical-align CSS property specifies the vertical alignment of an inline, inline-block or table-cell element.

Read this article for Understanding vertical-align

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

Let me share what worked for me:

  1. When we do "mvn clean" - we are cleaning old compiled classes please lgo to ocation "your project directroy -> target " you will find this folder is getting cleaned because that's where MVN places it's compiled artifacts

  2. Since it's already a MAVEN project then go to your project folder and open in command prompt. And issue "mvn clean" and then "mvn test" -> "mvn test" command will place all the compiled files under proper folders and then you can run your tests through TestNG or MAVEN itself.

  3. Make sure you set up "M2_HOME" or "MAVEN_HOME" to your env path , sometime "MAVEN_HOME" doesn't work so add "M2_HOME" as well (google it for this set up)

Above suggestions worked for me so I wanted to share, good luck

Getting all types that implement an interface

I got exceptions in the linq-code so I do it this way (without a complicated extension):

private static IList<Type> loadAllImplementingTypes(Type[] interfaces)
{
    IList<Type> implementingTypes = new List<Type>();

    // find all types
    foreach (var interfaceType in interfaces)
        foreach (var currentAsm in AppDomain.CurrentDomain.GetAssemblies())
            try
            {
                foreach (var currentType in currentAsm.GetTypes())
                    if (interfaceType.IsAssignableFrom(currentType) && currentType.IsClass && !currentType.IsAbstract)
                        implementingTypes.Add(currentType);
            }
            catch { }

    return implementingTypes;
}

What are native methods in Java and where should they be used?

What are native methods in Java and where should they be used?

Once you see a small example, it becomes clear:

Main.java:

public class Main {
    public native int intMethod(int i);
    public static void main(String[] args) {
        System.loadLibrary("Main");
        System.out.println(new Main().intMethod(2));
    }
}

Main.c:

#include <jni.h>
#include "Main.h"

JNIEXPORT jint JNICALL Java_Main_intMethod(
    JNIEnv *env, jobject obj, jint i) {
  return i * i;
}

Compile and run:

javac Main.java
javah -jni Main
gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \
  -I${JAVA_HOME}/include/linux Main.c
java -Djava.library.path=. Main

Output:

4

Tested on Ubuntu 14.04 with Oracle JDK 1.8.0_45.

So it is clear that it allows you to:

  • call a compiled dynamically loaded library (here written in C) with arbitrary assembly code from Java
  • and get results back into Java

This could be used to:

  • write faster code on a critical section with better CPU assembly instructions (not CPU portable)
  • make direct system calls (not OS portable)

with the tradeoff of lower portability.

It is also possible for you to call Java from C, but you must first create a JVM in C: How to call Java functions from C++?

Example on GitHub for you to play with.

equivalent to push() or pop() for arrays?

For those who don't have time to refactor the code to replace arrays with Collections (for example ArrayList), there is an alternative. Unlike Collections, the length of an array cannot be changed, but the array can be replaced, like this:

array = push(array, item);

The drawbacks are that

  • the whole array has to be copied each time you push, and
  • the original array Object is not changed, so you have to update the variable(s) as appropriate.

Here is the push method for String:
(You can create multiple push methods, one for String, one for int, etc)

private static String[] push(String[] array, String push) {
    String[] longer = new String[array.length + 1];
    for (int i = 0; i < array.length; i++)
        longer[i] = array[i];
    longer[array.length] = push;
    return longer;
}

This alternative is more efficient, shorter & harder to read:

private static String[] push(String[] array, String push) {
    String[] longer = new String[array.length + 1];
    System.arraycopy(array, 0, longer, 0, array.length);
    longer[array.length] = push;
    return longer;
}

How to change shape color dynamically?

My shape xml :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid  android:color="@android:color/transparent" />
<stroke android:width="0.5dp" android:color="@android:color/holo_green_dark"/>
</shape>

My activity xml :

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="cn.easydone.test.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />
    <TextView
        android:id="@+id/test_text"
        android:background="@drawable/bg_stroke_dynamic_color"
        android:padding="20dp"
        android:text="asdasdasdasd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</android.support.design.widget.AppBarLayout>

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:clipToPadding="false"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

My activity java :

 TextView testText = (TextView) findViewById(R.id.test_text);
 ((GradientDrawable)testText.getBackground()).setStroke(10,Color.BLACK);

Result picture : result

C# Creating and using Functions

Just make your Add function static by adding the static keyword like this:

public static int Add(int x, int y)

Write and read a list from file

If you don't need it to be human-readable/editable, the easiest solution is to just use pickle.

To write:

with open(the_filename, 'wb') as f:
    pickle.dump(my_list, f)

To read:

with open(the_filename, 'rb') as f:
    my_list = pickle.load(f)

If you do need them to be human-readable, we need more information.

If my_list is guaranteed to be a list of strings with no embedded newlines, just write them one per line:

with open(the_filename, 'w') as f:
    for s in my_list:
        f.write(s + '\n')

with open(the_filename, 'r') as f:
    my_list = [line.rstrip('\n') for line in f]

If they're Unicode strings rather than byte strings, you'll want to encode them. (Or, worse, if they're byte strings, but not necessarily in the same encoding as your system default.)

If they might have newlines, or non-printable characters, etc., you can use escaping or quoting. Python has a variety of different kinds of escaping built into the stdlib.

Let's use unicode-escape here to solve both of the above problems at once:

with open(the_filename, 'w') as f:
    for s in my_list:
        f.write((s + u'\n').encode('unicode-escape'))

with open(the_filename, 'r') as f:
    my_list = [line.decode('unicode-escape').rstrip(u'\n') for line in f]

You can also use the 3.x-style solution in 2.x, with either the codecs module or the io module:*

import io

with io.open(the_filename, 'w', encoding='unicode-escape') as f:
    f.writelines(line + u'\n' for line in my_list)

with open(the_filename, 'r') as f:
    my_list = [line.rstrip(u'\n') for line in f]

* TOOWTDI, so which is the one obvious way? It depends… For the short version: if you need to work with Python versions before 2.6, use codecs; if not, use io.

Compiling C++11 with g++

Your Ubuntu definitely has a sufficiently recent version of g++. The flag to use is -std=c++0x.

How can I center a div within another div?

#main_content {
    width: 400px;
    margin: 0 auto;
    min-height: 300px;
    height: auto;
    background-color: #2185C5;
    position: relative;
}

#container {
    width: 50%;
    height: auto;
    margin: 0 auto;
    background-color: #CCC;
    padding: 10px;
    position: relative;
}

Try this. It tested OK. There is a live check on jsfiddle.

How can I debug what is causing a connection refused or a connection time out?

Use a packet analyzer to intercept the packets to/from somewhere.com. Studying those packets should tell you what is going on.

Time-outs or connections refused could mean that the remote host is too busy.

How can I change image source on click with jQuery?

It switches back because by default, when you click a link, it follows the link and loads the page. In your case, you don't want that. You can prevent it either by doing e.preventDefault(); (like Neal mentioned) or by returning false :

$(function() {
 $('.menulink').click(function(){
   $("#bg").attr('src',"img/picture1.jpg");
   return false;
 });
});

Interesting question on the differences between prevent default and return false.

In this case, return false will work just fine because the event doesn't need to be propagated.

Change :hover CSS properties with JavaScript

Had some same problems, used addEventListener for events "mousenter", "mouseleave":

let DOMelement = document.querySelector('CSS selector for your HTML element');

// if you want to change e.g color: 
let origColorStyle = DOMelement.style.color;

DOMelement.addEventListener("mouseenter", (event) => { event.target.style.color = "red" });

DOMelement.addEventListener("mouseleave", (event) => { event.target.style.color = origColorStyle })

Or something else for style when cursor is above the DOMelement. DOMElement can be chosen by various ways.

Map to String in Java

You can also use google-collections (guava) Joiner class if you want to customize the print format

Display fullscreen mode on Tkinter

root = Tk()
root.geomentry('1599x1499')

Collections.emptyList() returns a List<Object>?

the emptyList method has this signature:

public static final <T> List<T> emptyList()

That <T> before the word List means that it infers the value of the generic parameter T from the type of variable the result is assigned to. So in this case:

List<String> stringList = Collections.emptyList();

The return value is then referenced explicitly by a variable of type List<String>, so the compiler can figure it out. In this case:

setList(Collections.emptyList());

There's no explicit return variable for the compiler to use to figure out the generic type, so it defaults to Object.

Securing a password in a properties file

Actually, this is a duplicate of Encrypt Password in Configuration Files?.

The best solution I found so far is in this answert: https://stackoverflow.com/a/1133815/1549977

Pros: Password is saved a a char array, not as a string. It's still not good, but better than anything else.

How can I get the corresponding table header (th) from a table cell (td)?

You can do it by using the td's index:

var tdIndex = $td.index() + 1;
var $th = $('#table tr').find('th:nth-child(' + tdIndex + ')');

If (Array.Length == 0)

As other have already suggested it is likely you are getting a NullReferenceException which can be avoided by first checking to see if the reference is null. However, you need to ask yourself whether that check is actually warranted. Would you be doing it because the reference really might be null and it being null has a special meaning in your code? Or would you be doing it to cover up a bug? The nature of the question leads me to believe it would be the latter. In which case you really need to examine the code in depth and figure out why that reference did not get initialized properly in the first place.

How to use phpexcel to read data and insert into database?

Using the PHPExcel library, the following code will do.

require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';    
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true); //optional

$objPHPExcel = $objReader->load(__DIR__.'/YourExcelFile.xlsx');
$objWorksheet = $objPHPExcel->getActiveSheet();

$i=1;
foreach ($objWorksheet->getRowIterator() as $row) {

    $column_A_Value = $objPHPExcel->getActiveSheet()->getCell("A$i")->getValue();//column A
    //you can add your own columns B, C, D etc.

    //inset $column_A_Value value in DB query here

    $i++;
}

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

The NSDictionary and NSMutableDictionary docs are probably your best bet. They even have some great examples on how to do various things, like...

...create an NSDictionary

NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects 
                                                       forKeys:keys];

...iterate over it

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

...make it mutable

NSMutableDictionary *mutableDict = [dictionary mutableCopy];

Note: historic version before 2010: [[dictionary mutableCopy] autorelease]

...and alter it

[mutableDict setObject:@"value3" forKey:@"key3"];

...then store it to a file

[mutableDict writeToFile:@"path/to/file" atomically:YES];

...and read it back again

NSMutableDictionary *anotherDict = [NSMutableDictionary dictionaryWithContentsOfFile:@"path/to/file"];

...read a value

NSString *x = [anotherDict objectForKey:@"key1"];

...check if a key exists

if ( [anotherDict objectForKey:@"key999"] == nil ) NSLog(@"that key is not there");

...use scary futuristic syntax

From 2014 you can actually just type dict[@"key"] rather than [dict objectForKey:@"key"]

How to validate an email address using a regular expression?

Cal Henderson (Flickr) wrote an article called Parsing Email Adresses in PHP and shows how to do proper RFC (2)822-compliant Email Address parsing. You can also get the source code in php, python and ruby which is cc licensed.

How can I get two form fields side-by-side, with each field’s label above the field, in CSS?

How about something like this?

<div id="leftContainer">
  <span>Company Name</span>
  <br><input type="text" value="John Lewis Partnership">
</div>
<div id="rightContainer">
  <span>Contact Name</span>
  <br><input type="text" value="Timothy Patten">
</div>

Then, you can align the 2 divs by floating them left and right:-

#leftContainer {
   float:left;
}

#rightContainer {
   float:right;
}

How do I create a view controller file after creating a new view controller?

To add new ViewController once you have have an existing ViewController, follow below step:

  1. Click on background of Main.storyboard.

  2. Search and select ViewController from object library at the utility window.

  3. Drag and drop it in background to create a new ViewController.

Locating child nodes of WebElements in selenium

For Finding All the ChildNodes you can use the below Snippet

List<WebElement> childs = MyCurrentWebElement.findElements(By.xpath("./child::*"));

        for (WebElement e  : childs)
        {
            System.out.println(e.getTagName());
        }

Note that this will give all the Child Nodes at same level -> Like if you have structure like this :

<Html> 
<body> 
 <div> ---suppose this is current WebElement 
   <a>
   <a>
      <img>
          <a>
      <img>
   <a>

It will give me tag names of 3 anchor tags here only . If you want all the child Elements recursively , you can replace the above code with MyCurrentWebElement.findElements(By.xpath(".//*"));

Hope That Helps !!

Set the selected index of a Dropdown using jQuery

Just found this, it works for me and I personally find it easier to read.

This will set the actual index just like gnarf's answer number 3 option.

// sets selected index of a select box the actual index of 0 
$("select#elem").attr('selectedIndex', 0);

This didn't used to work but does now... see bug: http://dev.jquery.com/ticket/1474

Addendum

As recommended in the comments use :

$("select#elem").prop('selectedIndex', 0);

Failure [INSTALL_FAILED_INVALID_APK]

I meet the similar issue, but it auto fixed after i reboot my Ubuntu PC,for I install some Ubuntu(12.04)app update,which leads to this issue.

how to pass data in an hidden field from one jsp page to another?

The code from Alex works great. Just note that when you use request.getParameter you must use a request dispatcher

//Pass results back to the client
RequestDispatcher dispatcher =   getServletContext().getRequestDispatcher("TestPages/ServiceServlet.jsp");
dispatcher.forward(request, response);

How to set Oracle's Java as the default Java in Ubuntu?

I put the line:

export JAVA_HOME=/usr/lib/jvm/java-7-oracle

in my ~/.bashrc file.

/usr/lib/jvm/java7-oracle should be a symbolic link pointing to /usr/lib/jvm/java-7-oracle-[version number here].

The reason it's a symbolic link is that in case there's a new version of the JVM, you don't need to update your .bashrc file, it should automatically point to the new version.

If you want to set JAVA_HOME environment variables globally and at system level means use should set in /etc/environment file.

How do I launch a program from command line without opening a new cmd window?

In Windows 7+ the first quotations will be the title to the cmd window to open the program:

start "title" "C:\path\program.exe"

Formatting your command like the above will temporarily open a cmd window that goes away as fast as it comes up so you really never see it. It also allows you to open more than one program without waiting for the first one to close first.

Measure string size in Bytes in php

You have to figure out if the string is ascii encoded or encoded with a multi-byte format.

In the former case, you can just use strlen.

In the latter case you need to find the number of bytes per character.

the strlen documentation gives an example of how to do it : http://www.php.net/manual/en/function.strlen.php#72274

Recommended SQL database design for tags or tagging

Use a single formatted text column[1] for storing the tags and use a capable full text search engine to index this. Else you will run into scaling problems when trying to implement boolean queries.

If you need details about the tags you have, you can either keep track of it in a incrementally maintained table or run a batch job to extract the information.

[1] Some RDBMS even provide a native array type which might be even better suited for storage by not needing a parsing step, but might cause problems with the full text search.

Custom height Bootstrap's navbar

I believe you are using Bootstrap 3. If so, please try this code, here is the bootply

<header>
    <div class="navbar navbar-static-top navbar-default">
        <div class="navbar-header">
            <a class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="glyphicon glyphicon-th-list"></span>
            </a>
        </div>
        <div class="container" style="background:yellow;">
            <a href="/">
                <img src="img/logo.png" class="logo img-responsive">
            </a>

            <nav class="navbar-collapse collapse pull-right" style="line-height:150px; height:150px;">
                <ul class="nav navbar-nav" style="display:inline-block;">
                    <li><a href="">Portfolio</a></li>
                    <li><a href="">Blog</a></li>
                    <li><a href="">Contact</a></li>
                </ul>
            </nav>
        </div>
    </div>
</header>

How do I mock an autowired @Value field in Spring with Mockito?

I'd like to suggest a related solution, which is to pass the @Value-annotated fields as parameters to the constructor, instead of using the ReflectionTestUtils class.

Instead of this:

public class Foo {

    @Value("${foo}")
    private String foo;
}

and

public class FooTest {

    @InjectMocks
    private Foo foo;

    @Before
    public void setUp() {
        ReflectionTestUtils.setField(Foo.class, "foo", "foo");
    }

    @Test
    public void testFoo() {
        // stuff
    }
}

Do this:

public class Foo {

    private String foo;

    public Foo(@Value("${foo}") String foo) {
        this.foo = foo;
    }
}

and

public class FooTest {

    private Foo foo;

    @Before
    public void setUp() {
        foo = new Foo("foo");
    }

    @Test
    public void testFoo() {
        // stuff
    }
}

Benefits of this approach: 1) we can instantiate the Foo class without a dependency container (it's just a constructor), and 2) we're not coupling our test to our implementation details (reflection ties us to the field name using a string, which could cause a problem if we change the field name).

How to include !important in jquery

Apparently it's possible to do this in jQuery:

$("#tabs").css("cssText", "height: 650px !important;");

Src: http://bugs.jquery.com/ticket/2066

Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

How can I use a local image as the base image with a dockerfile?

Verified: it works well in Docker 1.7.0.

Don't specify --pull=true when running the docker build command

From this thread on reference locally-built image using FROM at dockerfile:

If you want use the local image as the base image, pass without the option --pull=true
--pull=true will always attempt to pull a newer version of the image.

Linker Error C++ "undefined reference "

This error tells you everything:

undefined reference toHash::insert(int, char)

You're not linking with the implementations of functions defined in Hash.h. Don't you have a Hash.cpp to also compile and link?

Unable to install Android Studio in Ubuntu

@warsong is right. Installing only lib32stdc++6 solved the problem.

For next uses I rewrite @warsongs comment in answer area.

sudo apt-get install lib32stdc++6

Update :

For Ubuntu 15.04,15.10,16.04 LTS & Debian 8

Should composer.lock be committed to version control?

There's no exact answer to this.

Generally speaking, composer shouldn't be doing what the build system is meant to be doing and you shouldn't be putting composer.lock in VCS. Composer might strangely have it backwards. End users rather than produces shouldn't be using lock files. Usually your build system keeps snapshots, reusable dirs, etc rather than an empty dir each time. People checkout out a lib from composer might want that lib to use a lock so that the dependencies that lib loads have been tested against.

On the other hand that significantly increases the burden of version management, where you'd almost certainly want multiple versions of every library as dependencies will be strictly locked. If every library is likely to have a slightly different version then you need some multiple library version support and you can also quickly see the size of dependencies needed flair out, hence the advise to keep it on the leaf.

Taking that on board, I really don't find lock files to be useful either libraries or your own workdirs. It's only use for me is in my build/testing platform which persists any externally acquired assets only updating them when requested, providing repeatable builds for testing, build and deploy. While that can be kept in VCS it's not always kept with the source tree, the build trees will either be elsewhere in the VCS structure or managed by another system somewhere else. If it's stored in a VCS it's debatable whether or not to keep it in the same repo as source trees because otherwise every pull can bring in a mass of build assets. I quite like having things all in a well arranged repo with the exception of production/sensitive credentials and bloat.

SVN can do it better than git as it doesn't force you to acquire the entire repo (though I suspect that's not actually strictly needed for git either but support for that is limited and it's not commonly used). Simple build repos are usually just an overlay branch you merge/export the build tree into. Some people combine exernal resources in their source tree or separate further, external, build and source trees. It usually serves two purposes, build caching and repeatable builds but sometimes keeping it separate on at least some level also permits fresh/blank builds and multiple builds easily.

There are a number of strategies for this and none of them particularly work well with persisting the sources list unless you're keeping external source in your source tree.

They also have things like hashes in of the file, how do that merge when two people update packages? That alone should make you think maybe this is misconstrued.

The arguments people are putting forward for lock files are cases where they've taken a very specific and restrictive view of the problem. Want repeatable builds and consistent builds? Include the vendor folder in VCS. Then you also speed up fetching assets as well as not having to depend on potentially broken external resources during build. None of the build and deploy pipelines I create require external access unless absolutely necessary. If you do have to update an external resource it's once and only once. What composer is trying to achieve makes sense for a distributed system except as mentioned before it makes no sense because it would end up with library dependency hell for library updates with common clashes and updates being as slow as the slowest to update package.

Additionally I update ferociously. Every time I develop I update and test everything. There's a very very tiny window for significant version drift to sneak in. Realistically as well, when semantic versioning is upheld, which is tends to be for composer, you're not suppose to have that many compatibility issues or breakages.

In composer.json you put the packages you require and their versions. You can lock the versions there. However those packages also have dependencies with dynamic versions that wont be locked by composer.json (though I don't see why your couldn't also put them there yourself if you do want them to be version locked) so someone else running composer install gets something different without the lock. You might not care a great deal about that or you might care, it depends. Should you care? Probably at least a little, enough to ensure you're aware of it in any situation and potential impact, but it might not be a problem either if you always have the time to just DRY run first and fix anything that got updated.

The hassle composer is trying to avoid sometimes just isn't there and the hassle having composer lock files can make is significant. They have absolutely no right to tell users what they should or shouldn't do regarding build versus source assets (whether to join of separate in VCS) as that's none of their business, they're not the boss of you or me. "Composer says" isn't an authority, they're not your superior officer nor do they give anyone any superiority on this subject. Only you know your real situation and what's best for that. However, they might advise a default course of action for users that don't understand how things work in which case you might want to follow that but personally I don't think that's a real substitute for knowing how things work and being able to properly workout your requirements. Ultimately, their answer to that question is a best guess. The people who make composer do not know where you should keep your composer.lock nor should they. Their only responsibility is to tell you what it is and what it does. Outside of that you need to decide what's best for you.

Keeping the lock file in is problematic for usability because composer is very secretive about whether it uses lock or JSON and doesn't always to well to use both together. If you run install it only uses the lock file it would appear so if you add something to composer.json then it wont be installed because it's not in your lock. It's not intuitive at all what operations really do and what they're doing in regards to the json/lock file and sometimes don't appear to even make sense (help says install takes a package name but on trying to use it it says no).

To update the lock or basically apply changes from the json you have to use update and you might not want to update everything. The lock takes precedence for choosing what should be installed. If there's a lock file, it's what's used. You can restrict update somewhat but the system is still just a mess.

Updating takes an age, gigs of RAM. I suspect as well if you pick up a project that's not been touched for a while that it looked from the versions it has up, which there will be more of over time and it probably doesn't do that efficiently which just strangles it.

They're very very sneaky when it comes to having secret composite commands you couldn't expect to be composite. By default the composer remove command appears to maps to composer update and composer remove for example.

The question you really need to be asking is not if you should keep the lock in your source tree or alternatively whether you should persist it somewhere in some fashion or not but rather you should be asking what it actually does, then you can decide for yourself when you need to persist it and where.

I will point out that having the ability to have the lock is a great convenience when you have a robust external dependency persistence strategy as it keeps track of you the information useful for tracking that (the origins) and updating it but if you don't then it's neither here not there. It's not useful when it's forced down your throat as a mandatory option to have it polluting your source trees. It's a very common thing to find in legacy codebases where people have made lots of changes to composer.json which haven't really been applied and are broken when people try to use composer. No composer.lock, no desync problem.

127 Return code from $?

This error is also at times deceiving. It says file is not found even though the files is indeed present. It could be because of invalid unreadable special characters present in the files that could be caused by the editor you are using. This link might help you in such cases.

-bash: ./my_script: /bin/bash^M: bad interpreter: No such file or directory

The best way to find out if it is this issue is to simple place an echo statement in the entire file and verify if the same error is thrown.

Navigation bar show/hide

If you want to detect the status of navigation bar wether it is hidden/shown. You can simply use following code to detect -

if self.navigationController?.isNavigationBarHidden{
    print("Show navigation bar")
} else {
    print("hide navigation bar")
}

Maven fails to find local artifact

I had the same error from a different cause: I'd created a starter POM containing our "good practice" dependencies, and built & installed it locally to test it. I could "see" it in the repo, but a project that used it got the above error. What I'd done was set the starter POM to pom, so there was no JAR. Maven was quite correct that it wasn't in Nexus -- but I wasn't expecting it to be, so the error was, ummm, unhelpful. Changing the starter POM to normal packaging & reinstalling fixed the issue.

When to use an interface instead of an abstract class and vice versa?

Personally, I almost never have the need to write abstract classes.

Most times I see abstract classes being (mis)used, it's because the author of the abstract class is using the "Template method" pattern.

The problem with "Template method" is that it's nearly always somewhat re-entrant - the "derived" class knows about not just the "abstract" method of its base class that it is implementing, but also about the public methods of the base class, even though most times it does not need to call them.

(Overly simplified) example:

abstract class QuickSorter
{
    public void Sort(object[] items)
    {
        // implementation code that somewhere along the way calls:
        bool less = compare(x,y);
        // ... more implementation code
    }
    abstract bool compare(object lhs, object rhs);
}

So here, the author of this class has written a generic algorithm and intends for people to use it by "specializing" it by providing their own "hooks" - in this case, a "compare" method.

So the intended usage is something like this:

class NameSorter : QuickSorter
{
    public bool compare(object lhs, object rhs)
    {
        // etc.
    }
}

The problem with this is that you've unduly coupled together two concepts:

  1. A way of comparing two items (what item should go first)
  2. A method of sorting items (i.e. quicksort vs merge sort etc.)

In the above code, theoretically, the author of the "compare" method can re-entrantly call back into the superclass "Sort" method... even though in practise they will never want or need to do this.

The price you pay for this unneeded coupling is that it's hard to change the superclass, and in most OO languages, impossible to change it at runtime.

The alternative method is to use the "Strategy" design pattern instead:

interface IComparator
{
    bool compare(object lhs, object rhs);
}

class QuickSorter
{
    private readonly IComparator comparator;
    public QuickSorter(IComparator comparator)
    {
        this.comparator = comparator;
    }

    public void Sort(object[] items)
    {
        // usual code but call comparator.Compare();
    }
}

class NameComparator : IComparator
{
    bool compare(object lhs, object rhs)
    {
        // same code as before;
    }
}

So notice now: All we have are interfaces, and concrete implementations of those interfaces. In practise, you don't really need anything else to do a high level OO design.

To "hide" the fact that we've implemented "sorting of names" by using a "QuickSort" class and a "NameComparator", we might still write a factory method somewhere:

ISorter CreateNameSorter()
{
    return new QuickSorter(new NameComparator());
}

Any time you have an abstract class you can do this... even when there is a natural re-entrant relationship between the base and derived class, it usually pays to make them explicit.

One final thought: All we've done above is "compose" a "NameSorting" function by using a "QuickSort" function and a "NameComparison" function... in a functional programming language, this style of programming becomes even more natural, with less code.

Center align "span" text inside a div

You are giving the span a 100% width resulting in it expanding to the size of the parent. This means you can’t center-align it, as there is no room to move it.

You could give the span a set width, then add the margin:0 auto again. This would center-align it.

.left 
{
   background-color: #999999;
   height: 50px;
   width: 24.5%;
}
span.panelTitleTxt 
{
   display:block;
   width:100px;
   height: 100%;
   margin: 0 auto;
}

How to assign an exec result to a sql variable?

Here is solution for dynamic queries.

For example if you have more tables with different suffix:

dbo.SOMETHINGTABLE_ONE, dbo.SOMETHINGTABLE_TWO

Code:

DECLARE @INDEX AS NVARCHAR(20)
DECLARE @CheckVALUE AS NVARCHAR(max) = 'SELECT COUNT(SOMETHING) FROM 
dbo.SOMETHINGTABLE_'+@INDEX+''
DECLARE @tempTable Table (TempVALUE int)
DECLARE @RESULTVAL INT

INSERT INTO @tempTable
    EXEC sp_executesql @CheckVALUE

SET @RESULTVAL = (SELECT * FROM @tempTable)

DELETE @tempTable

SELECT @RESULTVAL 

Clearing NSUserDefaults

All above answers are very relevant, but if someone still unable to reset the userdefaults for deleted app, then you can reset the content settings of you simulator, and it will work.enter image description here

Strtotime() doesn't work with dd/mm/YYYY format

If nothing worked, try this.

$date = '25/05/2010'; //dd/mm/YYYY
$dateAr = explode('/',);
$date = $dateAr[2].'-'.$dateAr[1].'-'.$dateAr[0]; //YYYY-mm-dd

How to send data in request body with a GET when using jQuery $.ajax()

You can send your data like the "POST" request through the "HEADERS".

Something like this:

$.ajax({
   url: "htttp://api.com/entity/list($body)",
   type: "GET",
   headers: ['id1':1, 'id2':2, 'id3':3],
   data: "",
   contentType: "text/plain",
   dataType: "json",
   success: onSuccess,
   error: onError
});

How to go back (ctrl+z) in vi/vim

Just in normal mode press:

  • u - undo,
  • Ctrl + r - redo changes which were undone (undo the undos).

Undo and Redo

HTML <input type='file'> File Selection Event

Though it is an old question, it is still a valid one.

Expected behavior:

  • Show selected file name after upload.
  • Do not do anything if the user clicks Cancel.
  • Show the file name even when the user selects the same file.

Code with a demonstration:

_x000D_
_x000D_
<!DOCTYPE html>
<html>

<head>
  <title>File upload event</title>
</head>

<body>
  <form action="" method="POST" enctype="multipart/form-data">
    <input type="file" name="userFile" id="userFile"><br>
    <input type="submit" name="upload_btn" value="upload">
  </form>
  <script type="text/javascript">
    document.getElementById("userFile").onchange = function(e) {
      alert(this.value);
      this.value = null;
    }
  </script>
</body>

</html>
_x000D_
_x000D_
_x000D_

Explanation:

  • The onchange event handler is used to handle any change in file selection event.
  • The onchange event is triggered only when the value of an element is changed. So, when we select the same file using the input field the event will not be triggered. To overcome this, I set this.value = null; at the end of the onchange event function. It sets the file path of the selected file to null. Thus, the onchange event is triggered even at the time of the same file selection.

what is an illegal reflective access

There is an Oracle article I found regarding Java 9 module system

By default, a type in a module is not accessible to other modules unless it’s a public type and you export its package. You expose only the packages you want to expose. With Java 9, this also applies to reflection.

As pointed out in https://stackoverflow.com/a/50251958/134894, the differences between the AccessibleObject#setAccessible for JDK8 and JDK9 are instructive. Specifically, JDK9 added

This method may be used by a caller in class C to enable access to a member of declaring class D if any of the following hold:

  • C and D are in the same module.
  • The member is public and D is public in a package that the module containing D exports to at least the module containing C.
  • The member is protected static, D is public in a package that the module containing D exports to at least the module containing C, and C is a subclass of D.
  • D is in a package that the module containing D opens to at least the module containing C. All packages in unnamed and open modules are open to all modules and so this method always succeeds when D is in an unnamed or open module.

which highlights the significance of modules and their exports (in Java 9)

getResourceAsStream returns null

So there are several ways to get a resource from a jar and each has slightly different syntax where the path needs to be specified differently.

The best explanation I have seen is this article from InfoWorld. I'll summarize here, but if you want to know more you should check out the article.

Methods

  1. ClassLoader.getResourceAsStream().

Format: "/"-separated names; no leading "/" (all names are absolute).

Example: this.getClass().getClassLoader().getResourceAsStream("some/pkg/resource.properties");

  1. Class.getResourceAsStream()

Format: "/"-separated names; leading "/" indicates absolute names; all other names are relative to the class's package

Example: this.getClass().getResourceAsStream("/some/pkg/resource.properties");

Updated Sep 2020: Changed article link. Original article was from Javaworld, it is now hosted on InfoWorld (and has many more ads)

What is the 'new' keyword in JavaScript?

For beginners to understand it better

try out the following code in the browser console.

function Foo() { 
    return this; 
}

var a = Foo();       //returns window object
var b = new Foo();   //returns empty object of foo

a instanceof Window;  // true
a instanceof Foo;     // false

b instanceof Window;  // false
b instanceof Foo;     // true

Now you can read the community wiki answer :)

Xcode Debugger: view value of variable

This gets a little complicated. These objects are custom classes or structs, and looking inside them is not as easy on Xcode as in other development environments.

If I were you, I'd NSLog the values you want to see, with some description.

i.e:

NSLog(@"Description of object & time: %i", indexPath.row);

Generating a random hex color code with PHP

If someone wants to generate light colors

sprintf('#%06X', mt_rand(0xFF9999, 0xFFFF00));

AngularJS UI Router - change url without reloading state

Try something like this

$state.go($state.$current.name, {... $state.params, 'key': newValue}, {notify: false})

Filter values only if not null using lambda in Java8

You can do this in single filter step:

requiredCars = cars.stream().filter(c -> c.getName() != null && c.getName().startsWith("M"));

If you don't want to call getName() several times (for example, it's expensive call), you can do this:

requiredCars = cars.stream().filter(c -> {
    String name = c.getName();
    return name != null && name.startsWith("M");
});

Or in more sophisticated way:

requiredCars = cars.stream().filter(c -> 
    Optional.ofNullable(c.getName()).filter(name -> name.startsWith("M")).isPresent());

How to validate numeric values which may contain dots or commas?

\d{1,2}[\,\.]{1}\d{1,2}

EDIT: update to meet the new requirements (comments) ;)
EDIT: remove unnecesary qtfier as per Bryan

^[0-9]{1,2}([,.][0-9]{1,2})?$

JavaScript string newline character?

Don't use "\n". Just try this:

var string = "this\
is a multi\
line\
string";

Just enter a back-slash and keep on truckin'! Works like a charm.

Regex for allowing alphanumeric,-,_ and space

var regex = new RegExp("^[A-Za-z0-9? ,_-]+$");
            var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
            if (!regex.test(key)) {
                event.preventDefault();
                return false;
            }

in the regExp [A-Za-z0-9?spaceHere,_-] there is a literal space after the question mark '?'. This matches space. Others like /^[-\w\s]+$/ and /^[a-z\d\-_\s]+$/i were not working for me.

asp:TextBox ReadOnly=true or Enabled=false?

Readonly will allow the user to copy text from it. Disabled will not.

How to calculate difference in hours (decimal) between two dates in SQL Server?

Declare @date1 datetime
Declare @date2 datetime

Set @date1 = '11/20/2009 11:00:00 AM'
Set @date2 = '11/20/2009 12:00:00 PM'

Select Cast(DateDiff(hh, @date1, @date2) as decimal(3,2)) as HoursApart

Result = 1.00

Random character generator with a range of (A..Z, 0..9) and punctuation

Why reinvent the wheel? RandomStringUtils from Apache Commons has functions to which you can specify the character set from which characters are generated. You can take what you need to your app:

http://kickjava.com/src/org/apache/commons/lang/RandomStringUtils.java.htm

Show and hide divs at a specific time interval using jQuery

Try this

      $('document').ready(function(){
         window.setTimeout('test()',time in milliseconds);
      });

      function test(){

      $('#divid').hide();

      } 

Resize command prompt through commands

Modify cmd.exe properties using the command prompt Pretty much has what you're asking for. More on the topic, mode con: cols=160 lines=78 should achieve what you want. Change 160 and 78 to your values.

What is special about /dev/tty?

The 'c' means it's a character device. tty is a special file representing the 'controlling terminal' for the current process.

Character Devices

Unix supports 'device files', which aren't really files at all, but file-like access points to hardware devices. A 'character' device is one which is interfaced byte-by-byte (as opposed to buffered IO).

TTY

/dev/tty is a special file, representing the terminal for the current process. So, when you echo 1 > /dev/tty, your message ('1') will appear on your screen. Likewise, when you cat /dev/tty, your subsequent input gets duplicated (until you press Ctrl-C).

/dev/tty doesn't 'contain' anything as such, but you can read from it and write to it (for what it's worth). I can't think of a good use for it, but there are similar files which are very useful for simple IO operations (e.g. /dev/ttyS0 is normally your serial port)

This quote is from http://tldp.org/HOWTO/Text-Terminal-HOWTO-7.html#ss7.3 :

/dev/tty stands for the controlling terminal (if any) for the current process. To find out which tty's are attached to which processes use the "ps -a" command at the shell prompt (command line). Look at the "tty" column. For the shell process you're in, /dev/tty is the terminal you are now using. Type "tty" at the shell prompt to see what it is (see manual pg. tty(1)). /dev/tty is something like a link to the actually terminal device name with some additional features for C-programmers: see the manual page tty(4).

Here is the man page: http://linux.die.net/man/4/tty

How do I compare strings in Java?

String a = new String("foo");
String b = new String("foo");
System.out.println(a == b); // prints false
System.out.println(a.equals(b)); // prints true

Make sure you understand why. It's because the == comparison only compares references; the equals() method does a character-by-character comparison of the contents.

When you call new for a and b, each one gets a new reference that points to the "foo" in the string table. The references are different, but the content is the same.

ADB Driver and Windows 8.1

In Windows 7, 8 or 8.1, in Devices Manager:

  1. Select tree 'Android Device': remove 'Android Composite ADB Interface' [?]
  2. Press on main root of devices tree and call context menu (by right mouse click) and click on 'Update configuration'
  3. After updating your device should appear in 'Other devices'
  4. Select your device, call context menu from it and choose 'Update driver' and perform this updating

C# HttpClient 4.5 multipart/form-data upload

Here is another example on how to use HttpClient to upload a multipart/form-data.

It uploads a file to a REST API and includes the file itself (e.g. a JPG) and additional API parameters. The file is directly uploaded from local disk via FileStream.

See here for the full example including additional API specific logic.

public static async Task UploadFileAsync(string token, string path, string channels)
{
    // we need to send a request with multipart/form-data
    var multiForm = new MultipartFormDataContent();

    // add API method parameters
    multiForm.Add(new StringContent(token), "token");
    multiForm.Add(new StringContent(channels), "channels");

    // add file and directly upload it
    FileStream fs = File.OpenRead(path);
    multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(path));

    // send request to API
    var url = "https://slack.com/api/files.upload";
    var response = await client.PostAsync(url, multiForm);
}

Why do I get the "Unhandled exception type IOException"?

Java has a feature called "checked exceptions". That means that there are certain kinds of exceptions, namely those that subclass Exception but not RuntimeException, such that if a method may throw them, it must list them in its throws declaration, say: void readData() throws IOException. IOException is one of those.

Thus, when you are calling a method that lists IOException in its throws declaration, you must either list it in your own throws declaration or catch it.

The rationale for the presence of checked exceptions is that for some kinds of exceptions, you must not ignore the fact that they may happen, because their happening is quite a regular situation, not a program error. So, the compiler helps you not to forget about the possibility of such an exception being raised and requires you to handle it in some way.

However, not all checked exception classes in Java standard library fit under this rationale, but that's a totally different topic.

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

I just renamed the package and it worked for me.

Or if you are using Ionic, you could delete the application and try again, this happens when ionic detects that the app you are deploying is not coming from the same build. It often happen when you change from pc.

Node.js – events js 72 throw er unhandled 'error' event

Well, your script throws an error and you just need to catch it (and/or prevent it from happening). I had the same error, for me it was an already used port (EADDRINUSE).

Can grep show only words that match search pattern?

To search all the words with start with "icon-" the following command works perfect. I am using Ack here which is similar to grep but with better options and nice formatting.

ack -oh --type=html "\w*icon-\w*" | sort | uniq

Best way to parse command-line parameters?

Here's a scala command line parser that is easy to use. It automatically formats help text, and it converts switch arguments to your desired type. Both short POSIX, and long GNU style switches are supported. Supports switches with required arguments, optional arguments, and multiple value arguments. You can even specify the finite list of acceptable values for a particular switch. Long switch names can be abbreviated on the command line for convenience. Similar to the option parser in the Ruby standard library.

How to use IntelliJ IDEA to find all unused code?

After you've run the Inspect by Name, select all the locations, and make use of the Apply quick fixes to all the problems drop-down, and use either (or both) of Delete unused parameter(s) and Safe Delete.

Don't forget to hit Do Refactor afterwards.

Then you'll need to run another analysis, as the refactored code will no doubt reveal more unused declarations.

Apply quick fixes to all the problems

A valid provisioning profile for this executable was not found... (again)

If none of above stated works then check for your device date, make sure your device date doesn't exceed profile expiry date i.e. not set to far future.

Linux Command History with date and time

It depends on the shell (and its configuration) in standard bash only the command is stored without the date and time (check .bash_history if there is any timestamp there).

To have bash store the timestamp you need to set HISTTIMEFORMAT before executing the commands, e.g. in .bashrc or .bash_profile. This will cause bash to store the timestamps in .bash_history (see the entries starting with #).

C# Enum - How to Compare Value

You should convert the string to an enumeration value before comparing.

Enum.TryParse("Retailer", out AccountType accountType);

Then

if (userProfile?.AccountType == accountType)
{
    //your code
}

How to get selected value of a html select with asp.net

If you would use asp:dropdownlist you could select it easier by testSelect.Text.

Now you'd have to do a Request.Form["testSelect"] to get the value after pressed btnTes.

Hope it helps.

EDIT: You need to specify a name of the select (not only ID) to be able to Request.Form["testSelect"]

Unsuccessful append to an empty NumPy array

numpy.append is pretty different from list.append in python. I know that's thrown off a few programers new to numpy. numpy.append is more like concatenate, it makes a new array and fills it with the values from the old array and the new value(s) to be appended. For example:

import numpy

old = numpy.array([1, 2, 3, 4])
new = numpy.append(old, 5)
print old
# [1, 2, 3, 4]
print new
# [1, 2, 3, 4, 5]
new = numpy.append(new, [6, 7])
print new
# [1, 2, 3, 4, 5, 6, 7]

I think you might be able to achieve your goal by doing something like:

result = numpy.zeros((10,))
result[0:2] = [1, 2]

# Or
result = numpy.zeros((10, 2))
result[0, :] = [1, 2]

Update:

If you need to create a numpy array using loop, and you don't know ahead of time what the final size of the array will be, you can do something like:

import numpy as np

a = np.array([0., 1.])
b = np.array([2., 3.])

temp = []
while True:
    rnd = random.randint(0, 100)
    if rnd > 50:
        temp.append(a)
    else:
        temp.append(b)
    if rnd == 0:
         break

 result = np.array(temp)

In my example result will be an (N, 2) array, where N is the number of times the loop ran, but obviously you can adjust it to your needs.

new update

The error you're seeing has nothing to do with types, it has to do with the shape of the numpy arrays you're trying to concatenate. If you do np.append(a, b) the shapes of a and b need to match. If you append an (2, n) and (n,) you'll get a (3, n) array. Your code is trying to append a (1, 0) to a (2,). Those shapes don't match so you get an error.

How to concatenate strings in django templates?

extends has no facility for this. Either put the entire template path in a context variable and use that, or copy the exist template tag and modify it appropriately.

How to downgrade python from 3.7 to 3.6

If you are working with Anaconda, then

conda install python=3.5.0
# or maybe 
conda install python=2.7.8
# or whatever you want....

might work.

Trigger an event on `click` and `enter`

you can use below event of keypress on document load.

 $(document).keypress(function(e) {
            if(e.which == 13) {
               yourfunction();
            }
        });

Thanks

How do I do base64 encoding on iOS?

As per your requirement i have created a sample demo using Swift 4 in which you can encode/decode string and image as per your requirement.

  • I have also added sample methods of relevant operations.

    //
    //  Base64VC.swift
    //  SOF_SortArrayOfCustomObject
    //
    //  Created by Test User on 09/01/18.
    //  Copyright © 2018 Test User. All rights reserved.
    //
    
    import UIKit
    import Foundation
    
    class Base64VC: NSObject {
    
        //----------------------------------------------------------------
        // MARK:-
        // MARK:- String to Base64 Encode Methods
        //----------------------------------------------------------------
    
        func sampleStringEncodingAndDecoding() {
            if let base64String = self.base64Encode(string: "TestString") {
                print("Base64 Encoded String: \n\(base64String)")
                if let originalString = self.base64Decode(base64String: base64String) {
                    print("Base64 Decoded String: \n\(originalString)")
                }
            }
        }
    
    
        //----------------------------------------------------------------
    
        func base64Encode(string: String) -> String? {
            if let stringData = string.data(using: .utf8) {
                return stringData.base64EncodedString()
            }
            return nil
        }
    
        //----------------------------------------------------------------
    
        func base64Decode(base64String: String) -> String? {
            if let base64Data = Data(base64Encoded: base64String) {
                return String(data: base64Data, encoding: .utf8)
            }
            return nil
        }
    
    
        //----------------------------------------------------------------
        // MARK:-
        // MARK:- Image to Base64 Encode  Methods
        //----------------------------------------------------------------
    
        func sampleImageEncodingAndDecoding() {
            if let base64ImageString = self.base64Encode(image: UIImage.init(named: "yourImageName")!) {
                print("Base64 Encoded Image: \n\(base64ImageString)")
                if let originaImage = self.base64Decode(base64ImageString: base64ImageString) {
                    print("originalImageData \n\(originaImage)")
                }
            }
        }
    
        //----------------------------------------------------------------
    
        func base64Encode(image: UIImage) -> String? {
            if let imageData = UIImagePNGRepresentation(image) {
                return imageData.base64EncodedString()
            }
            return nil
        }
    
        //----------------------------------------------------------------
    
        func base64Decode(base64ImageString: String) -> UIImage? {
            if let base64Data = Data(base64Encoded: base64ImageString) {
                return UIImage(data: base64Data)!
            }
            return nil
        }
    
    
    }
    

Get the ID of a drawable in ImageView

Even easier: just store the R.drawable id in the view's id: use v.setId(). Then get it back with v.getId().

How to run a .jar in mac?

You don't need JDK to run Java based programs. JDK is for development which stands for Java Development Kit.

You need JRE which should be there in Mac.

Try: java -jar Myjar_file.jar

EDIT: According to this article, for Mac OS 10

The Java runtime is no longer installed automatically as part of the OS installation.

Then, you need to install JRE to your machine.

How can I scroll a div to be visible in ReactJS?

With reacts Hooks:

  1. Import
import ReactDOM from 'react-dom';
import React, {useRef} from 'react';
  1. Make new hook:
const divRef = useRef<HTMLDivElement>(null);
  1. Add new Div
<div ref={divRef}/>
  1. Scroll function:
const scrollToDivRef  = () => {
    let node = ReactDOM.findDOMNode(divRef.current) as Element;
    node.scrollIntoView({block: 'start', behavior: 'smooth'});
}

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

Your question is a little unclear...as the part that you indicate you want to bold in Excel is a DataGridView in the import from word method. Do you maybe want to bold the first row in the excel document?

using xl = Microsoft.Office.Interop.Excel;

xl.Range rng = (xl.Range)xlWorkSheet.Rows[0];
rng.Font.Bold = true;

Simple as that!

HTH, Z

Laravel 4: Redirect to a given url

This worked for me in Laravel 5.8

return \Redirect::to('https://bla.com/?yken=KuQxIVTNRctA69VAL6lYMRo0');

Or instead of / you can use

use Redirect;

Cannot import keras after installation

Firstly checked the list of installed Python packages by:

pip list | grep -i keras

If there is keras shown then install it by:

pip install keras --upgrade --log ./pip-keras.log

now check the log, if there is any pending dependencies are present, it will affect your installation. So remove dependencies and then again install it.

Display Animated GIF

Nobody has mentioned the Ion or Glide library. they work very well.

It's easier to handle compared to a WebView.

How to make a loop in x86 assembly language?

mov cx,3

loopstart:
   do stuff
   dec cx          ;Note:  decrementing cx and jumping on result is
   jnz loopstart   ;much faster on Intel (and possibly AMD as I haven't
                   ;tested in maybe 12 years) rather than using loop loopstart

How do I set the rounded corner radius of a color drawable using xml?

mbaird's answer works fine. Just be aware that there seems to be a bug in Android (2.1 at least), that if you set any individual corner's radius to 0, it forces all the corners to 0 (at least that's the case with "dp" units; I didn't try it with any other units).

I needed a shape where the top corners were rounded and the bottom corners were square. I got achieved this by setting the corners I wanted to be square to a value slightly larger than 0: 0.1dp. This still renders as square corners, but it doesn't force the other corners to be 0 radius.

Changing PowerShell's default output encoding to UTF-8

Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.

  • On PSv5.1 or higher, where > and >> are effectively aliases of Out-File, you can set the default encoding for > / >> / Out-File via the $PSDefaultParameterValues preference variable:

    • $PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
  • On PSv5.0 or below, you cannot change the encoding for > / >>, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File.
    (The $PSDefaultParameterValues preference variable was introduced in PSv3.0).

  • On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
    an -Encoding parameter
    (which in PSv5.1+ includes > and >>), use:

    • $PSDefaultParameterValues['*:Encoding'] = 'utf8'

If you place this command in your $PROFILE, cmdlets such as Out-File and Set-Content will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding parameter.

Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues:

  • $PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }

Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.

For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.


The automatic $OutputEncoding variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.


Optional reading: The cross-platform perspective: PowerShell Core:

PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.

  • This means that source-code files without a BOM are assumed to be UTF-8, and using > / Out-File / Set-Content defaults to BOM-less UTF-8; explicit use of the utf8 -Encoding argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom value.

  • If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1 file will typically not have a UTF-8 pseudo-BOM:

    • This works fine on PowerShell Core.
    • It may break on Windows PowerShell, if the file contains non-ASCII characters; if you do need to use non-ASCII characters in your scripts, save them as UTF-8 with BOM.
      Without the BOM, Windows PowerShell (mis)interprets your script as being encoded in the legacy "ANSI" codepage (determined by the system locale for pre-Unicode applications; e.g., Windows-1252 on US-English systems).
  • Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat, sed, and awk - and even some editors such as gedit - to pass the pseudo-BOM through, i.e., to treat it as data.

    • This may not always be a problem, but definitely can be, such as when you try to read a file into a string in bash with, say, text=$(cat file) or text=$(<file) - the resulting variable will contain the pseudo-BOM as the first 3 bytes.

Inconsistent default encoding behavior in Windows PowerShell:

Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.

Note:

  • The following doesn't aspire to cover all standard cmdlets.

  • Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.

  • As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.


Cmdlets that write:

Out-File and > / >> create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content / Add-Content (see next point); New-ModuleManifest and Export-CliXml also create UTF-16LE files.

Set-Content (and Add-Content if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default).

Export-Csv indeed creates ASCII files, as documented, but see the notes re -Append below.

Export-PSSession creates UTF-8 files with BOM by default.

New-Item -Type File -Value currently creates BOM-less(!) UTF-8.

The Send-MailMessage help topic also claims that ASCII encoding is the default - I have not personally verified that claim.

Start-Transcript invariably creates UTF-8 files with BOM, but see the notes re -Append below.

Re commands that append to an existing file:

>> / Out-File -Append make no attempt to match the encoding of a file's existing content. That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding, which is not an option with >> (except indirectly in PSv5.1+, via $PSDefaultParameterValues, as shown above). In short: you must know the encoding of an existing file's content and append using that same encoding.

Add-Content is the laudable exception: in the absence of an explicit -Encoding argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.

This inconsistency between Out-File -Append / >> and Add-Content, which also affects PowerShell Core, is discussed in this GitHub issue.

Export-Csv -Append partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append assumes UTF-8 is, whereas Add-Content assumes ANSI.

Start-Transcript -Append partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.


Cmdlets that read (that is, the encoding used in the absence of a BOM):

Get-Content and Import-PowerShellDataFile default to ANSI (Default), which is consistent with Set-Content.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.

By contrast, Import-Csv, Import-CliXml and Select-String assume UTF-8 in the absence of a BOM.

How can I delete a user in linux when the system says its currently used in a process

restart your computer and run $sudo deluser username... worked for me

Changing default encoding of Python?

Here is a simpler method (hack) that gives you back the setdefaultencoding() function that was deleted from sys:

import sys
# sys.setdefaultencoding() does not exist, here!
reload(sys)  # Reload does the trick!
sys.setdefaultencoding('UTF8')

(Note for Python 3.4+: reload() is in the importlib library.)

This is not a safe thing to do, though: this is obviously a hack, since sys.setdefaultencoding() is purposely removed from sys when Python starts. Reenabling it and changing the default encoding can break code that relies on ASCII being the default (this code can be third-party, which would generally make fixing it impossible or dangerous).

How to write PNG image to string with the PIL?

save() can take a file-like object as well as a path, so you can use an in-memory buffer like a StringIO:

buf = StringIO.StringIO()
im.save(buf, format='JPEG')
jpeg = buf.getvalue()

Using the star sign in grep

The "star sign" is only meaningful if there is something in front of it. If there isn't the tool (grep in this case) may just treat it as an error. For example:

'*xyz'    is meaningless
'a*xyz'   means zero or more occurrences of 'a' followed by xyz

How to compare dates in datetime fields in Postgresql?

When you compare update_date >= '2013-05-03' postgres casts values to the same type to compare values. So your '2013-05-03' was casted to '2013-05-03 00:00:00'.

So for update_date = '2013-05-03 14:45:00' your expression will be that:

'2013-05-03 14:45:00' >= '2013-05-03 00:00:00' AND '2013-05-03 14:45:00' <= '2013-05-03 00:00:00'

This is always false

To solve this problem cast update_date to date:

select * from table where update_date::date >= '2013-05-03' AND update_date::date <= '2013-05-03' -> Will return result

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

The Syntax as specified by Microsoft for the dropping a column part of an ALTER statement is this

 DROP 
 {
     [ CONSTRAINT ] 
     { 
          constraint_name 
          [ WITH 
           ( <drop_clustered_constraint_option> [ ,...n ] ) 
          ] 
      } [ ,...n ]
      | COLUMN 
      {
          column_name 
      } [ ,...n ]
 } [ ,...n ]

Notice that the [,...n] appears after both the column name and at the end of the whole drop clause. What this means is that there are two ways to delete multiple columns. You can either do this:

ALTER TABLE TableName
    DROP COLUMN Column1, Column2, Column3

or this

ALTER TABLE TableName
    DROP 
        COLUMN Column1,
        COLUMN Column2,
        COLUMN Column3

This second syntax is useful if you want to combine the drop of a column with dropping a constraint:

ALTER TBALE TableName
    DROP
        CONSTRAINT DF_TableName_Column1,
        COLUMN Column1;

When dropping columns SQL Sever does not reclaim the space taken up by the columns dropped. For data types that are stored inline in the rows (int for example) it may even take up space on the new rows added after the alter statement. To get around this you need to create a clustered index on the table or rebuild the clustered index if it already has one. Rebuilding the index can be done with a REBUILD command after modifying the table. But be warned this can be slow on very big tables. For example:

ALTER TABLE Test
    REBUILD;

Scroll RecyclerView to show selected item on top

Try what worked for me cool!

Create a variable private static int displayedposition = 0;

Now for the position of your RecyclerView in your Activity.

myRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                LinearLayoutManager llm = (LinearLayoutManager) myRecyclerView.getLayoutManager();


                displayedposition = llm.findFirstVisibleItemPosition();


            }
        });

Place this statement where you want it to place the former site displayed in your view .

LinearLayoutManager llm = (LinearLayoutManager) mRecyclerView.getLayoutManager();
        llm.scrollToPositionWithOffset(displayedposition , youList.size());

Well that's it , it worked fine for me \o/

How to create enum like type in TypeScript?

Just another note that you can a id/string enum with the following:

class EnumyObjects{
    public static BOUNCE={str:"Bounce",id:1};
    public static DROP={str:"Drop",id:2};
    public static FALL={str:"Fall",id:3};


}

Open existing file, append a single line

Choice one! But the first is very simple. The last maybe util for file manipulation:

//Method 1 (I like this)
File.AppendAllLines(
    "FileAppendAllLines.txt", 
    new string[] { "line1", "line2", "line3" });

//Method 2
File.AppendAllText(
    "FileAppendAllText.txt",
    "line1" + Environment.NewLine +
    "line2" + Environment.NewLine +
    "line3" + Environment.NewLine);

//Method 3
using (StreamWriter stream = File.AppendText("FileAppendText.txt"))
{
    stream.WriteLine("line1");
    stream.WriteLine("line2");
    stream.WriteLine("line3");
}

//Method 4
using (StreamWriter stream = new StreamWriter("StreamWriter.txt", true))
{
    stream.WriteLine("line1");
    stream.WriteLine("line2");
    stream.WriteLine("line3");
}

//Method 5
using (StreamWriter stream = new FileInfo("FileInfo.txt").AppendText())
{
    stream.WriteLine("line1");
    stream.WriteLine("line2");
    stream.WriteLine("line3");
}

Jquery sortable 'change' event element position

$( "#sortable" ).sortable({
    change: function(event, ui) {       
        var pos = ui.helper.index() < ui.placeholder.index() 
            ? { start: ui.helper.index(), end: ui.placeholder.index() }
            : { start: ui.placeholder.index(), end: ui.helper.index() }

        $(this)
            .children().removeClass( 'highlight' )
            .not( ui.helper ).slice( pos.start, pos.end ).addClass( 'highlight' );
    },
    stop: function(event, ui) {
        $(this).children().removeClass( 'highlight' );
    }
});

FIDDLE

An example of how it could be done inside change event without storing arbitrary data into element storage. Since the element where drag starts is ui.helper, and the element of current position is ui.placeholder, we can take the elements between those two indexes and highlight them. Also, we can use this inside handler since it refers to the element that the widget is attached. The example works with dragging in both directions.

Trying to fire the onload event on script tag

You should set the src attribute after the onload event, f.ex:

el.onload = function() { //...
el.src = script;

You should also append the script to the DOM before attaching the onload event:

$body.append(el);
el.onload = function() { //...
el.src = script;

Remember that you need to check readystate for IE support. If you are using jQuery, you can also try the getScript() method: http://api.jquery.com/jQuery.getScript/

The listener supports no services

You need to add your ORACLE_HOME definition in your listener.ora file. Right now its not registered with any ORACLE_HOME.

Sample listener.ora

abc =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = abc.kma.com)(PORT = 1521))
    )
  )

SID_LIST_abc =
  (SID_LIST =
    (SID_DESC =
      (ORACLE_HOME= /abc/DbTier/11.2.0)
      (SID_NAME = abc)
    )
  )

How do I ignore files in Subversion?

  1. open you use JetBrains Product(i.e. Pycharm)
  2. then click the 'commit' button on the top toolbar or use shortcut 'ctrl + k' screenshot_toolbar
  3. on the commit interface, move your unwanted files to another change list as follows. screenshot_commit_change
  4. next time you can only commit default change list.

Git commit in terminal opens VIM, but can't get back to terminal

You need to return to normal mode and save the commit message with either

<Esc>:wq

or

<Esc>:x

or

<Esc>ZZ

The Esc key returns you from insert mode to normal mode. The :wq, :x or ZZ sequence writes the changes and exits the editor.

Converting serial port data to TCP/IP in a Linux environment

You might find Perl or Python useful to get data from the serial port. To send data to the server, the solution could be easy if the server is (let's say) an HTTP application or even a popular database. The solution would be not so easy if it is some custom/proprietary TCP application.

How can I make a SQL temp table with primary key and auto-incrementing field?

You are just missing the words "primary key" as far as I can see to meet your specified objective.

For your other columns it's best to explicitly define whether they should be NULL or NOT NULL though so you are not relying on the ANSI_NULL_DFLT_ON setting.

CREATE TABLE #tmp
(
ID INT IDENTITY(1, 1) primary key ,
AssignedTo NVARCHAR(100),
AltBusinessSeverity NVARCHAR(100),
DefectCount int
);

insert into #tmp 
select 'user','high',5 union all
select 'user','med',4


select * from #tmp

How to debug a GLSL shader?

You can try this: https://github.com/msqrt/shader-printf which is an implementation called appropriately "Simple printf functionality for GLSL."

You might also want to try ShaderToy, and maybe watch a video like this one (https://youtu.be/EBrAdahFtuo) from "The Art of Code" YouTube channel where you can see some of the techniques that work well for debugging and visualising. I can strongly recommend his channel as he writes some really good stuff and he also has a knack for presenting complex ideas in novel, highly engaging and and easy to digest formats (His Mandelbrot video is a superb example of exactly that : https://youtu.be/6IWXkV82oyY)

I hope nobody minds this late reply, but the question ranks high on Google searches for GLSL debugging and much has of course changed in 9 years :-)

PS: Other alternatives could also be NVIDIA nSight and AMD ShaderAnalyzer which offer a full stepping debugger for shaders.

Why can't radio buttons be "readonly"?

I found that use onclick='this.checked = false;' worked to a certain extent. A radio button that was clicked would not be selected. However, if there was a radio button that was already selected (e.g., a default value), that radio button would become unselected.

<!-- didn't completely work -->
<input type="radio" name="r1" id="r1" value="N" checked="checked" onclick='this.checked = false;'>N</input>
<input type="radio" name="r1" id="r1" value="Y" onclick='this.checked = false;'>Y</input>

For this scenario, leaving the default value alone and disabling the other radio button(s) preserves the already selected radio button and prevents it from being unselected.

<!-- preserves pre-selected value -->
<input type="radio" name="r1" id="r1" value="N" checked="checked">N</input>
<input type="radio" name="r1" id="r1" value="Y" disabled>Y</input>

This solution is not the most elegant way of preventing the default value from being changed, but it will work whether or not javascript is enabled.

In CSS what is the difference between "." and "#" when declaring a set of styles?

A couple of quick extensions on what has already been said...

An id must be unique, but you can use the same id to make different styles more specific.

For example, given this HTML extract:

<div id="sidebar">
    <h2>Heading</h2>
    <ul class="menu">
        ...
    </ul>
</div>
<div id="content">
    <h2>Heading</h2>
    ...
</div>
<div id="footer">
    <ul class="menu">
        ...
    </ul>
</div>

You could apply different styles with these:

#sidebar h2
{ ... }

#sidebar .menu
{ ... }

#content h2
{ ... }

#footer .menu
{ ... }


Another useful thing to know: you can have multiple classes on an element, by space-delimiting them...

<ul class="main menu">...</ul>
<ul class="other menu">...</ul>

Which allows you to have common styling in .menu with specific styles using .main.menu and .sub.menu

.menu
{ ... }

.main.menu
{ ... }

.other.menu
{ ... }

angularjs - ng-repeat: access key and value from JSON array object

You've got an array of objects, so you'll need to use ng-repeat twice, like:

<ul ng-repeat="item in items">
  <li ng-repeat="(key, val) in item">
    {{key}}: {{val}}
  </li>
</ul>

Example: http://jsfiddle.net/Vwsej/

Edit:

Note that properties order in objects are not guaranteed.

<table>
    <tr>
        <th ng-repeat="(key, val) in items[0]">{{key}}</th>
    </tr>
    <tr ng-repeat="item in items">
        <td ng-repeat="(key, val) in item">{{val}}</td>
    </tr>
</table>

Example: http://jsfiddle.net/Vwsej/2/

How can I pass a list as a command-line argument with argparse?

Using nargs parameter in argparse's add_argument method

I use nargs='*' as an add_argument parameter. I specifically used nargs='*' to the option to pick defaults if I am not passing any explicit arguments

Including a code snippet as example:

Example: temp_args1.py

Please Note: The below sample code is written in python3. By changing the print statement format, can run in python2

#!/usr/local/bin/python3.6

from argparse import ArgumentParser

description = 'testing for passing multiple arguments and to get list of args'
parser = ArgumentParser(description=description)
parser.add_argument('-i', '--item', action='store', dest='alist',
                    type=str, nargs='*', default=['item1', 'item2', 'item3'],
                    help="Examples: -i item1 item2, -i item3")
opts = parser.parse_args()

print("List of items: {}".format(opts.alist))

Note: I am collecting multiple string arguments that gets stored in the list - opts.alist If you want list of integers, change the type parameter on parser.add_argument to int

Execution Result:

python3.6 temp_agrs1.py -i item5 item6 item7
List of items: ['item5', 'item6', 'item7']

python3.6 temp_agrs1.py -i item10
List of items: ['item10']

python3.6 temp_agrs1.py
List of items: ['item1', 'item2', 'item3']

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

in the end of your Index.js need to add this Code:

_x000D_
_x000D_
import React from 'react';_x000D_
import ReactDOM from 'react-dom';_x000D_
import { BrowserRouter  } from 'react-router-dom';_x000D_
_x000D_
import './index.css';_x000D_
import App from './App';_x000D_
_x000D_
import { Provider } from 'react-redux';_x000D_
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';_x000D_
import thunk from 'redux-thunk';_x000D_
_x000D_
///its your redux ex_x000D_
import productReducer from './redux/reducer/admin/product/produt.reducer.js'_x000D_
_x000D_
const rootReducer = combineReducers({_x000D_
    adminProduct: productReducer_x000D_
   _x000D_
})_x000D_
const composeEnhancers = window._REDUX_DEVTOOLS_EXTENSION_COMPOSE_ || compose;_x000D_
const store = createStore(rootReducer, composeEnhancers(applyMiddleware(thunk)));_x000D_
_x000D_
_x000D_
const app = (_x000D_
    <Provider store={store}>_x000D_
        <BrowserRouter   basename='/'>_x000D_
            <App />_x000D_
        </BrowserRouter >_x000D_
    </Provider>_x000D_
);_x000D_
ReactDOM.render(app, document.getElementById('root'));
_x000D_
_x000D_
_x000D_

Trying to mock datetime.date.today(), but not working

I implemented @user3016183 method using a custom decorator:

def changeNow(func, newNow = datetime(2015, 11, 23, 12, 00, 00)):
    """decorator used to change datetime.datetime.now() in the tested function."""
    def retfunc(self):                             
        with mock.patch('mymodule.datetime') as mock_date:                         
            mock_date.now.return_value = newNow
            mock_date.side_effect = lambda *args, **kw: datetime(*args, **kw)
            func(self)
    return retfunc

I thought that might help someone one day...

Java 8 Lambda function that throws exception?

This is not specific to Java 8. You are trying to compile something equivalent to:

interface I {
    void m();
}
class C implements I {
    public void m() throws Exception {} //can't compile
}

Property 'value' does not exist on type 'Readonly<{}>'

The problem is you haven't declared your interface state replace any with your suitable variable type of the 'value'

Here is a good reference

interface AppProps {
   //code related to your props goes here
}

interface AppState {
   value: any
}

class App extends React.Component<AppProps, AppState> {
  // ...
}

How to get the index of a maximum element in a NumPy array along one axis

argmax() will only return the first occurrence for each row. http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html

If you ever need to do this for a shaped array, this works better than unravel:

import numpy as np
a = np.array([[1,2,3], [4,3,1]])  # Can be of any shape
indices = np.where(a == a.max())

You can also change your conditions:

indices = np.where(a >= 1.5)

The above gives you results in the form that you asked for. Alternatively, you can convert to a list of x,y coordinates by:

x_y_coords =  zip(indices[0], indices[1])

How to replace � in a string

Use the unicode escape sequence. First you'll have to find the codepoint for the character you seek to replace (let's just say it is ABCD in hex):

str = str.replaceAll("\uABCD", "");

Getting a 'source: not found' error when using source in a bash script

In Ubuntu if you execute the script with sh scriptname.sh you get this problem.

Try executing the script with ./scriptname.sh instead.

How do I specify different layouts for portrait and landscape orientations?

Create a new directory layout-land, then create xml file with same name in layout-land as it was layout directory and align there your content for Landscape mode.

Note that id of content in both xml is same.

The name 'InitializeComponent' does not exist in the current context

Another possible explanation is that you're building against x86. Right-click your Solution and choose Configuration Manager. See if you're building against x86 instead of Any CPU.

Regular expression for a hexadecimal number?

If you're using Perl or PHP, you can replace

[0-9a-fA-F]

with:

[[:xdigit:]]

SQL select everything in an array

SELECT * FROM products WHERE catid IN ('1', '2', '3', '4')

How to enable C++11 in Qt Creator?

add to your qmake file

QMAKE_CXXFLAGS+= -std=c++11
QMAKE_LFLAGS +=  -std=c++11

Get List of connected USB Devices

Add a reference to System.Management for your project, then try something like this:

namespace ConsoleApplication1
{
  using System;
  using System.Collections.Generic;
  using System.Management; // need to add System.Management to your project references.

  class Program
  {
    static void Main(string[] args)
    {
      var usbDevices = GetUSBDevices();

      foreach (var usbDevice in usbDevices)
      {
        Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}",
            usbDevice.DeviceID, usbDevice.PnpDeviceID, usbDevice.Description);
      }

      Console.Read();
    }

    static List<USBDeviceInfo> GetUSBDevices()
    {
      List<USBDeviceInfo> devices = new List<USBDeviceInfo>();

      ManagementObjectCollection collection;
      using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub"))
        collection = searcher.Get();      

      foreach (var device in collection)
      {
        devices.Add(new USBDeviceInfo(
        (string)device.GetPropertyValue("DeviceID"),
        (string)device.GetPropertyValue("PNPDeviceID"),
        (string)device.GetPropertyValue("Description")
        ));
      }

      collection.Dispose();
      return devices;
    }
  }

  class USBDeviceInfo
  {
    public USBDeviceInfo(string deviceID, string pnpDeviceID, string description)
    {
      this.DeviceID = deviceID;
      this.PnpDeviceID = pnpDeviceID;
      this.Description = description;
    }
    public string DeviceID { get; private set; }
    public string PnpDeviceID { get; private set; }
    public string Description { get; private set; }
  }
}

How to check if a variable is a dictionary in Python?

The OP did not exclude the starting variable, so for completeness here is how to handle the generic case of processing a supposed dictionary that may include items as dictionaries.

Also following the pure Python(3.8) recommended way to test for dictionary in the above comments.

from collections.abc import Mapping

dict = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}

def parse_dict(in_dict): 
    if isinstance(in_dict, Mapping):
        for k_outer, v_outer in in_dict.items():
            if isinstance(v_outer, Mapping):
                for k_inner, v_inner in v_outer.items():
                    print(k_inner, v_inner)
            else:
                print(k_outer, v_outer)

parse_dict(dict)

How to center cell contents of a LaTeX table whose columns have fixed widths?

\usepackage{array} in the preamble

then this:

\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}

note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"

Regex pattern including all special characters

Please use this.. it is simplest.

\p{Punct} Punctuation: One of !"#$%&'()*+,-./:;<=>?@[]^_`{|}~

https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

    StringBuilder builder = new StringBuilder(checkstring);
    String regex = "\\p{Punct}"; //Special character : `~!@#$%^&*()-_+=\|}{]["';:/?.,><
    //change your all special characters to "" 
    Pattern  pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(builder.toString());
    checkstring=matcher.replaceAll("");

Is the sizeof(some pointer) always equal to four?

Size of pointer and int is 2 bytes in Turbo C compiler on windows 32 bit machine.

So size of pointer is compiler specific. But generally most of the compilers are implemented to support 4 byte pointer variable in 32 bit and 8 byte pointer variable in 64 bit machine).

So size of pointer is not same in all machines.

MySQL: ignore errors when importing?

Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

For example:

mysql -u userName -p -f -D dbName < script.sql

One time page refresh after first page load

I'd say use hash, like this:

window.onload = function() {
    if(!window.location.hash) {
        window.location = window.location + '#loaded';
        window.location.reload();
    }
}

How to parse the AndroidManifest.xml file inside an .apk package

You can use axml2xml.pl tool developed a while ago within android-random project. It will generate the textual manifest file (AndroidManifest.xml) from the binary one.

I'm saying "textual" and not "original" because like many reverse-engineering tools this one isn't perfect and the result will not be complete. I presume either it was never feature complete or simply not forward-compatible (with newer binary encoding scheme). Whatever the reason, axml2xml.pl tool will not be able to extract all the attribute values correctly. Such attributes are minSdkVersion, targetSdkVersion and basically all attributes that are referencing resources (like strings, icons, etc.), i.e. only class names (of activities, services, etc.) are extracted correctly.

However, you can still find these missing information by running aapt tool on the original Android app file (.apk):

aapt l -a <someapp.apk>

resource error in android studio after update: No Resource Found

I noticed I didn't have sdk 23 installed. So I first installed it then re-built my project. And it worked fine. Also compilesdkVersion should be 23

proper name for python * operator?

One can also call * a gather parameter (when used in function arguments definition) or a scatter operator (when used at function invocation).

As seen here: Think Python/Tuples/Variable-length argument tuples.

Cast from VARCHAR to INT - MySQL

As described in Cast Functions and Operators:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

Therefore, you should use:

SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT

Why does this CSS margin-top style not work?

If you add any padding to #outer, it works.

Demo

#outer {
    width:500px; 
    height:200px; 
    background:#FFCCCC;
    margin:50px auto 0 auto;
    display:block;
    padding-top:1px;
}

String split on new line, tab and some number of spaces

If you look at the documentation for str.split:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

In other words, if you're trying to figure out what to pass to split to get '\n\tName: Jane Smith' to ['Name:', 'Jane', 'Smith'], just pass nothing (or None).

This almost solves your whole problem. There are two parts left.

First, you've only got two fields, the second of which can contain spaces. So, you only want one split, not as many as possible. So:

s.split(None, 1)

Next, you've still got those pesky colons. But you don't need to split on them. At least given the data you've shown us, the colon always appears at the end of the first field, with no space before and always space after, so you can just remove it:

key, value = s.split(None, 1)
key = key[:-1]

There are a million other ways to do this, of course; this is just the one that seems closest to what you were already trying.

Reversing a string in C

You can put your (len/2) test in the for loop:

for(i = 0,k=len-1 ; i < (len/2); i++,k--)
{
        temp = str[k];
        str[k] = str[i];
        str[i] = temp;

}

Submit form with Enter key without submit button?

$("input").keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
        $("form").submit();
    }
});

How to check for the type of a template parameter?

Use is_same:

#include <type_traits>

template <typename T>
void foo()
{
    if (std::is_same<T, animal>::value) { /* ... */ }  // optimizable...
}

Usually, that's a totally unworkable design, though, and you really want to specialize:

template <typename T> void foo() { /* generic implementation  */ }

template <> void foo<animal>()   { /* specific for T = animal */ }

Note also that it's unusual to have function templates with explicit (non-deduced) arguments. It's not unheard of, but often there are better approaches.

Why use double indirection? or Why use pointers to pointers?

Why double pointers?

The objective is to change what studentA points to, using a function.

#include <stdio.h>
#include <stdlib.h>


typedef struct Person{
    char * name;
} Person; 

/**
 * we need a ponter to a pointer, example: &studentA
 */
void change(Person ** x, Person * y){
    *x = y; // since x is a pointer to a pointer, we access its value: a pointer to a Person struct.
}

void dontChange(Person * x, Person * y){
    x = y;
}

int main()
{

    Person * studentA = (Person *)malloc(sizeof(Person));
    studentA->name = "brian";

    Person * studentB = (Person *)malloc(sizeof(Person));
    studentB->name = "erich";

    /**
     * we could have done the job as simple as this!
     * but we need more work if we want to use a function to do the job!
     */
    // studentA = studentB;

    printf("1. studentA = %s (not changed)\n", studentA->name);

    dontChange(studentA, studentB);
    printf("2. studentA = %s (not changed)\n", studentA->name);

    change(&studentA, studentB);
    printf("3. studentA = %s (changed!)\n", studentA->name);

    return 0;
}

/**
 * OUTPUT:
 * 1. studentA = brian (not changed)
 * 2. studentA = brian (not changed)
 * 3. studentA = erich (changed!)
 */

How can I get a uitableViewCell by indexPath?

Here is a code to get custom cell from index path

 NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
 YourCell *cell = (YourCell *)[tblRegister cellForRowAtIndexPath:indexPath];

For Swift

let indexpath = NSIndexPath(forRow: 2, inSection: 0)
let currentCell = tblTest.cellForRowAtIndexPath(indexpath) as! CellTest

For Swift 4 (for collectionview)

let indexpath = NSIndexPath(row: 2, section: 0)
let cell = self.colVw!.cellForItem(at: indexpath as IndexPath) as? ColViewCell

Change background of LinearLayout in Android

 android:background="@drawable/ic_launcher"

should be included inside Layout tab. where ic_launcher is image name that u can put inside project folder/res/drawable . you can copy any number of images and make it as background

How to convert between bytes and strings in Python 3?

TRY THIS:

StringVariable=ByteVariable.decode('UTF-8','ignore')

TO TEST TYPE:

print(type(StringVariable))

Here 'StringVariable' represented as a string. 'ByteVariable' represent as Byte. Its not relevent to question Variables..

Primitive type 'short' - casting in Java

In C# and Java, the arithmatic expression on the right hand side of the assignment evaluates to int by default. That's why you need to cast back to a short, because there is no implicit conversion form int to short, for obvious reasons.

How to resolve "The requested URL was rejected. Please consult with your administrator." error?

I have faced the same issue using Google Chrome browser. Same website was opening normally using the incognito mode and different browsers. At first, I cleared cached files and cookies over the past 24 hours, but this didn't help.

I realized that my first visit to the website was during the past 10 days. So, I cleared cached files and cookies over the past 4 weeks and that resolved the problem.
Note: I didn't clear my browsing history data

How remove border around image in css?

I realize this is a very old post, but I encountered a similar issue in which my displayed image always had a border around it. I was trying to fill the browser window with a single image. Adding styles like border:none; did not remove the border and neither did margin:0; or padding:0; or any combination of the three.

However, adding position:absolute;top:0;left:0; fixed the problem.

The original post above has position:absolute; but does not have top:0;left:0; and this was adding a default border on my page.

To illustrate the solution, this has a white border (to be precise, it has a top and left offset):

<img src="filename.jpg"
style="width:100%;height:100%;position:absolute;">

This does not have a border:

<img src="filename.jpg"
style="width:100%;height:100%;position:absolute;top:0;left:0;">

Hopefully this helps someone finding this post looking to resolve a similar problem.

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

I had same issue, and for me, I was trying to use an IP Address instead of computer name. Just adding this as one more potential solution for people finding this down the road.

Unable to create a constant value of type Only primitive types or enumeration types are supported in this context

It's worth adding, since the OP's code sample doesn't provide enough context to prove otherwise, but I received this error as well on the following code:

public RetailSale GetByRefersToRetailSaleId(Int32 refersToRetailSaleId)
{
    return GetQueryable()
        .FirstOrDefault(x => x.RefersToRetailSaleId.Equals(refersToRetailSaleId));
}

Apparently, I cannot use Int32.Equals in this context to compare an Int32 with a primitive int; I had to (safely) change to this:

public RetailSale GetByRefersToRetailSaleId(Int32 refersToRetailSaleId)
{
    return GetQueryable()
      .FirstOrDefault(x => x.RefersToRetailSaleId == refersToRetailSaleId);
}

Check last modified date of file in C#

Be aware that the function File.GetLastWriteTime does not always work as expected, the values are sometimes not instantaneously updated by the OS. You may get an old Timestamp, even if the file has been modified right before.

The behaviour may vary between OS versions. For example, this unit test worked well every time on my developer machine, but it always fails on our build server.

  [TestMethod]
  public void TestLastModifiedTimeStamps()
  {
     var tempFile = Path.GetTempFileName();
     var lastModified = File.GetLastWriteTime(tempFile);
     using (new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None))
     {

     }
     Assert.AreNotEqual(lastModified, File.GetLastWriteTime(tempFile));
  }

See File.GetLastWriteTime seems to be returning 'out of date' value

Your options:

a) live with the occasional omissions.

b) Build up an active component realising the observer pattern (eg. a tcp server client structure), communicating the changes directly instead of writing / reading files. Fast and flexible, but another dependency and a possible point of failure (and some work, of course).

c) Ensure the signalling process by replacing the content of a dedicated signal file that other processes regularly read. It´s not that smart as it´s a polling procedure and has a greater overhead than calling File.GetLastWriteTime, but if not checking the content from too many places too often, it will do the work.

/// <summary>
/// type to set signals or check for them using a central file 
/// </summary>
public class FileSignal
{
    /// <summary>
    /// path to the central file for signal control
    /// </summary>
    public string FilePath { get; private set; }

    /// <summary>
    /// numbers of retries when not able to retrieve (exclusive) file access
    /// </summary>
    public int MaxCollisions { get; private set; }

    /// <summary>
    /// timespan to wait until next try
    /// </summary>
    public TimeSpan SleepOnCollisionInterval { get; private set; }

    /// <summary>
    /// Timestamp of the last signal
    /// </summary>
    public DateTime LastSignal { get; private set; }

    /// <summary>
    /// constructor
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>
    /// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>
    /// <param name="sleepOnCollisionInterval">timespan to wait until next try </param>
    public FileSignal(string filePath, int maxCollisions, TimeSpan sleepOnCollisionInterval)
    {
        FilePath = filePath;
        MaxCollisions = maxCollisions;
        SleepOnCollisionInterval = sleepOnCollisionInterval;
        LastSignal = GetSignalTimeStamp();
    }

    /// <summary>
    /// constructor using a default value of 50 ms for sleepOnCollisionInterval
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>
    /// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>        
    public FileSignal(string filePath, int maxCollisions): this (filePath, maxCollisions, TimeSpan.FromMilliseconds(50))
    {
    }

    /// <summary>
    /// constructor using a default value of 50 ms for sleepOnCollisionInterval and a default value of 10 for maxCollisions
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>        
    public FileSignal(string filePath) : this(filePath, 10)
    {
    }

    private Stream GetFileStream(FileAccess fileAccess)
    {
        var i = 0;
        while (true)
        {
            try
            {
                return new FileStream(FilePath, FileMode.Create, fileAccess, FileShare.None);
            }
            catch (Exception e)
            {
                i++;
                if (i >= MaxCollisions)
                {
                    throw e;
                }
                Thread.Sleep(SleepOnCollisionInterval);
            };
        };
    }

    private DateTime GetSignalTimeStamp()
    {
        if (!File.Exists(FilePath))
        {
            return DateTime.MinValue;
        }
        using (var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.None))
        {
            if(stream.Length == 0)
            {
                return DateTime.MinValue;
            }
            using (var reader = new BinaryReader(stream))
            {
                return DateTime.FromBinary(reader.ReadInt64());
            };                
        }
    }

    /// <summary>
    /// overwrites the existing central file and writes the current time into it.
    /// </summary>
    public void Signal()
    {
        LastSignal = DateTime.Now;
        using (var stream = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            using (var writer = new BinaryWriter(stream))
            {
                writer.Write(LastSignal.ToBinary());
            }
        }
    }

    /// <summary>
    /// returns true if the file signal has changed, otherwise false.
    /// </summary>        
    public bool CheckIfSignalled()
    {
        var signal = GetSignalTimeStamp();
        var signalTimestampChanged = LastSignal != signal;
        LastSignal = signal;
        return signalTimestampChanged;
    }
}

Some tests for it:

    [TestMethod]
    public void TestSignal()
    {
        var fileSignal = new FileSignal(Path.GetTempFileName());
        var fileSignal2 = new FileSignal(fileSignal.FilePath);
        Assert.IsFalse(fileSignal.CheckIfSignalled());
        Assert.IsFalse(fileSignal2.CheckIfSignalled());
        Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        fileSignal.Signal();
        Assert.IsFalse(fileSignal.CheckIfSignalled());
        Assert.AreNotEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        Assert.IsTrue(fileSignal2.CheckIfSignalled());
        Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        Assert.IsFalse(fileSignal2.CheckIfSignalled());
    }

Django: List field in model?

If you are using Google App Engine or MongoDB as your backend, and you are using the djangoappengine library, there is a built in ListField that does exactly what you want. Further, it's easy to query the Listfield to find all objects that contain an element in the list.

filter items in a python dictionary where keys contain a specific string

input = {"A":"a", "B":"b", "C":"c"}
output = {k:v for (k,v) in input.items() if key_satifies_condition(k)}

jQuery - find table row containing table cell containing specific text

You can use filter() to do that:

var tableRow = $("td").filter(function() {
    return $(this).text() == "foo";
}).closest("tr");

change cursor from block or rectangle to line?

If you happen to be using a mac keyboard on linux (ubuntu), Insert is actually fn + return. You can also click on the zero of the number pad to switch between the cursor types.

Took me a while to figure that out. :-P

jQuery DataTables: control table width

Check this solution too. this solved my DataTable column width issue easily

JQuery DataTables 1.10.20 introduces columns.adjust() method which fix Bootstrap toggle tab issue

 $('a[data-toggle="tab"]').on( 'shown.bs.tab', function (e) {
    $.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
} );

Please refer the documentation : Scrolling and Bootstrap tabs

How to get last month/year in java?

The simplest & least error prone approach is... Use Calendar's roll() method. Like this:

    c.roll(Calendar.MONTH, false);

the roll method takes a boolean, which basically means roll the month up(true) or down(false)?

Why rgb and not cmy?

The difference lies in whether mixing colours results in LIGHTER or DARKER colours. When mixing light, the result is a lighter colour, so mixing red light and blue light becomes a lighter pink. When mixing paint (or ink), red and blue become a darker purple. Mixing paint results in DARKER colours, whereas mixing light results in LIGHTER colours. Therefore for paint the primary colours are Red Yellow Blue (or Cyan Magenta Yellow) as you stated. Yet for light the primary colours are Red Green Blue. It is (virtually) impossible to mix Red Green Blue paint into Yellow paint, or mixing Red Yellow Blue light into Green light.

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

In my case, because I had reinstalled iis, I needed to register iis with dot net 4 using this command:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i

How to center content in a bootstrap column?

No need to complicate things. With Bootstrap 4, you can simply align items horizontally inside a column using the margin auto class my-auto

         <div class="col-md-6 my-auto">
           <h3>Lorem ipsum.</h3>
         </div>

jQuery .scrollTop(); + animation

you can use both CSS class or HTML id, for keeping it symmetric I always use CSS class for example

<a class="btn btn-full js--scroll-to-plans" href="#">I’m hungry</a> 
|
|
|
<section class="section-plans js--section-plans clearfix">

$(document).ready(function () {
    $('.js--scroll-to-plans').click(function () {
        $('body,html').animate({
            scrollTop: $('.js--section-plans').offset().top
        }, 1000);
        return false;})
});

The requested URL /about was not found on this server

change only .htaccess:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Eclipse keyboard shortcut to indent source code to the left?

You can use Ctrl + Shift + F which will run your formatter on the file and fix indentations along the way also.

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

Just start your browser with superuser rights, and don't forget to set Java's JRE security to medium.

Parsing GET request parameters in a URL that contains another URL

I had a similar problem and ended up using parse_url and parse_str, which as long as the URL in the parameter is correctly url encoded (which it definitely should) allows you to access both all the parameters of the actual URL, as well as the parameters of the encoded URL in the query parameter, like so:

$get_url = "http://google.com/?var=234&key=234";
$my_url = "http://localhost/test.php?id=" . urlencode($get_url);

function so_5645412_url_params($url) {
    $url_comps = parse_url($url);
    $query = $url_comps['query'];

    $args = array();
    parse_str($query, $args);

    return $args;
}

$my_url_args = so_5645412_url_params($my_url); // Array ( [id] => http://google.com/?var=234&key=234 )
$get_url_args = so_5645412_url_params($my_url_args['id']); // Array ( [var] => 234, [key] => 234 )

jQuery UI DatePicker to show month year only

If anyone want that also for multiple calendars its not very hard to add this functionallity to jquery ui. with minified search for:

x+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+t+'">'+(/all|left/.test(t)&&C==0?c?f:n:"")+(

add this in front of x

var accl = ''; if(this._get(a,"justMonth")) {accl = ' ui-datepicker-just_month';}

search for

<table class="ui-datepicker-calendar

and replace it with

<table class="ui-datepicker-calendar'+accl+'

also search for

this._defaults={

replace it with

this._defaults={justMonth:false,

for css you should use:

.ui-datepicker table.ui-datepicker-just_month{
    display: none;
}

after that all is done just go to your desired datepicker init functions and provide setting var

$('#txt_month_chart_view').datepicker({
    changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'MM yy',
        justMonth: true,
        create: function(input, inst) {
            $(".ui-datepicker table").addClass("badbad");
        },
        onClose: function(dateText, inst) {
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(year, month, 1));
        }
});

justMonth: true is the key here :)

What are Covering Indexes and Covered Queries in SQL Server?

When I simply recalled that a Clustered Index consists of a key-ordered non-heap list of ALL the columns in the defined table, the lights went on for me. The word "cluster", then, refers to the fact that there is a "cluster" of all the columns, like a cluster of fish in that "hot spot". If there is no index covering the column containing the sought value (the right side of the equation), then the execution plan uses a Clustered Index Seek into the Clustered Index's representation of the requested column because it does not find the requested column in any other "covering" index. The missing will cause a Clustered Index Seek operator in the proposed Execution Plan, where the sought value is within a column inside the ordered list represented by the Clustered Index.

So, one solution is to create a non-clustered index that has the column containing the requested value inside the index. In this way, there is no need to reference the Clustered Index, and the Optimizer should be able to hook that index in the Execution Plan with no hint. If, however, there is a Predicate naming the single column clustering key and an argument to a scalar value on the clustering key, the Clustered Index Seek Operator will still be used, even if there is already a covering index on a second column in the table without an index.

Convert float to double without losing precision

Does this work?

float flt = 145.664454;

Double dbl = 0.0;
dbl += flt;

Convert Pandas column containing NaNs to dtype `int`

import pandas as pd

df= pd.read_csv("data.csv")
df['id'] = pd.to_numeric(df['id'])

Android sample bluetooth code to send a simple string via bluetooth

I made the following code so that even beginners can understand. Just copy the code and read comments. Note that message to be send is declared as a global variable which you can change just before sending the message. General changes can be done in Handler function.

multiplayerConnect.java

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;

public class multiplayerConnect extends AppCompatActivity {

public static final int REQUEST_ENABLE_BT=1;
ListView lv_paired_devices;
Set<BluetoothDevice> set_pairedDevices;
ArrayAdapter adapter_paired_devices;
BluetoothAdapter bluetoothAdapter;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public static final int MESSAGE_READ=0;
public static final int MESSAGE_WRITE=1;
public static final int CONNECTING=2;
public static final int CONNECTED=3;
public static final int NO_SOCKET_FOUND=4;


String bluetooth_message="00";




@SuppressLint("HandlerLeak")
Handler mHandler=new Handler()
{
    @Override
    public void handleMessage(Message msg_type) {
        super.handleMessage(msg_type);

        switch (msg_type.what){
            case MESSAGE_READ:

                byte[] readbuf=(byte[])msg_type.obj;
                String string_recieved=new String(readbuf);

                //do some task based on recieved string

                break;
            case MESSAGE_WRITE:

                if(msg_type.obj!=null){
                    ConnectedThread connectedThread=new ConnectedThread((BluetoothSocket)msg_type.obj);
                    connectedThread.write(bluetooth_message.getBytes());

                }
                break;

            case CONNECTED:
                Toast.makeText(getApplicationContext(),"Connected",Toast.LENGTH_SHORT).show();
                break;

            case CONNECTING:
                Toast.makeText(getApplicationContext(),"Connecting...",Toast.LENGTH_SHORT).show();
                break;

            case NO_SOCKET_FOUND:
                Toast.makeText(getApplicationContext(),"No socket found",Toast.LENGTH_SHORT).show();
                break;
        }
    }
};



@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.multiplayer_bluetooth);
    initialize_layout();
    initialize_bluetooth();
    start_accepting_connection();
    initialize_clicks();

}

public void start_accepting_connection()
{
    //call this on button click as suited by you

    AcceptThread acceptThread = new AcceptThread();
    acceptThread.start();
    Toast.makeText(getApplicationContext(),"accepting",Toast.LENGTH_SHORT).show();
}
public void initialize_clicks()
{
    lv_paired_devices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            Object[] objects = set_pairedDevices.toArray();
            BluetoothDevice device = (BluetoothDevice) objects[position];

            ConnectThread connectThread = new ConnectThread(device);
            connectThread.start();

            Toast.makeText(getApplicationContext(),"device choosen "+device.getName(),Toast.LENGTH_SHORT).show();
        }
    });
}

public void initialize_layout()
{
    lv_paired_devices = (ListView)findViewById(R.id.lv_paired_devices);
    adapter_paired_devices = new ArrayAdapter(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item);
    lv_paired_devices.setAdapter(adapter_paired_devices);
}

public void initialize_bluetooth()
{
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter == null) {
        // Device doesn't support Bluetooth
        Toast.makeText(getApplicationContext(),"Your Device doesn't support bluetooth. you can play as Single player",Toast.LENGTH_SHORT).show();
        finish();
    }

    //Add these permisions before
//        <uses-permission android:name="android.permission.BLUETOOTH" />
//        <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
//        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
//        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    if (!bluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

    else {
        set_pairedDevices = bluetoothAdapter.getBondedDevices();

        if (set_pairedDevices.size() > 0) {

            for (BluetoothDevice device : set_pairedDevices) {
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress(); // MAC address

                adapter_paired_devices.add(device.getName() + "\n" + device.getAddress());
            }
        }
    }
}


public class AcceptThread extends Thread
{
    private final BluetoothServerSocket serverSocket;

    public AcceptThread() {
        BluetoothServerSocket tmp = null;
        try {
            // MY_UUID is the app's UUID string, also used by the client code
            tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord("NAME",MY_UUID);
        } catch (IOException e) { }
        serverSocket = tmp;
    }

    public void run() {
        BluetoothSocket socket = null;
        // Keep listening until exception occurs or a socket is returned
        while (true) {
            try {
                socket = serverSocket.accept();
            } catch (IOException e) {
                break;
            }

            // If a connection was accepted
            if (socket != null)
            {
                // Do work to manage the connection (in a separate thread)
                mHandler.obtainMessage(CONNECTED).sendToTarget();
            }
        }
    }
}


private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        bluetoothAdapter.cancelDiscovery();

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mHandler.obtainMessage(CONNECTING).sendToTarget();

            mmSocket.connect();
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        // Do work to manage the connection (in a separate thread)
//            bluetooth_message = "Initial message"
//            mHandler.obtainMessage(MESSAGE_WRITE,mmSocket).sendToTarget();
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
private class ConnectedThread extends Thread {

    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[2];  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();

            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
}

multiplayer_bluetooth.xml

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Challenge player"/>

    <ListView
        android:id="@+id/lv_paired_devices"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">
    </ListView>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Make sure Device is paired"/>

</LinearLayout>

JSON character encoding

The answers here helped me solve my problem, although it's not completely related. I use the javax.ws.rs API and the @Produces and @Consumes annotations and had this same problem - the JSON I was returning in the webservice was not in UTF-8. I solved it with the following annotations on top of my controller functions :

@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON + "; charset=UTF-8")

and

@Consumes(javax.ws.rs.core.MediaType.APPLICATION_JSON + "; charset=UTF-8")

On every endpoint's get and post function. I wasn't setting the charset and this solved it. This is part of jersey so maybe you'll have to add a maven dependency.

Python equivalent of a given wget command

Here's the code adopted from the torchvision library:

import urllib

def download_url(url, root, filename=None):
    """Download a file from a url and place it in root.
    Args:
        url (str): URL to download file from
        root (str): Directory to place downloaded file in
        filename (str, optional): Name to save the file under. If None, use the basename of the URL
    """

    root = os.path.expanduser(root)
    if not filename:
        filename = os.path.basename(url)
    fpath = os.path.join(root, filename)

    os.makedirs(root, exist_ok=True)

    try:
        print('Downloading ' + url + ' to ' + fpath)
        urllib.request.urlretrieve(url, fpath)
    except (urllib.error.URLError, IOError) as e:
        if url[:5] == 'https':
            url = url.replace('https:', 'http:')
            print('Failed download. Trying https -> http instead.'
                    ' Downloading ' + url + ' to ' + fpath)
            urllib.request.urlretrieve(url, fpath)

If you are ok to take dependency on torchvision library then you also also simply do:

from torchvision.datasets.utils import download_url
download_url('http://something.com/file.zip', '~/my_folder`)

How to get the new value of an HTML input after a keypress has modified it?

Can you post your code? I'm not finding any issue with this. Tested on Firefox 3.01/safari 3.1.2 with:

function showMe(e) {
// i am spammy!
  alert(e.value);
}
....
<input type="text" id="foo" value="bar" onkeyup="showMe(this)" />