Programs & Examples On #Storage

Details on how data is being kept in memory/on disks, most frequently being applied to databases, media banks and backup-recovery solutions.

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

I'd say, it depends on your situation. For example, I work in local government, and we have lots of images like mugshots, etc. We don't have a high number of users, but we need to have good security and auditing around the data. The database is a better solution for us since it makes this easier and we aren't going to run into scaling problems.

How can I easily add storage to a VirtualBox machine with XP installed?

For Windows users there's an additional user friendly option: CloneVDI Tool by mpack. It's a GUI front-end to VBoxManage that makes things a little easier to work with.

http://forums.virtualbox.org/viewtopic.php?f=6&t=22422

As Alexander M. mentioned, you'll still have to use GParted, Partition Magic or a similar partition editor to grow your partition to the newly allocated physical drive. To do this just download the GParted iso, mount it as a bootable drive in the VirtualBox and boot from it.

http://gparted.sourceforge.net/download.php

Django CharField vs TextField

CharField has max_length of 255 characters while TextField can hold more than 255 characters. Use TextField when you have a large string as input. It is good to know that when the max_length parameter is passed into a TextField it passes the length validation to the TextArea widget.

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

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

Happy coding..

What column type/length should I use for storing a Bcrypt hashed password in a Database?

A Bcrypt hash can be stored in a BINARY(40) column.

BINARY(60), as the other answers suggest, is the easiest and most natural choice, but if you want to maximize storage efficiency, you can save 20 bytes by losslessly deconstructing the hash. I've documented this more thoroughly on GitHub: https://github.com/ademarre/binary-mcf

Bcrypt hashes follow a structure referred to as modular crypt format (MCF). Binary MCF (BMCF) decodes these textual hash representations to a more compact binary structure. In the case of Bcrypt, the resulting binary hash is 40 bytes.

Gumbo did a nice job of explaining the four components of a Bcrypt MCF hash:

$<id>$<cost>$<salt><digest>

Decoding to BMCF goes like this:

  1. $<id>$ can be represented in 3 bits.
  2. <cost>$, 04-31, can be represented in 5 bits. Put these together for 1 byte.
  3. The 22-character salt is a (non-standard) base-64 representation of 128 bits. Base-64 decoding yields 16 bytes.
  4. The 31-character hash digest can be base-64 decoded to 23 bytes.
  5. Put it all together for 40 bytes: 1 + 16 + 23

You can read more at the link above, or examine my PHP implementation, also on GitHub.

Android saving file to external storage

Make sure your app has the proper permissions to be allowed to write to external storage: http://developer.android.com/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE

It should look something like this in your manifest file:

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

AWS EFS vs EBS vs S3 (differences & when to use?)

To add to the comparison: (burst)read/write-performance on EFS depends on gathered credits. Gathering of credits depends on the amount of data you store on it. More date -> more credits. That means that when you only need a few GB of storage which is read or written often you will run out of credits very soon and througphput drops to about 50kb/s. The only way to fix this (in my case) was to add large dummy files to increase the rate credits are earned. However more storage -> more cost.

Android: Storing username and password?

With the new (Android 6.0) fingerprint hardware and API you can do it as in this github sample application.

What are the main performance differences between varchar and nvarchar SQL Server data types?

Since your application is small, there is essentially no appreciable cost increase to using nvarchar over varchar, and you save yourself potential headaches down the road if you have a need to store unicode data.

How to create a file on Android Internal Storage?

Hi try this it will create directory + file inside it

File mediaDir = new File("/sdcard/download/media");
if (!mediaDir.exists()){
    mediaDir.mkdir();
}

File resolveMeSDCard = new File("/sdcard/download/media/hello_file.txt");
resolveMeSDCard.createNewFile();
FileOutputStream fos = new FileOutputStream(resolveMeSDCard);
fos.write(string.getBytes());
fos.close();

System.out.println("Your file has been written");  

How to Get True Size of MySQL Database?

If you want to find the size of all MySQL databases, us this command, it will show their respective sizes in megabytes;

SELECT table_schema "database", sum(data_length + index_length)/1024/1024 "size in MB" FROM information_schema.TABLES GROUP BY table_schema;

If you have large databases, you can use the following command to show the result in gigabytes;

SELECT table_schema "database", sum(data_length + index_length)/1024/1024/1024 "size in GB" FROM information_schema.TABLES GROUP BY table_schema;

If you want to show the size of only a specific database, for example YOUR_DATABASE_NAME, you could use the following query;

SELECT table_schema "database", sum(data_length + index_length)/1024/1024/1024 "size in GB" FROM information_schema.TABLES WHERE table_schema='YOUR_DATABASE_NAME' GROUP BY table_schema;

Storing Images in DB - Yea or Nay?

Something nobody has mentioned is that the DB guarantees atomic actions, transactional integrity and deals with concurrency. Even referentially integrity is out of the window with a filesystem - so how do you know your file names are really still correct?

If you have your images in a file-system and someone is reading the file as you're writing a new version or even deleting the file - what happens?

We use blobs because they're easier to manage (backup, replication, transfer) too. They work well for us.

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

Here is a simple expressjs solution if you just want to run this app locally and security is not a concern:

On your server.js or app.js file, add the following:

app.use('/local-files', express.static('/'));

That will serve your ENTIRE root directory under /local-files. Needless to say this is a really bad idea if you're planning to deploy this app anywhere other than your local machine.

Now, you can simply do:

<img src="/local-files/images/mypic.jps"/> 

note: I'm running macOS. If you're using Windows you may have to search and remove 'C:\' from the path string

What are Transient and Volatile Modifiers?

Volatile means other threads can edit that particular variable. So the compiler allows access to them.

http://www.javamex.com/tutorials/synchronization_volatile.shtml

Transient means that when you serialize an object, it will return its default value on de-serialization

http://www.geekinterview.com/question_details/2

HTML Table different number of columns in different rows

On the realisation that you're unfamiliar with colspan, I presumed you're also unfamiliar with rowspan, so I thought I'd throw that in for free.

One important point to note, when using rowspan: the following tr elements must contain fewer td elements, because of the cells using rowspan in the previous row (or previous rows).

_x000D_
_x000D_
table {_x000D_
  border: 1px solid #000;_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
}
_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th colspan="2">Column one and two</th>_x000D_
      <th>Column three</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td rowspan="2" colspan="2">A large cell</td>_x000D_
      <td>a smaller cell</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <!-- note that this row only has _one_ td, since the preceding row_x000D_
                     takes up some of this row -->_x000D_
      <td>Another small cell</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to change default text color using custom theme?

When you create an App, a file called styles.xml will be created in your res/values folder. If you change the styles, you can change the background, text color, etc for all your layouts. That way you don’t have to go into each individual layout and change the it manually.

styles.xml:

<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="Theme.AppBaseTheme" parent="@android:style/Theme.Light">
    <item name="android:editTextColor">#295055</item> 
    <item name="android:textColorPrimary">#295055</item>
    <item name="android:textColorSecondary">#295055</item>
    <item name="android:textColorTertiary">#295055</item>
    <item name="android:textColorPrimaryInverse">#295055</item>
    <item name="android:textColorSecondaryInverse">#295055</item>
    <item name="android:textColorTertiaryInverse">#295055</item>

     <item name="android:windowBackground">@drawable/custom_background</item>        
</style>

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>

parent="@android:style/Theme.Light" is Google’s native colors. Here is a reference of what the native styles are: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/res/res/values/themes.xml

The default Android style is also called “Theme”. So you calling it Theme probably confused the program.

name="Theme.AppBaseTheme" means that you are creating a style that inherits all the styles from parent="@android:style/Theme.Light". This part you can ignore unless you want to inherit from AppBaseTheme again. = <style name="AppTheme" parent="AppBaseTheme">

@drawable/custom_background is a custom image I put in the drawable’s folder. It is a 300x300 png image.

#295055 is a dark blue color.

My code changes the background and text color. For Button text, please look through Google’s native stlyes (the link I gave u above).

Then in Android Manifest, remember to include the code:

<application
android:theme="@style/Theme.AppBaseTheme">

Set font-weight using Bootstrap classes

I found this on the Bootstrap website, but it really isn't a Bootstrap class, it's just HTML.

<strong>rendered as bold text</strong>

Store select query's output in one array in postgres

I had exactly the same problem. Just one more working modification of the solution given by Denis (the type must be specified):

SELECT ARRAY(
SELECT column_name::text
FROM information_schema.columns
WHERE table_name='aean'
)

How to use if-else option in JSTL

Besides the need to have an else, in many cases you will need to use the same condition on multiple locations.

I prefer to extract the condition into a variable:

<c:set var="conditionVar" value="#{expression}"/>

And after that, you can use the condition variable as many times as you need it:

...
<c:if test="#{conditionVar}">
       ...
</c:if>
<c:if test="#{!conditionVar}">
       ...
</c:if>
...
<c:if test="#{conditionVar}">
       ...
</c:if>
<c:if test="#{!conditionVar}">
       ...
</c:if>
...

The c:choose element is good for more complicated situations, but if you need an if else only, I think this approach is better. It is efficient and has the following benefits:

  • more readable if the variable name is well chosen
  • more reusable because the condition is extracted and the resulting variable can be reused for other ifs and in other expressions. It discourages writing the same condition (and evaluating it) multiple times.

String Resource new line /n not possible?

don't put space after \n, otherwise, it won't work. I don't know the reason, but this trick worked for me pretty well.

Value cannot be null. Parameter name: source

In my case, the problem popped up while configuring the web application on IIS, When the update command on any record was fired this error got generated.

It was a permission issue on App_Data which set to read-only. Right-click the folder, uncheck the Read-only checkbox and you are done. By the way, for testing purpose, I was using the localdb database which was in App_Data folder.

How to set Grid row and column positions programmatically

Try this:

                Grid grid = new Grid(); //Define the grid
                for (int i = 0; i < 36; i++) //Add 36 rows
                {
                    ColumnDefinition columna = new ColumnDefinition()
                    {
                        Name = "Col_" + i,
                        Width = new GridLength(32.5),
                    };
                    grid.ColumnDefinitions.Add(columna);
                }

                for (int i = 0; i < 36; i++) //Add 36 columns
                {
                    RowDefinition row = new RowDefinition();
                    row.Height = new GridLength(40, GridUnitType.Pixel);
                    grid.RowDefinitions.Add(row);
                }

                for (int i = 0; i < 36; i++)
                {
                    for (int j = 0; j < 36; j++)
                    {
                        Label t1 = new Label()
                        {
                            FontSize = 10,
                            FontFamily = new FontFamily("consolas"),
                            FontWeight = FontWeights.SemiBold,
                            BorderBrush = Brushes.LightGray,
                            BorderThickness = new Thickness(2),
                            HorizontalContentAlignment = HorizontalAlignment.Center,
                            VerticalContentAlignment = VerticalAlignment.Center,
                        };
                        Grid.SetRow(t1, i);
                        Grid.SetColumn(t1, j);
                        grid.Children.Add(t1); //Add the Label Control to the Grid created
                    }
                }

Check if a variable is between two numbers with Java

public static boolean between(int i, int minValueInclusive, int maxValueInclusive) {
    if (i >= minValueInclusive && i <= maxValueInclusive)
        return true;
    else
        return false;
}

https://alvinalexander.com/java/java-method-integer-is-between-a-range

How to show an empty view with a RecyclerView?

One more way is to use addOnChildAttachStateChangeListener which handles appearing/disappearing child views in RecyclerView.

recyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(@NonNull View view) {
                forEmptyTextView.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onChildViewDetachedFromWindow(@NonNull View view) {
                forEmptyTextView.setVisibility(View.VISIBLE);
            }
        });

How to get text from EditText?

Place the following after the setContentView() method.

final EditText edit =  (EditText) findViewById(R.id.Your_Edit_ID);
String emailString = (String) edit.getText().toString();
Log.d("email",emailString);

How do I sort a list of datetime or date objects?

You're getting None because list.sort() it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort() without assigning it to a again.

There is a built in function sorted(), which returns a sorted version of the list - a = sorted(a) will do what you want as well.

Turn a single number into single digits Python

Here's a way to do it without turning it into a string first (based on some rudimentary benchmarking, this is about twice as fast as stringifying n first):

>>> n = 43365644
>>> [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10))-1, -1, -1)]
[4, 3, 3, 6, 5, 6, 4, 4]

Updating this after many years in response to comments of this not working for powers of 10:

[(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][bool(math.log(n,10)%1):]

The issue is that with powers of 10 (and ONLY with these), an extra step is required. ---So we use the remainder in the log_10 to determine whether to remove the leading 0--- We can't exactly use this because floating-point math errors cause this to fail for some powers of 10. So I've decided to cross the unholy river into sin and call upon regex.

In [32]: n = 43

In [33]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
Out[33]: [4, 3]

In [34]: n = 1000

In [35]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
Out[35]: [1, 0, 0, 0]

How to show android checkbox at right side?

The following link demonstrates how to render seveveral Standard Android view objects with an animated checkbox on the right by setting the right drawable.

Set the background to get a ripple effect.

[link to website with example checkbox on right and left side.][1] http://landenlabs.com/android/uicomponents/uicomponents.html#checkbox

         <Button
            android:id="@+id/p2Button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:background="@drawable/transparent_ripple"
            android:drawableRight="@drawable/checkline"
            android:gravity="left|center_vertical"
            android:text="Button"
            android:textAllCaps="false"

            android:textColor="@android:color/white"
            android:textSize="@dimen/buttonTextSize" />

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/p2Button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:background="@drawable/transparent_ripple"
            android:drawableRight="@drawable/checkline"
            android:gravity="left|center_vertical"
            android:text="AppCompatButton"
            android:textAllCaps="false"

            android:textColor="@android:color/white"
            android:textSize="@dimen/buttonTextSize" />

        <TextView
            android:id="@+id/p2TextView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:background="@drawable/transparent_ripple"
            android:drawableRight="@drawable/checkline"
            android:gravity="left|center_vertical"
            android:hapticFeedbackEnabled="true"

            android:text="TextView"
            android:textColor="@android:color/white"
            android:textSize="@dimen/buttonTextSize" />

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/p2TextView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:background="@drawable/transparent_ripple"
            android:drawableRight="@drawable/checkline"
            android:gravity="left|center_vertical"
            android:hapticFeedbackEnabled="true"

            android:text="AppCompatTextView"
            android:textColor="@android:color/white"
            android:textSize="@dimen/buttonTextSize" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@android:color/white" />

        <CheckBox
            android:id="@+id/p2Checkbox1"
            android:layout_width="match_parent"
            android:layout_height="@dimen/buttonHeight"
            android:background="@drawable/transparent_ripple"
            android:button="@null"
            android:checked="true"
            android:drawableRight="@drawable/checkline"
            android:gravity="left|center_vertical"
            android:text="CheckBox"
            android:textColor="@android:color/white"
            android:textSize="@dimen/buttonTextSize" />

        <android.support.v7.widget.AppCompatCheckBox
            android:id="@+id/p2Checkbox2"
            android:layout_width="match_parent"
            android:layout_height="@dimen/buttonHeight"
            android:background="@drawable/transparent_ripple"
            android:button="@null"
            android:checked="true"
            android:drawableRight="@drawable/checkline"
            android:gravity="left|center_vertical"
            android:text="AppCompatCheckBox"
            android:textColor="@android:color/white"
            android:textSize="@dimen/buttonTextSize" />

        <android.support.v7.widget.AppCompatCheckedTextView
            android:id="@+id/p2Checkbox3"
            android:layout_width="match_parent"
            android:layout_height="@dimen/buttonHeight"
            android:background="@drawable/transparent_ripple"
            android:checkMark="@drawable/checkline"
            android:checked="true"
            android:gravity="left|center_vertical"
            android:text="AppCompatCheckedTextView"
            android:textColor="@android:color/white"
            android:textSize="@dimen/buttonTextSize" />

        <!--  android:checkMark="?android:attr/listChoiceIndicatorMultiple" -->
        <CheckedTextView
            android:id="@+id/p2Checkbox4"
            android:layout_width="match_parent"
            android:layout_height="@dimen/buttonHeight"
            android:background="@drawable/transparent_ripple"
            android:checkMark="@drawable/checkline"
            android:checked="true"
            android:gravity="left|center_vertical"
            android:text="CheckedTextView"
            android:textColor="@android:color/white"
            android:textSize="@dimen/buttonTextSize" />

        <CheckBox
            android:id="@+id/p2Checkbox5"
            android:layout_width="match_parent"
            android:layout_height="@dimen/buttonHeight"
            android:background="@drawable/transparent_ripple"
            android:checked="true"
            android:gravity="center_vertical|end"
            android:text="CheckBox"
            android:textColor="@android:color/white"
            android:textSize="@dimen/buttonTextSize" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@android:color/white" />


        <ToggleButton
            android:id="@+id/p2ToggleButton1"
            android:layout_width="match_parent"
            android:layout_height="@dimen/buttonHeight"
            android:background="@drawable/transparent_ripple"
            android:checked="true"
            android:drawableRight="@drawable/checkline"
            android:gravity="center_vertical|left"
            android:textAllCaps="false"
            android:textColor="@android:color/white"

            android:textOff="ToggleButtonOff"

            android:textOn="ToggleButtonOn"
            android:textSize="@dimen/buttonTextSize" />

        <ToggleButton
            android:id="@+id/p2ToggleButton2"
            android:layout_width="match_parent"
            android:layout_height="@dimen/buttonHeight"
            android:background="@drawable/transparent_ripple"
            android:checked="true"
            android:drawableRight="@drawable/btn_check_material_anim"
            android:gravity="center_vertical|left"
            android:textAllCaps="false"

            android:textColor="@android:color/white"
            android:textOff="ToggleBtnnAnimOff"
            android:textOn="ToggleBtnnAnimOn"
            android:textSize="@dimen/buttonTextSize" />

Sample checkline.xml (in drawable, see link for animated version in drawable-v21)

Sample transparent_ripple.xml (in drawable-v21)

<!-- Limit ripple to view object, can also use shape such as oval -->
<item android:id="@android:id/mask" android:drawable="@android:color/white" />

<item>
    <selector xmlns:android="http://schemas.android.com/apk/res/android"
        android:enterFadeDuration="200"
        android:exitFadeDuration="200">

        <item android:state_pressed="true">
            <shape android:shape="rectangle">
                <solid android:color="#80c0c000" />
            </shape>
        </item>
    </selector>
</item>


Sample transparent_ripple.xml (in drawable, highlight only no ripple available

<item android:state_pressed="true">
    <shape android:shape="rectangle">
        <solid android:color="#80c0c000" />
    </shape>
</item>
<item>
    <shape android:shape="rectangle">
        <solid android:color="@android:color/transparent" />
    </shape>
</item>

matplotlib has no attribute 'pyplot'

pyplot is a sub-module of matplotlib which doesn't get imported with a simple import matplotlib.

>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>> 

It seems customary to do: import matplotlib.pyplot as plt at which time you can use the various functions and classes it contains:

p = plt.plot(...)

SQL User Defined Function Within Select

Use a scalar-valued UDF, not a table-value one, then you can use it in a SELECT as you want.

"Unorderable types: int() < str()"

Just a side note, in Python 2.0 you could compare anything to anything (int to string). As this wasn't explicit, it was changed in 3.0, which is a good thing as you are not running into the trouble of comparing senseless values with each other or when you forget to convert a type.

Extract digits from a string in Java

Using Google Guava:

CharMatcher.DIGIT.retainFrom("123-456-789");

CharMatcher is plug-able and quite interesting to use, for instance you can do the following:

String input = "My phone number is 123-456-789!";
String output = CharMatcher.is('-').or(CharMatcher.DIGIT).retainFrom(input);

output == 123-456-789

How to add bootstrap to an angular-cli project

you can install bootstrap in angular using npm install bootstrap command.

and next setup bootstrap path in angular.json file and style.css file.

you can read a full blog about how to install & setup bootstrap in angular, click here to read full blog about this

Is there a MessageBox equivalent in WPF?

The WPF equivalent would be the System.Windows.MessageBox. It has a quite similar interface, but uses other enumerations for parameters and return value.

How to use ConfigurationManager

Go to tools >> nuget >> console and type:

Install-Package System.Configuration.ConfigurationManager 

If you want a specific version:

Install-Package System.Configuration.ConfigurationManager -Version 4.5.0

Your ConfigurationManager dll will now be imported and the code will begin to work.

Calling JavaScript Function From CodeBehind

IIRC Code Behind is compiled serverside and javascript is interpreted client side. This means there is no direct link between the two.

What you can do on the other hand is have the client and server communicate through a nifty tool called AJAX. http://en.wikipedia.org/wiki/Asynchronous_JavaScript_and_XML

PHP output showing little black diamonds with a question mark

This happened to work in my case:

$text = utf8_decode($text)

I turns the black diamond character into a question mark so you can:

$text = str_replace('?', '', utf8_decode($text));

How to add a linked source folder in Android Studio?

You can add a source folder to the build script and then sync. Look for sourceSets in the documentation here: http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Basic-Project

I haven't found a good way of adding test source folders. I have manually added the source to the .iml file. Of course this means it will go away everytime the build script is synched.

Update query with PDO and MySQL

This has nothing to do with using PDO, it's just that you are confusing INSERT and UPDATE.

Here's the difference:

  • INSERT creates a new row. I'm guessing that you really want to create a new row.
  • UPDATE changes the values in an existing row, but if this is what you're doing you probably should use a WHERE clause to restrict the change to a specific row, because the default is that it applies to every row.

So this will probably do what you want:

$sql = "INSERT INTO `access_users`   
  (`contact_first_name`,`contact_surname`,`contact_email`,`telephone`) 
  VALUES (:firstname, :surname, :email, :telephone);
  ";

Note that I've also changed the order of columns; the order of your columns must match the order of values in your VALUES clause.

MySQL also supports an alternative syntax for INSERT:

$sql = "INSERT INTO `access_users`   
  SET `contact_first_name` = :firstname,
    `contact_surname` = :surname,
    `contact_email` = :email,
    `telephone` = :telephone
  ";

This alternative syntax looks a bit more like an UPDATE statement, but it creates a new row like INSERT. The advantage is that it's easier to match up the columns to the correct parameters.

Validating Phone Numbers Using Javascript

<!DOCTYPE html>
<html>
    <head>
        <style>
           .container__1{
               max-width: 450px;
               font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
           }
           .container__1 label{
               display: block;
               margin-bottom: 10px;
           }
           .container__1 label > span{
               float: left;
               width: 100px;
               color: #F072A9;
               font-weight: bold;
               font-size: 13px;
               text-shadow: 1px 1px 1px #fff;
           }
           .container__1 fieldset{
               border-radius: 10px;
               -webkit-border-radious:10px;
               -moz-border-radoius: 10px;
               margin: 0px 0px 0px 0px;
               border: 1px solid #FFD2D2;
               padding: 20px;
               background:#FFF4F4 ;
               box-shadow: inset 0px 0px 15px #FFE5E5;


           }
           .container__1 fieldset legend{
               color: #FFA0C9;
               border-top: 1px solid #FFD2D2 ;
               border-left: 1px solid #FFD2D2 ;
               border-right: 1px solid #FFD2D2 ;
               border-radius: 5px 5px 0px 0px;
               background: #FFF4F4;
               padding: 0px 8px 3px 8px;
               box-shadow: -0px -1px 2px #F1F1F1;
               font-weight: normal;
               font-size: 12px;
           }
           .container__1 textarea{
               width: 250px;
               height: 100px;
           }.container__1 input[type=text],
           .container__1 input[type=email],
           .container__1 select{
               border-radius: 3px;
               border: 1px solid #FFC2DC;
               outline: none;
               color: #F072A9;
               padding: 5px 8px 5px 8px;
               box-shadow: inset 1px 1px 4px #FFD5E7;
               background: #FFEFF6;
               

           }
           .container__1 input[type=submit],
           .container__1 input[type=button]{
               background: #EB3B88;
               border: 1px solid #C94A81;
               padding: 5px 15px 5px 15px;
               color: #FFCBE2;
               box-shadow: inset -1px -1px 3px #FF62A7;
               border-radius: 3px;
               font-weight: bold;
           }
           .required{
               color: red;
           }
        </style>
    </head>
    <body>
        <div class="container__1">
            <form name="RegisterForm" onsubmit="return(SubmitClick())">
                <fieldset>
                    <legend>Personal</legend>
                    <label for="field1"><span >Name<span class="required">*</span><input id="name" type="text" class="input-field" name="Name" value=""</label>
                    <label for="field2"><span >Email<span class="required">*</span><input placeholder="Ex: [email protected]" id="email" type="email" class="input-field" name="Email" value=""</label>
                    <label for="field3"><span >Phone<span class="required">*</span><input placeholder="+919853004369" id="mobile" type="text" class="input-field" name="Mobile" value=""</label>
                    <label for="field4">
                        <span>Subject</span>
                        <select name="subject" id="subject" class="select-field">
                            <option value="none">Choose Your Sub..</option>
                            <option value="Appointment">Appiontment</option>
                            <option value="Interview">Interview</option>
                            <option value="Regarding a post">Regarding a post</option>
                        </select>
                    </label>
                    <label><span></span><input type="submit"  ></label>
                </fieldset>
            </form>
        </div>
    </body>
    <script>
        function SubmitClick(){
        _name = document.querySelector('#name').value;
        _email = document.querySelector('#email').value;
        _mobile = document.querySelector('#mobile').value;
        _subject = document.querySelector('#subject').value;
          if(_name == '' || _name == null ){
              alert('Enter Your Name');
              document.RegisterForm.Name.focus();
              return false; 
          } 
          var atPos = _email.indexOf('@');
         var dotPos = _email.lastIndexOf('.');

          if(_email == '' || atPos<1 || (dotPos - atPos)<2){
              alert('Provide Your Correct Email address');
              document.RegisterForm.Email.focus();
              return false;
          }
          var regExp = /^\+91[0-9]{10}$/;
          if(_mobile == '' || !regExp.test(_mobile)){
              alert('Please Provide your Mobile number as Ex:- +919853004369');
              document.RegisterForm.Mobile.focus();
              return false;
          }
          if(_subject == 'none'){
              alert('Please choose a subject');
              document.RegisterForm.subject.focus();
              return false;
          }else{
            alert (`success!!!:--'\n'Name:${_name},'\n' Mobile: ${_mobile},'\n' Email:${_email},'\n' Subject:${_subject},`)
          }
        
          
        }
    </script>
</html>

How to parse a string in JavaScript?

Use the Javascript string split() function.

var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');

// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc

How To Format A Block of Code Within a Presentation?

I've also thought of this. Finally, my solution is to use github gist. Don't forget it also has highlight functionality. Just copy it. :)

How to decode viewstate

Use Fiddler and grab the view state in the response and paste it into the bottom left text box then decode.

Submitting HTML form using Jquery AJAX

Quick Description of AJAX

AJAX is simply Asyncronous JSON or XML (in most newer situations JSON). Because we are doing an ASYNC task we will likely be providing our users with a more enjoyable UI experience. In this specific case we are doing a FORM submission using AJAX.

Really quickly there are 4 general web actions GET, POST, PUT, and DELETE; these directly correspond with SELECT/Retreiving DATA, INSERTING DATA, UPDATING/UPSERTING DATA, and DELETING DATA. A default HTML/ASP.Net webform/PHP/Python or any other form action is to "submit" which is a POST action. Because of this the below will all describe doing a POST. Sometimes however with http you might want a different action and would likely want to utilitize .ajax.

My code specifically for you (described in code comments):

_x000D_
_x000D_
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /* get the action attribute from the <form action=""> element */
  var $form = $(this),
    url = $form.attr('action');

  /* Send the data using post with element id name and name2*/
  var posting = $.post(url, {
    name: $('#name').val(),
    name2: $('#name2').val()
  });

  /* Alerts the results */
  posting.done(function(data) {
    $('#result').text('success');
  });
  posting.fail(function() {
    $('#result').text('failed');
  });
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="formoid" action="studentFormInsert.php" title="" method="post">
  <div>
    <label class="title">First Name</label>
    <input type="text" id="name" name="name">
  </div>
  <div>
    <label class="title">Last Name</label>
    <input type="text" id="name2" name="name2">
  </div>
  <div>
    <input type="submit" id="submitButton" name="submitButton" value="Submit">
  </div>
</form>

<div id="result"></div>
_x000D_
_x000D_
_x000D_


Documentation

From jQuery website $.post documentation.

Example: Send form data using ajax requests

$.post("test.php", $("#testform").serialize());

Example: Post a form using ajax and put results in a div

<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    </head>
    <body>
        <form action="/" id="searchForm">
            <input type="text" name="s" placeholder="Search..." />
            <input type="submit" value="Search" />
        </form>
        <!-- the result of the search will be rendered inside this div -->
        <div id="result"></div>
        <script>
            /* attach a submit handler to the form */
            $("#searchForm").submit(function(event) {

                /* stop form from submitting normally */
                event.preventDefault();

                /* get some values from elements on the page: */
                var $form = $(this),
                    term = $form.find('input[name="s"]').val(),
                    url = $form.attr('action');

                /* Send the data using post */
                var posting = $.post(url, {
                    s: term
                });

                /* Put the results in a div */
                posting.done(function(data) {
                    var content = $(data).find('#content');
                    $("#result").empty().append(content);
                });
            });
        </script>
    </body>
</html>

Important Note

Without using OAuth or at minimum HTTPS (TLS/SSL) please don't use this method for secure data (credit card numbers, SSN, anything that is PCI, HIPAA, or login related)

adding a datatable in a dataset

you have to set the tableName you want to your dtimage that is for instance

dtImage.TableName="mydtimage";


if(!ds.Tables.Contains(dtImage.TableName))
        ds.Tables.Add(dtImage);

it will be reflected in dataset because dataset is a container of your datatable dtimage and you have a reference on your dtimage

How to capture UIView to UIImage without loss of quality on retina display

Here's a Swift 4 UIView extension based on the answer from @Dima.

extension UIView {
   func snapshotImage() -> UIImage? {
       UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
       drawHierarchy(in: bounds, afterScreenUpdates: false)
       let image = UIGraphicsGetImageFromCurrentImageContext()
       UIGraphicsEndImageContext()
       return image
   }
}

How to establish ssh key pair when "Host key verification failed"

If you're sure the server is correct, sed -i 1d ~/.ssh/known_hosts will delete line 1 of your local ~/.ssh/known_hosts. The new correct key will be added to the file the next time you connect.

Selenium WebDriver.get(url) does not open the URL

I was getting similar problem and Stating string for URL worked for me. :)

package Chrome_Example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Launch_Chrome {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "C:\\Users\\doyes\\Downloads\\chromedriver_win324\\chromedriver.exe");
        String URL = "http://www.google.com";
        WebDriver driver = new ChromeDriver();
        driver.get(URL);
    }

}

HTTPS setup in Amazon EC2

This answer is focused to someone that buy a domain in another site (as GoDaddy) and want to use the Amazon free certificate with Certificate Manager

This answer uses Amazon Classic Load Balancer (paid) see the pricing before using it


Step 1 - Request a certificate with Certificate Manager

Go to Certificate Manager > Request Certificate > Request a public certificate

On Domain name you will add myprojectdomainname.com and *.myprojectdomainname.com and go on Next

Chose Email validation and Confirm and Request

Open the email that you have received (on the email account that you have buyed the domain) and aprove the request

After this, check if the validation status of myprojectdomainname.com and *.myprojectdomainname.com is sucess, if is sucess you can continue to Step 2

Step 2 - Create a Security Group to a Load Balancer

On EC2 go to Security Groups > and Create a Security Group and add the http and https inbound

It will be something like: enter image description here

Step 3 - Create the Load Balancer

EC2 > Load Balancer > Create Load Balancer > Classic Load Balancer (Third option)

Create LB inside - the vpc of your project On Load Balancer Protocol add Http and Https enter image description here

Next > Select exiting security group

Choose the security group that you have create in the previous step

Next > Choose certificate from ACM

Select the certificate of the step 1

Next >

on Health check i've used the ping path / (one slash instead of /index.html)

Step 4 - Associate your instance with the security group of load balancer

EC2 > Instances > click on your project > Actions > Networking > Change Security Groups

Add the Security Group of your Load Balancer

Step 5

EC2 > Load Balancer > Click on the load balancer that you have created > copy the DNS Name (A Record), it will be something like myproject-2021611191.us-east-1.elb.amazonaws.com

Go to Route 53 > Routes Zones > click on the domain name > Go to Records Sets (If you are don't have your domain here, create a hosted zone with Domain Name: myprojectdomainname.com and Type: Public Hosted Zone)

Check if you have a record type A (probably not), create/edit record set with name empty, type A, alias Yes and Target the dns that you have copied

Create also a new Record Set of type A, name *.myprojectdomainname.com, alias Yes and Target your domain (myprojectdomainname.com). This will make possible access your site with www.myprojectdomainname.com and subsite.myprojectdomainname.com. Note: You will need to configure your reverse proxy (Nginx/Apache) to do so.

On NS copy the 4 Name Servers values to use on the next Step, it will be something like:

ns-362.awsdns-45.com ns-1558.awsdns-02.co.uk ns-737.awsdns-28.net ns-1522.awsdns-62.org

Go to EC2 > Instances > And copy the IPv4 Public IP too

Step 6

On the domain register site that you have buyed the domain (in my case GoDaddy)

Change the routing to http : <Your IPv4 Public IP Number> and select Forward with masking

Change the Name Servers (NS) to the 4 NS that you have copied, this can take 48 hours to make effect

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

Why do you want to enforce that only a single thread can access the DB at any one time?

It is the job of the database driver to implement any necessary locking, assuming a Connection is only used by one thread at a time!

Most likely, your database is perfectly capable of handling multiple, parallel access

How to simulate key presses or a click with JavaScript?

Simulating a mouse click

My guess is that the webpage is listening to mousedown rather than click (which is bad for accessibility because when a user uses the keyboard, only focus and click are fired, not mousedown). So you should simulate mousedown, click, and mouseup (which, by the way, is what the iPhone, iPod Touch, and iPad do on tap events).

To simulate the mouse events, you can use this snippet for browsers that support DOM 2 Events. For a more foolproof simulation, fill in the mouse position using initMouseEvent instead.

// DOM 2 Events
var dispatchMouseEvent = function(target, var_args) {
  var e = document.createEvent("MouseEvents");
  // If you need clientX, clientY, etc., you can call
  // initMouseEvent instead of initEvent
  e.initEvent.apply(e, Array.prototype.slice.call(arguments, 1));
  target.dispatchEvent(e);
};
dispatchMouseEvent(element, 'mouseover', true, true);
dispatchMouseEvent(element, 'mousedown', true, true);
dispatchMouseEvent(element, 'click', true, true);
dispatchMouseEvent(element, 'mouseup', true, true);

When you fire a simulated click event, the browser will actually fire the default action (e.g. navigate to the link's href, or submit a form).

In IE, the equivalent snippet is this (unverified since I don't have IE). I don't think you can give the event handler mouse positions.

// IE 5.5+
element.fireEvent("onmouseover");
element.fireEvent("onmousedown");
element.fireEvent("onclick");  // or element.click()
element.fireEvent("onmouseup");

Simulating keydown and keypress

You can simulate keydown and keypress events, but unfortunately in Chrome they only fire the event handlers and don't perform any of the default actions. I think this is because the DOM 3 Events working draft describes this funky order of key events:

  1. keydown (often has default action such as fire click, submit, or textInput events)
  2. keypress (if the key isn't just a modifier key like Shift or Ctrl)
  3. (keydown, keypress) with repeat=true if the user holds down the button
  4. default actions of keydown!!
  5. keyup

This means that you have to (while combing the HTML5 and DOM 3 Events drafts) simulate a large amount of what the browser would otherwise do. I hate it when I have to do that. For example, this is roughly how to simulate a key press on an input or textarea.

// DOM 3 Events
var dispatchKeyboardEvent = function(target, initKeyboradEvent_args) {
  var e = document.createEvent("KeyboardEvents");
  e.initKeyboardEvent.apply(e, Array.prototype.slice.call(arguments, 1));
  target.dispatchEvent(e);
};
var dispatchTextEvent = function(target, initTextEvent_args) {
  var e = document.createEvent("TextEvent");
  e.initTextEvent.apply(e, Array.prototype.slice.call(arguments, 1));
  target.dispatchEvent(e);
};
var dispatchSimpleEvent = function(target, type, canBubble, cancelable) {
  var e = document.createEvent("Event");
  e.initEvent.apply(e, Array.prototype.slice.call(arguments, 1));
  target.dispatchEvent(e);
};

var canceled = !dispatchKeyboardEvent(element,
    'keydown', true, true,  // type, bubbles, cancelable
    null,  // window
    'h',  // key
    0, // location: 0=standard, 1=left, 2=right, 3=numpad, 4=mobile, 5=joystick
    '');  // space-sparated Shift, Control, Alt, etc.
dispatchKeyboardEvent(
    element, 'keypress', true, true, null, 'h', 0, '');
if (!canceled) {
  if (dispatchTextEvent(element, 'textInput', true, true, null, 'h', 0)) {
    element.value += 'h';
    dispatchSimpleEvent(element, 'input', false, false);
    // not supported in Chrome yet
    // if (element.form) element.form.dispatchFormInput();
    dispatchSimpleEvent(element, 'change', false, false);
    // not supported in Chrome yet
    // if (element.form) element.form.dispatchFormChange();
  }
}
dispatchKeyboardEvent(
    element, 'keyup', true, true, null, 'h', 0, '');

I don't think it is possible to simulate key events in IE.

Spring boot - Not a managed type

I think replacing @ComponentScan with @ComponentScan("com.nervy.dialer.domain") will work.

Edit :

I have added a sample application to demonstrate how to set up a pooled datasource connection with BoneCP.

The application has the same structure with yours. I hope this will help you to resolve your configuration problems

How to set cache: false in jQuery.get call

I think you have to use the AJAX method instead which allows you to turn caching off:

$.ajax({
  url: "test.html",
  data: 'foo',
  success: function(){
    alert('bar');
  },
  cache: false
});

Selenium wait until document is ready

The following code should probably work:

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.presenceOfAllElementsLocated(By.xpath("//*")));

Most pythonic way to delete a file which may not exist

Matt's answer is the right one for older Pythons and Kevin's the right answer for newer ones.

If you wish not to copy the function for silentremove, this functionality is exposed in path.py as remove_p:

from path import Path
Path(filename).remove_p()

How can I obfuscate (protect) JavaScript?

You can't secure client side code: just press F12 on Google Chrome, pause javascript execution and you will get all strings, even those encrypted. Beautify it and rename variables and you will get almost the original code.

If you're writing server side javascript (i.e. NodeJS) is afraid of someone hacking into your server and want to make the hacker work more difficult, giving you more time to get your access back, then use javacript compilers:

You need to use Closure Compiler on Advanced Compilation, as it's the only tool that renames all your variables, even if those are used in multiple files/modules. But it just have a problem: it only work if you write in it's coding style.

How to convert string to boolean php

you can use json_decode to decode that boolean

$string = 'false';
$boolean = json_decode($string);
if($boolean) {
  // Do something
} else {
  //Do something else
}

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

It may sound banal, but for me Build > Clean Project fixed this error without any other changes.

How to connect to SQL Server from command prompt with Windows authentication

You can use different syntax to achieve different things. If it is windows authentication you want, you could try this:

sqlcmd /S  /d  -E

If you want to use SQL Server authentication you could try this:

sqlcmd /S  /d -U -P 

Definitions:

/S = the servername/instance name. Example: Pete's Laptop/SQLSERV
/d = the database name. Example: Botlek1
-E = Windows authentication.
-U = SQL Server authentication/user. Example: Pete
-P = password that belongs to the user. Example: 1234

Hope this helps!

System.Collections.Generic.IEnumerable' does not contain any definition for 'ToList'

You're missing a reference to System.Linq.

Add

using System.Linq

to get access to the ToList() function on the current code file.


To give a little bit of information over why this is necessary, Enumerable.ToList<TSource> is an extension method. Extension methods are defined outside the original class that it targets. In this case, the extension method is defined on System.Linq namespace.

String formatting in Python 3

That line works as-is in Python 3.

>>> sys.version
'3.2 (r32:88445, Oct 20 2012, 14:09:29) \n[GCC 4.5.2]'
>>> "(%d goals, $%d)" % (self.goals, self.penalties)
'(1 goals, $2)'

jQuery DIV click, with anchors

I know that if you were to change that to an href you'd do:

$("a#link1").click(function(event) {
  event.preventDefault();
  $('div.link1').show();
  //whatever else you want to do
});

so if you want to keep it with the div, I'd try

$("div.clickable").click(function(event) {
  event.preventDefault();
  window.location = $(this).attr("url");
});

How to display HTML in TextView?

Simple use Html.fromHtml("html string"). This will work. If the string has tags like <h1> then spaces will come. But we cannot eliminate those spaces. If you still want to remove the spaces, then you can remove the tags in the string and then pass the string to the method Html.fromHtml("html string"); . Also generally these strings come from server(dynamic) but not often, if it is the case better to pass the string as it is to the method than try to remove the tags from the string.

PHP String to Float

$rootbeer = (float) $InvoicedUnits;

Should do it for you. Check out Type-Juggling. You should also read String conversion to Numbers.

Can't connect to Postgresql on port 5432

You probably need to either open up the port to access it in your LAN (or outside of it) or bind the network address to the port (make PostgreSQL listen on your LAN instead of just on localhost)

How to remove the border highlight on an input text element

Remove the outline when focus is on element, using below CSS property:

input:focus {
    outline: 0;
}

This CSS property removes the outline for all input fields on focus or use pseudo class to remove outline of element using below CSS property.

.className input:focus {
    outline: 0;
} 

This property removes the outline for selected element.

How to restart ADB manually from Android Studio

AndroidStudio:

Go to: Tools -> Android -> Android Device Monitor

see the Device tab, under many icons, last one is drop-down arrow.

Open it.

At the bottom: RESET ADB.

How to add headers to OkHttp request interceptor?

Kotlin version:

fun okHttpClientFactory(): OkHttpClient {
    return OkHttpClient().newBuilder()
        .addInterceptor { chain ->
            chain.request().newBuilder()
                .addHeader(HEADER_AUTHONRIZATION, O_AUTH_AUTHENTICATION)
                .build()
                .let(chain::proceed)
        }
        .build()
}

Difference between matches() and find() in Java Regex

matches tries to match the expression against the entire string and implicitly add a ^ at the start and $ at the end of your pattern, meaning it will not look for a substring. Hence the output of this code:

public static void main(String[] args) throws ParseException {
    Pattern p = Pattern.compile("\\d\\d\\d");
    Matcher m = p.matcher("a123b");
    System.out.println(m.find());
    System.out.println(m.matches());

    p = Pattern.compile("^\\d\\d\\d$");
    m = p.matcher("123");
    System.out.println(m.find());
    System.out.println(m.matches());
}

/* output:
true
false
true
true
*/

123 is a substring of a123b so the find() method outputs true. matches() only 'sees' a123b which is not the same as 123 and thus outputs false.

Iterating on a file doesn't work the second time

The file object is a buffer. When you read from the buffer, that portion that you read is consumed (the read position is shifted forward). When you read through the entire file, the read position is at the end of the file (EOF), so it returns nothing because there is nothing left to read.

If you have to reset the read position on a file object for some reason, you can do:

f.seek(0)

Find integer index of rows with NaN in pandas dataframe

Another simple solution is list(np.where(df['b'].isnull())[0])

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

Well in my case i was accessing an static array of a class by reference of that class, but as we know we can directly access static member via class name. So when I replaced reference with class name where I was accessing that array. It fixed this error.

Keep values selected after form submission

After trying all these "solutions", nothing work. I did some research on W3Schools before and remember there was explanation of keeping values about radio.

But it also works for the Select option. See below for an example. Just try it out and play with it.

<?php
    $example = $_POST["example"];
?>
<form method="post">
    <select name="example">
        <option <?php if (isset($example) && $example=="a") echo "selected";?>>a</option>
        <option <?php if (isset($example) && $example=="b") echo "selected";?>>b</option>
        <option <?php if (isset($example) && $example=="c") echo "selected";?>>c</option>
    </select>
    <input type="submit" name="submit" value="submit" />
</form>

setTimeout or setInterval?

When you run some function inside setInterval, which works more time than timeout-> the browser will be stuck.

- E.g., doStuff() takes 1500 sec. to be execute and you do: setInterval(doStuff, 1000);
1) Browser run doStuff() which takes 1.5 sec. to be executed;
2) After ~1 second it tries to run doStuff() again. But previous doStuff() is still executed-> so browser adds this run to the queue (to run after first is done).
3,4,..) The same adding to the queue of execution for next iterations, but doStuff() from previous are still in progress...
As the result- the browser is stuck.

To prevent this behavior, the best way is to run setTimeout inside setTimeout to emulate setInterval.
To correct timeouts between setTimeout calls, you can use self-correcting alternative to JavaScript's setInterval technique.

Corrupt jar file

It can be a typo int the MANIFEST.MF too, p.ex. Build-Date with two :

  Build-Date:: 2017-03-13 16:07:12

Difference between uint32 and uint32_t

uint32_t is standard, uint32 is not. That is, if you include <inttypes.h> or <stdint.h>, you will get a definition of uint32_t. uint32 is a typedef in some local code base, but you should not expect it to exist unless you define it yourself. And defining it yourself is a bad idea.

How to identify whether a grammar is LL(1), LR(0) or SLR(1)?

LL(1) grammar is Context free unambiguous grammar which can be parsed by LL(1) parsers.

In LL(1)

  • First L stands for scanning input from Left to Right. Second L stands for Left Most Derivation. 1 stands for using one input symbol at each step.

For Checking grammar is LL(1) you can draw predictive parsing table. And if you find any multiple entries in table then you can say grammar is not LL(1).

Their is also short cut to check if the grammar is LL(1) or not . Shortcut Technique

What are the best practices for using a GUID as a primary key, specifically regarding performance?

This link says it better than I could and helped in my decision making. I usually opt for an int as a primary key, unless I have a specific need not to and I also let SQL server auto-generate/maintain this field unless I have some specific reason not to. In reality, performance concerns need to be determined based on your specific app. There are many factors at play here including but not limited to expected db size, proper indexing, efficient querying, and more. Although people may disagree, I think in many scenarios you will not notice a difference with either option and you should choose what is more appropriate for your app and what allows you to develop easier, quicker, and more effectively (If you never complete the app what difference does the rest make :).

https://web.archive.org/web/20120812080710/http://databases.aspfaq.com/database/what-should-i-choose-for-my-primary-key.html

P.S. I'm not sure why you would use a Composite PK or what benefit you believe that would give you.

How to remove an element from the flow?

Another option is to set height: 0; overflow: visible; to an element, though it won't be really outside the flow and therefore may break margin collapsing.

How to return result of a SELECT inside a function in PostgreSQL?

Use RETURN QUERY:

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt   text   -- also visible as OUT parameter inside function
               , cnt   bigint
               , ratio bigint) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt
        , count(*) AS cnt                 -- column alias only visible inside
        , (count(*) * 100) / _max_tokens  -- I added brackets
   FROM  (
      SELECT t.txt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      LIMIT  _max_tokens
      ) t
   GROUP  BY t.txt
   ORDER  BY cnt DESC;                    -- potential ambiguity 
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM word_frequency(123);

Explanation:

  • It is much more practical to explicitly define the return type than simply declaring it as record. This way you don't have to provide a column definition list with every function call. RETURNS TABLE is one way to do that. There are others. Data types of OUT parameters have to match exactly what is returned by the query.

  • Choose names for OUT parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.

    But note the potential naming conflict between the OUT parameter cnt and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...) Postgres uses the column alias over the OUT parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:

    1. Use the ordinal position of the item in the SELECT list: ORDER BY 2 DESC. Example:
    2. Repeat the expression ORDER BY count(*).
    3. (Not applicable here.) Set the configuration parameter plpgsql.variable_conflict or use the special command #variable_conflict error | use_variable | use_column in the function. See:
  • Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt and cnt in my examples.

  • Added a missing ; and corrected a syntax error in the header. (_max_tokens int), not (int maxTokens) - type after name.

  • While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Even better: work with numeric (or a floating point type). See below.

Alternative

This is what I think your query should actually look like (calculating a relative share per token):

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt            text
               , abs_cnt        bigint
               , relative_share numeric) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt, t.cnt
        , round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2)  -- AS relative_share
   FROM  (
      SELECT t.txt, count(*) AS cnt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      GROUP  BY t.txt
      ORDER  BY cnt DESC
      LIMIT  _max_tokens
      ) t
   ORDER  BY t.cnt DESC;
END
$func$  LANGUAGE plpgsql;

The expression sum(t.cnt) OVER () is a window function. You could use a CTE instead of the subquery - pretty, but a subquery is typically cheaper in simple cases like this one.

A final explicit RETURN statement is not required (but allowed) when working with OUT parameters or RETURNS TABLE (which makes implicit use of OUT parameters).

round() with two parameters only works for numeric types. count() in the subquery produces a bigint result and a sum() over this bigint produces a numeric result, thus we deal with a numeric number automatically and everything just falls into place.

Visual Studio 2015 doesn't have cl.exe

Visual Studio 2015 doesn't install C++ by default. You have to rerun the setup, select Modify and then check Programming Language -> C++

How to use relative/absolute paths in css URLs?

Personally, I would fix this in the .htaccess file. You should have access to that.

Define your CSS URL as such:

url(/image_dir/image.png);

In your .htacess file, put:

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^image_dir/(.*) subdir/images/$1

or

RewriteRule ^image_dir/(.*) images/$1

depending on the site.

Force decimal point instead of comma in HTML5 number input (client-side)

As far as I understand it, the HTML5 input type="number always returns input.value as a string.

Apparently, input.valueAsNumber returns the current value as a floating point number. You could use this to return a value you want.

See http://diveintohtml5.info/forms.html#type-number

How to embed a SWF file in an HTML page?

I know this is an old question. But this answer will be good for the present.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>histo2</title>
        <style type="text/css" media="screen">
        html, body { height:100%; background-color: #ffff99;}
        body { margin:0; padding:0; overflow:hidden; }
        #flashContent { width:100%; height:100%; }
        </style>
    </head>
    <body>
        <div id="flashContent">
            <object type="application/x-shockwave-flash" data="histo2.swf" width="822" height="550" id="histo2" style="float: none; vertical-align:middle">
                <param name="movie" value="histo2.swf" />
                <param name="quality" value="high" />
                <param name="bgcolor" value="#ffff99" />
                <param name="play" value="true" />
                <param name="loop" value="true" />
                <param name="wmode" value="window" />
                <param name="scale" value="showall" />
                <param name="menu" value="true" />
                <param name="devicefont" value="false" />
                <param name="salign" value="" />
                <param name="allowScriptAccess" value="sameDomain" />
                <a href="http://www.adobe.com/go/getflash">
                    <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
                </a>
            </object>
        </div>
    </body>
</html>

How to hide .php extension in .htaccess

I've used this:

RewriteEngine On

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ http://example.com/folder/$1 [R=301,L]

# Redirect external .php requests to extensionless URL
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://example.com/folder/$1 [R=301,L]

# Resolve .php file for extensionless PHP URLs
RewriteRule ^([^/.]+)$ $1.php [L]

See also: this question

Ruby convert Object to Hash

Just say (current object) .attributes

.attributes returns a hash of any object. And it's much cleaner too.

printing a two dimensional array in python

There is always the easy way.

import numpy as np
print(np.matrix(A))

NLTK and Stopwords Fail #lookuperror

import nltk

nltk.download()

  • A GUI pops up and in that go the Corpora section, select the required corpus.
  • Verified Result

Fastest way to flatten / un-flatten nested JSON objects

I wrote two functions to flatten and unflatten a JSON object.


Flatten a JSON object:

var flatten = (function (isArray, wrapped) {
    return function (table) {
        return reduce("", {}, table);
    };

    function reduce(path, accumulator, table) {
        if (isArray(table)) {
            var length = table.length;

            if (length) {
                var index = 0;

                while (index < length) {
                    var property = path + "[" + index + "]", item = table[index++];
                    if (wrapped(item) !== item) accumulator[property] = item;
                    else reduce(property, accumulator, item);
                }
            } else accumulator[path] = table;
        } else {
            var empty = true;

            if (path) {
                for (var property in table) {
                    var item = table[property], property = path + "." + property, empty = false;
                    if (wrapped(item) !== item) accumulator[property] = item;
                    else reduce(property, accumulator, item);
                }
            } else {
                for (var property in table) {
                    var item = table[property], empty = false;
                    if (wrapped(item) !== item) accumulator[property] = item;
                    else reduce(property, accumulator, item);
                }
            }

            if (empty) accumulator[path] = table;
        }

        return accumulator;
    }
}(Array.isArray, Object));

Performance:

  1. It's faster than the current solution in Opera. The current solution is 26% slower in Opera.
  2. It's faster than the current solution in Firefox. The current solution is 9% slower in Firefox.
  3. It's faster than the current solution in Chrome. The current solution is 29% slower in Chrome.

Unflatten a JSON object:

function unflatten(table) {
    var result = {};

    for (var path in table) {
        var cursor = result, length = path.length, property = "", index = 0;

        while (index < length) {
            var char = path.charAt(index);

            if (char === "[") {
                var start = index + 1,
                    end = path.indexOf("]", start),
                    cursor = cursor[property] = cursor[property] || [],
                    property = path.slice(start, end),
                    index = end + 1;
            } else {
                var cursor = cursor[property] = cursor[property] || {},
                    start = char === "." ? index + 1 : index,
                    bracket = path.indexOf("[", start),
                    dot = path.indexOf(".", start);

                if (bracket < 0 && dot < 0) var end = index = length;
                else if (bracket < 0) var end = index = dot;
                else if (dot < 0) var end = index = bracket;
                else var end = index = bracket < dot ? bracket : dot;

                var property = path.slice(start, end);
            }
        }

        cursor[property] = table[path];
    }

    return result[""];
}

Performance:

  1. It's faster than the current solution in Opera. The current solution is 5% slower in Opera.
  2. It's slower than the current solution in Firefox. My solution is 26% slower in Firefox.
  3. It's slower than the current solution in Chrome. My solution is 6% slower in Chrome.

Flatten and unflatten a JSON object:

Overall my solution performs either equally well or even better than the current solution.

Performance:

  1. It's faster than the current solution in Opera. The current solution is 21% slower in Opera.
  2. It's as fast as the current solution in Firefox.
  3. It's faster than the current solution in Firefox. The current solution is 20% slower in Chrome.

Output format:

A flattened object uses the dot notation for object properties and the bracket notation for array indices:

  1. {foo:{bar:false}} => {"foo.bar":false}
  2. {a:[{b:["c","d"]}]} => {"a[0].b[0]":"c","a[0].b[1]":"d"}
  3. [1,[2,[3,4],5],6] => {"[0]":1,"[1][0]":2,"[1][1][0]":3,"[1][1][1]":4,"[1][2]":5,"[2]":6}

In my opinion this format is better than only using the dot notation:

  1. {foo:{bar:false}} => {"foo.bar":false}
  2. {a:[{b:["c","d"]}]} => {"a.0.b.0":"c","a.0.b.1":"d"}
  3. [1,[2,[3,4],5],6] => {"0":1,"1.0":2,"1.1.0":3,"1.1.1":4,"1.2":5,"2":6}

Advantages:

  1. Flattening an object is faster than the current solution.
  2. Flattening and unflattening an object is as fast as or faster than the current solution.
  3. Flattened objects use both the dot notation and the bracket notation for readability.

Disadvantages:

  1. Unflattening an object is slower than the current solution in most (but not all) cases.

The current JSFiddle demo gave the following values as output:

Nested : 132175 : 63
Flattened : 132175 : 564
Nested : 132175 : 54
Flattened : 132175 : 508

My updated JSFiddle demo gave the following values as output:

Nested : 132175 : 59
Flattened : 132175 : 514
Nested : 132175 : 60
Flattened : 132175 : 451

I'm not really sure what that means, so I'll stick with the jsPerf results. After all jsPerf is a performance benchmarking utility. JSFiddle is not.

how to remove the dotted line around the clicked a element in html

Like @Lo Juego said, read the article

a, a:active, a:focus {
   outline: none;
}

How to unload a package without restarting R

I would like to add an alternative solution. This solution does not directly answer your question on unloading a package but, IMHO, provides a cleaner alternative to achieve your desired goal, which I understand, is broadly concerned with avoiding name conflicts and trying different functions, as stated:

mostly because restarting R as I try out different, conflicting packages is getting frustrating, but conceivably this could be used in a program to use one function and then another--although namespace referencing is probably a better idea for that use

Solution

Function with_package offered via the withr package offers the possibility to:

attache a package to the search path, executes the code, then removes the package from the search path. The package namespace is not unloaded, however.

Example

library(withr)
with_package("ggplot2", {
  ggplot(mtcars) + geom_point(aes(wt, hp))
})
# Calling geom_point outside withr context 
exists("geom_point")
# [1] FALSE

geom_point used in the example is not accessible from the global namespace. I reckon it may be a cleaner way of handling conflicts than loading and unloading packages.

What's the difference between JPA and Hibernate?

JPA or Java Persistence API is a standard specification for ORM implementations whereas Hibernate is the actual ORM implementation or framework.

How do you get the magnitude of a vector in Numpy?

You can do this concisely using the toolbelt vg. It's a light layer on top of numpy and it supports single values and stacked vectors.

import numpy as np
import vg

x = np.array([1, 2, 3, 4, 5])
mag1 = np.linalg.norm(x)
mag2 = vg.magnitude(x)
print mag1 == mag2
# True

I created the library at my last startup, where it was motivated by uses like this: simple ideas which are far too verbose in NumPy.

How do I open a Visual Studio project in design view?

My problem, it showed an error called "The class Form1 can be designed, but is not the first class in the file. Visual Studio requires that designers use the first class in the file. Move the class code so that it is the first class in the file and try loading the designer again. ". So I moved the Form class to the first one and it worked. :)

Change directory in Node.js command prompt

Type .exit in command prompt window, It terminates the node repl.

How to import an existing directory into Eclipse?

The Eclipse UI is a little bit confusing.

The Import -> "Existing projects into workspace" actually means import "Existing Eclipse projects into workspace". That's why you can't click on finish: the import option looks for a .project file (the file used by Eclipse to store the project options) in the directory that you have chosen.

To import existing source code that doesn't have an Eclipse project file you have the following options (I suppose that you want to create a Java project):

  1. New project inside the workspace dir: Create a new empty Java project into the workspace (File->New->Java Project). Then right click on the source folder and choose Import...->General->File system then choose your files, and it will make a copy of your files.

    Tip: you can drag&drop your files from the Finder into the src folder.

  2. Create an eclipse project in your existing dir: Create a new Java project, but in the "New Java Project" window:

    • Un check the Use default location option, and choose the directory where is your non-Eclipse project.
    • Click Next and configure the sub-directories of your non-Eclipse project where the source files are located. And you are done :)

Change connection string & reload app.config at run time

You can also refresh the configuration in it's entirety:

ConnectionStringSettings importToConnectionString = currentConfiguration.ConnectionStrings.ConnectionStrings[newName];

if (importToConnectionString == null)
{
    importToConnectionString = new ConnectionStringSettings();
    importToConnectionString.ConnectionString = importFromConnectionString.ConnectionString;
    importToConnectionString.ProviderName = importFromConnectionString.ProviderName;
    importToConnectionString.Name = newName;
    currentConfiguration.ConnectionStrings.ConnectionStrings.Add(importToConnectionString);
}
else
{
    importToConnectionString.ConnectionString = importFromConnectionString.ConnectionString;
    importToConnectionString.ProviderName = importFromConnectionString.ProviderName;
}

Properties.Settings.Default.Reload();

Remove an onclick listener

Perhaps setOnClickListener(null) ?

An attempt was made to access a socket in a way forbidden by its access permissions

My windows firewall was blocking port 8080 so i changed it to 5000 and it worked!

Current timestamp as filename in Java

Improving the @Derek Springer post with fill length function:

public static String getFileWithDate(String fileName, String fileSaperator, String dateFormat) {
    String FileNamePrefix = fileName.substring(0, fileName.lastIndexOf(fileSaperator));
    String FileNameSuffix = fileName.substring(fileName.lastIndexOf(fileSaperator)+1, fileName.length());
    //System.out.println("File= Prefix~Suffix:"+FileNamePrefix +"~"+FileNameSuffix);
    
    String newFileName = new SimpleDateFormat("'"+FileNamePrefix+"_'"+dateFormat+"'"+fileSaperator+FileNameSuffix+"'").format(new Date());
    System.out.println("New File:"+newFileName);
    return newFileName;
}

Using the funciton and its Output:

String fileSaperator = ".", format = "yyyyMMMdd_HHmm";
getFileWithDate("Text1.txt", fileSaperator, format);
getFileWithDate("Text1.doc", fileSaperator, format);
getFileWithDate("Text1.txt.json", fileSaperator, format);

Output:

Old File:Text1.txt   New File:Text1_2020Nov11_1807.txt
Old File:Text1.doc   New File:Text1_2020Nov11_1807.doc
Old File:Text1.txt.json  New File:Text1.txt_2020Nov11_1807.json

SSL Error: unable to get local issuer certificate

jww is right — you're referencing the wrong intermediate certificate.

As you have been issued with a SHA256 certificate, you will need the SHA256 intermediate. You can grab it from here: http://secure2.alphassl.com/cacert/gsalphasha2g2r1.crt

Command line .cmd/.bat script, how to get directory of running script

for /F "eol= delims=~" %%d in ('CD') do set curdir=%%d

pushd %curdir%

Source

how to delete files from amazon s3 bucket?

Using the Python boto3 SDK (and assuming credentials are setup for AWS), the following will delete a specified object in a bucket:

import boto3

client = boto3.client('s3')
client.delete_object(Bucket='mybucketname', Key='myfile.whatever')

How can I add a custom HTTP header to ajax request with js or jQuery?

There are several solutions depending on what you need...

If you want to add a custom header (or set of headers) to an individual request then just add the headers property:

// Request with custom header
$.ajax({
    url: 'foo/bar',
    headers: { 'x-my-custom-header': 'some value' }
});

If you want to add a default header (or set of headers) to every request then use $.ajaxSetup():

$.ajaxSetup({
    headers: { 'x-my-custom-header': 'some value' }
});

// Sends your custom header
$.ajax({ url: 'foo/bar' });

// Overwrites the default header with a new header
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });

If you want to add a header (or set of headers) to every request then use the beforeSend hook with $.ajaxSetup():

$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('x-my-custom-header', 'some value');
    }
});

// Sends your custom header
$.ajax({ url: 'foo/bar' });

// Sends both custom headers
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });

Edit (more info): One thing to be aware of is that with ajaxSetup you can only define one set of default headers and you can only define one beforeSend. If you call ajaxSetup multiple times, only the last set of headers will be sent and only the last before-send callback will execute.

How to download/checkout a project from Google Code in Windows?

Thanks Mr. Tom Chantler adding that to get the exe http://downloadsvn.codeplex.com/ to pull the SVN source

just note that suppose you're downloading the below project: you have to enter exactly the following to donwload it in the exe URL:

http://myproject.googlecode.com/svn/trunk/

developer not taking care of appending the h t t p : / / if it does not exist. Hope it saves somebody's time.

Ignoring new fields on JSON objects using Jackson

If using a pojo class based on JSON response. If chances are there that json changes frequently declare at pojo class level:

@JsonIgnoreProperties(ignoreUnknown = true)

and at the objectMapper add this if you are converting:

objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

So that code will not break.

mssql '5 (Access is denied.)' error during restoring database

this happened to me earlier today, i was a member of the local server's admin group and have unimpeded access, or i thought so. I also ticked the "replace" option, even though there is no such DB in the instance.

Found out that there used to be DB of the same name there, and the MDF and LDF files are still physically located at the data and log folders of the server, but the actual metadata is missing in the sys.databases. the service account of SQL server also can't ovewrwrite the existing files. Found out also that the files' owner is "unknown", i had to change ownership, to the 2 files above so that it is now owned by the local server's admin group, then renamed it.

Then finally, it worked.

Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined

solve this issue for angular

"styles": [
              "src/styles.css",
              "node_modules/bootstrap/dist/css/bootstrap.min.css"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.min.js",
              "node_modules/bootstrap/dist/js/bootstrap.min.js"
            ]

CSS: How to remove pseudo elements (after, before,...)?

p:after {
   content: none;
}

none is the official value to set the content, if specified, to nothing.

http://www.w3schools.com/cssref/pr_gen_content.asp

Prevent a webpage from navigating away using JavaScript

I ended up with this slightly different version:

var dirty = false;
window.onbeforeunload = function() {
    return dirty ? "If you leave this page you will lose your unsaved changes." : null;
}

Elsewhere I set the dirty flag to true when the form gets dirtied (or I otherwise want to prevent navigating away). This allows me to easily control whether or not the user gets the Confirm Navigation prompt.

With the text in the selected answer you see redundant prompts:

enter image description here

Facebook Architecture

Well Facebook has undergone MANY many changes and it wasn't originally designed to be efficient. It was designed to do it's job. I have absolutely no idea what the code looks like and you probably won't find much info about it (for obvious security and copyright reasons), but just take a look at the API. Look at how often it changes and how much of it doesn't work properly, anymore, or at all.

I think the biggest ace up their sleeve is the Hiphop. http://developers.facebook.com/blog/post/358 You can use HipHop yourself: https://github.com/facebook/hiphop-php/wiki

But if you ask me it's a very ambitious and probably time wasting task. Hiphop only supports so much, it can't simply convert everything to C++. So what does this tell us? Well, it tells us that Facebook is NOT fully taking advantage of the PHP language. It's not using the latest 5.3 and I'm willing to bet there's still a lot that is PHP 4 compatible. Otherwise, they couldn't use HipHop. HipHop IS A GOOD IDEA and needs to grow and expand, but in it's current state it's not really useful for that many people who are building NEW PHP apps.

There's also PHP to JAVA via things like Resin/Quercus. Again, it doesn't support everything...

Another thing to note is that if you use any non-standard PHP module, you aren't going to be able to convert that code to C++ or Java either. However...Let's take a look at PHP modules. They are ARE compiled in C++. So if you can build PHP modules that do things (like parse XML, etc.) then you are basically (minus some interaction) working at the same speed. Of course you can't just make a PHP module for every possible need and your entire app because you would have to recompile and it would be much more difficult to code, etc.

However...There are some handy PHP modules that can help with speed concerns. Though at the end of the day, we have this awesome thing known as "the cloud" and with it, we can scale our applications (PHP included) so it doesn't matter as much anymore. Hardware is becoming cheaper and cheaper. Amazon just lowered it's prices (again) speaking of.

So as long as you code your PHP app around the idea that it will need to one day scale...Then I think you're fine and I'm not really sure I'd even look at Facebook and what they did because when they did it, it was a completely different world and now trying to hold up that infrastructure and maintain it...Well, you get things like HipHop.

Now how is HipHop going to help you? It won't. It can't. You're starting fresh, you can use PHP 5.3. I'd highly recommend looking into PHP 5.3 frameworks and all the new benefits that PHP 5.3 brings to the table along with the SPL libraries and also think about your database too. You're most likely serving up content from a database, so check out MongoDB and other types of databases that are schema-less and document-oriented. They are much much faster and better for the most "common" type of web site/app.

Look at NEW companies like Foursquare and Smugmug and some other companies that are utilizing NEW technology and HOW they are using it. For as successful as Facebook is, I honestly would not look at them for "how" to build an efficient web site/app. I'm not saying they don't have very (very) talented people that work there that are solving (their) problems creatively...I'm also not saying that Facebook isn't a great idea in general and that it's not successful and that you shouldn't get ideas from it....I'm just saying that if you could view their entire source code, you probably wouldn't benefit from it.

npm install error from the terminal

In my case it was due to a bad URL (http:// instead of git://, no .git at the end) for one of the dependencies.

Add User to Role ASP.NET Identity

This one works for me. You can see this code on AccountController -> Register

var user = new JobUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
    //add this to add role to user
     await UserManager.AddToRoleAsync(user.Id, "Name of your role");
}

but the role name must exist in your AspNetRoles table.

What does file:///android_asset/www/index.html mean?

file:/// is a URI (Uniform Resource Identifier) that simply distinguishes from the standard URI that we all know of too well - http://.

It does imply an absolute path name pointing to the root directory in any environment, but in the context of Android, it's a convention to tell the Android run-time to say "Here, the directory www has a file called index.html located in the assets folder in the root of the project".

That is how assets are loaded at runtime, for example, a WebView widget would know exactly where to load the embedded resource file by specifying the file:/// URI.

Consider the code example:

WebView webViewer = (WebView) findViewById(R.id.webViewer);
webView.loadUrl("file:///android_asset/www/index.html");

A very easy mistake to make here is this, some would infer it to as file:///android_assets, notice the plural of assets in the URI and wonder why the embedded resource is not working!

How do I change the UUID of a virtual disk?

The correct command is the following one.

VBoxManage internalcommands sethduuid "/home/user/VirtualBox VMs/drupal/drupal.vhd"

The path for the virtual disk contains a space, so it must be enclosed in double quotes to avoid it is parsed as two parameters.

Does JavaScript have the interface type (such as Java's 'interface')?

I know this is an old one, but I've recently found myself needing more and more to have a handy API for checking objects against interfaces. So I wrote this: https://github.com/tomhicks/methodical

It's also available via NPM: npm install methodical

It basically does everything suggested above, with some options for being a bit more strict, and all without having to do loads of if (typeof x.method === 'function') boilerplate.

Hopefully someone finds it useful.

javascript find and remove object in array based on key value

You can simplify this, and there's really no need for using jquery here.

var id = 88;

for(var i = 0; i < data.length; i++) {
    if(data[i].id == id) {
        data.splice(i, 1);
        break;
    }
}

Just iterate through the list, find the matching id, splice, and then break to exit your loop

How to change the data type of a column without dropping the column with query?

ALTER TABLE YourTableNameHere ALTER COLUMN YourColumnNameHere VARCHAR(20)

When using Trusted_Connection=true and SQL Server authentication, will this affect performance?

Not 100% sure what you mean:

Trusted_Connection=True;

IS using Windows credentials and is 100% equivalent to:

Integrated Security=SSPI;

or

Integrated Security=true;

If you don't want to use integrated security / trusted connection, you need to specify user id and password explicitly in the connection string (and leave out any reference to Trusted_Connection or Integrated Security)

server=yourservername;database=yourdatabase;user id=YourUser;pwd=TopSecret

Only in this case, the SQL Server authentication mode is used.

If any of these two settings is present (Trusted_Connection=true or Integrated Security=true/SSPI), then the Windows credentials of the current user are used to authenticate against SQL Server and any user iD= setting will be ignored and not used.

For reference, see the Connection Strings site for SQL Server 2005 with lots of samples and explanations.

Using Windows Authentication is the preferred and recommended way of doing things, but it might incur a slight delay since SQL Server would have to authenticate your credentials against Active Directory (typically). I have no idea how much that slight delay might be, and I haven't found any references for that.


Summing up:

If you specify either Trusted_Connection=True; or Integrated Security=SSPI; or Integrated Security=true; in your connection string

==> THEN (and only then) you have Windows Authentication happening. Any user id= setting in the connection string will be ignored.


If you DO NOT specify either of those settings,

==> then you DO NOT have Windows Authentication happening (SQL Authentication mode will be used)


How do you enable auto-complete functionality in Visual Studio C++ express edition?

I came across over the following post: http://blogs.msdn.com/b/raulperez/archive/2010/03/19/c-intellisense-options.aspx

The issue is that the "IntelliSense" option in c++ is disabled. This link explains about the IntelliSense database configuration and options.

After enabling the database you must close and reopen visual studio for autocomplete use 'ctrl'+'space'

Creating threads - Task.Factory.StartNew vs new Thread()

Your first block of code tells CLR to create a Thread (say. T) for you which is can be run as background (use thread pool threads when scheduling T ). In concise, you explicitly ask CLR to create a thread for you to do something and call Start() method on thread to start.

Your second block of code does the same but delegate (implicitly handover) the responsibility of creating thread (background- which again run in thread pool) and the starting thread through StartNew method in the Task Factory implementation.

This is a quick difference between given code blocks. Having said that, there are few detailed difference which you can google or see other answers from my fellow contributors.

What is the shortcut in IntelliJ IDEA to find method / functions?

To Find the actions build in the IDEA(reindent, create new, ...) you can use

CRTL+SHIFT+A

then type indent for example and ENTER.

Makefile: How to correctly include header file and its directory?

This is not a question about make, it is a question about the semantic of the #include directive.

The problem is, that there is no file at the path "../StdCUtil/StdCUtil/split.h". This is the path that results when the compiler combines the include path "../StdCUtil" with the relative path from the #include directive "StdCUtil/split.h".

To fix this, just use -I.. instead of -I../StdCUtil.

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

It seems daft, but I think when you use the same bind variable twice you have to set it twice:

cmd.Parameters.Add("VarA", "24");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarC", "1234");
cmd.Parameters.Add("VarC", "1234");

Certainly that's true with Native Dynamic SQL in PL/SQL:

SQL> begin
  2     execute immediate 'select * from emp where ename=:name and ename=:name'
  3     using 'KING';
  4  end;
  5  /
begin
*
ERROR at line 1:
ORA-01008: not all variables bound


SQL> begin
  2     execute immediate 'select * from emp where ename=:name and ename=:name' 
  3     using 'KING', 'KING';
  4  end;
  5  /

PL/SQL procedure successfully completed.

How to add calendar events in Android?

i used the code below, it solves my problem to add event in default device calendar in ICS and also on version less that ICS

    if (Build.VERSION.SDK_INT >= 14) {
        Intent intent = new Intent(Intent.ACTION_INSERT)
        .setData(Events.CONTENT_URI)
        .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis())
        .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis())
        .putExtra(Events.TITLE, "Yoga")
        .putExtra(Events.DESCRIPTION, "Group class")
        .putExtra(Events.EVENT_LOCATION, "The gym")
        .putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY)
        .putExtra(Intent.EXTRA_EMAIL, "[email protected],[email protected]");
         startActivity(intent);
}

    else {
        Calendar cal = Calendar.getInstance();              
        Intent intent = new Intent(Intent.ACTION_EDIT);
        intent.setType("vnd.android.cursor.item/event");
        intent.putExtra("beginTime", cal.getTimeInMillis());
        intent.putExtra("allDay", true);
        intent.putExtra("rrule", "FREQ=YEARLY");
        intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
        intent.putExtra("title", "A Test Event from android app");
        startActivity(intent);
        }

Hope it would help.....

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

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

Stream is a base class, you need to create one of the specific types of streams, such as MemoryStream.

Why ModelState.IsValid always return false in mvc

Please post your Model Class.

To check the errors in your ModelState use the following code:

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

OR: You can also use

var errors = ModelState.Values.SelectMany(v => v.Errors);

Place a break point at the above line and see what are the errors in your ModelState.

Font is not available to the JVM with Jasper Reports

If you are using maven in your project, you can just add the jasper-fonts dependency to pom.xml:

<dependency>
    <groupId>net.sf.jasperreports</groupId>
    <artifactId>jasperreports-fonts</artifactId>
    <version>6.8.1</version>
</dependency>

Installing the missing font on the system may be a working solution but not for me, I didn't want to have to install the missing fonts after each deployment in a new server, instead I opted for embedding the font with the application.

Regards.

Remove rows with all or some NAs (missing values) in data.frame

Assuming dat as your dataframe, the expected output can be achieved using

1.rowSums

> dat[!rowSums((is.na(dat))),]
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0   2    2    2    2
6 ENSG00000221312    0   1    2    3    2

2.lapply

> dat[!Reduce('|',lapply(dat,is.na)),]
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0   2    2    2    2
6 ENSG00000221312    0   1    2    3    2

phpMyAdmin - Error > Incorrect format parameter?

Just gone through the same problem when trying to import a CSV (400 MBs) and was also getting an error in red saying

Error - incorrect format parameter

Initially thought it could have been the parameters and tested again. Faster, from my previous experince with it, I realized that it was due to other reasons (size of the file, execution of script has a maximum time defined, etc).

So, I've gone to php.ini

php.ini

and changed the values from the following settings

max_execution_time = 3000
max_input_time = 120
memory_limit = 512M
post_max_size = 1500M
upload_max_filesize = 1500M 

After this modification, stoped MySQL and Apache and started them again, went to phpmyadmin trying to import. Then I reached another error

Fatal error: Maximum execution time of 300 seconds exceeded

which was fixed by simply setting in xampp/phpmyadmin/libraries/config.default.php

config.default.php

$cfg['ExecTimeLimit'] = 0;

Setting it to 0 disables execution time limits.

Then, after a while, the import happened without problems.

How to select rows with no matching entry in another table?

How to select rows with no matching entry in Both table?


    select * from [dbo].[EmppDetails] e
     right join [Employee].[Gender] d on e.Gid=d.Gid
    where e.Gid is Null

    union 
    select * from [dbo].[EmppDetails] e
     left join [Employee].[Gender] d on e.Gid=d.Gid
    where d.Gid is Null

get and set in TypeScript

Here's a working example that should point you in the right direction:

class Foo {
    _name;

    get Name() {
        return this._name;
    }

    set Name(val) {
        this._name = val;
    }
}

Getters and setters in JavaScript are just normal functions. The setter is a function that takes a parameter whose value is the value being set.

How to permanently remove few commits from remote branch

Sometimes the easiest way to fix this issue is to make a new branch from the place where you know the code is good. Then you can leave the errant branch history alone in case you need to cherry-pick other commits from it later. This also ensures you did not lose any commit history.

From your local errant branch:

git log

copy the commit hash that you wanted the branch to be at and exit the git log

git checkout theHashYouJustCopied
git checkout -b your_new_awesome_branch

Now you have a new branch just the way you want it.

If you also needed to keep a specific commit from the errant branch that is not on your new branch, you can just cherry-pick that specific commit you need:

git checkout the_errant_branch
git log

Copy the commit hash of the one commit you need to pull into the good branch and exit the git log.

git checkout your_new_awesome_branch
git cherry-pick theHashYouJustCopied

Pat yourself on the back.

Spark java.lang.OutOfMemoryError: Java heap space

To add a use case to this that is often not discussed, I will pose a solution when submitting a Spark application via spark-submit in local mode.

According to the gitbook Mastering Apache Spark by Jacek Laskowski:

You can run Spark in local mode. In this non-distributed single-JVM deployment mode, Spark spawns all the execution components - driver, executor, backend, and master - in the same JVM. This is the only mode where a driver is used for execution.

Thus, if you are experiencing OOM errors with the heap, it suffices to adjust the driver-memory rather than the executor-memory.

Here is an example:

spark-1.6.1/bin/spark-submit
  --class "MyClass"
  --driver-memory 12g
  --master local[*] 
  target/scala-2.10/simple-project_2.10-1.0.jar 

SQL LEFT-JOIN on 2 fields for MySQL

Let's try this way:

select 
    a.ip, 
    a.os, 
    a.hostname, 
    a.port, 
    a.protocol, 
    b.state
from a
left join b 
    on a.ip = b.ip 
        and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/

So, in where clause you can filter result set by column from right table only on this way:

...
where b.somecolumn <> (=) null

Launch Image does not show up in my iOS App

So this has been quite painful for something that should be trivial. Here is what I did:

Use xcassets

I decided to use .xcassets versus the .xib for launch. I deleted the .xib. If you have images.xcassets already in your project then great, otherwise you can add one from File>New>file:

AddNewASsetCatalog

Create a Launch Image Set

Now create at a minimum a launchimage set and icon set in your .xcassets file by right clicking in the navigator area.

Add new Launch image and app icon

Update the App Icons and Launch Images Settings

Then I made sure that the "Apps icon and image sets" in my target are as below.

Very Important: Make sure the "Launch screen file" setting is blank.

Apps icon and image sets

Add the Images

Last but not least, the terminology used by Apple for the device selection is confusing. Initially I thought that since I am deploying for iOS8 only (iPhone Portrait), I can do this and just put in the iPhone 6 and iPhone 6+ launch images:

Devices

I quickly realized that is not the way this works and I was getting a warning: "An iPhone Retina (4-inch) launch image for iOS 7.0 and later is required."

So I had to select the iPhone under iOS 7.0 and later as well and add an Image for the iPhone 5s.

So to find out which boxes to check on the right, do not ask the question: What is my minimum iOS and device and device orientation but rather ask:

What devices out there can support my minimum iOS? Now What is the minimum iOS supported on those devices? And make sure you check all of those boxes. So for me, I am targeting iPhone 5s, 6 and 6 Plus at 8.0 but given that iPhone 5s can exist with 7.0, I need to check the 7.0 box as well to show the image placeholder. In other words, the (iOS) check box on the right shows you the minimum iOS version available for that device and you need to click it to show the image placeholder and put an image regardless of whether you are deploying at this iOS version or not.

Hope this helps somebody.

Adding all devices

enter image description here

Bootstrap 3 Collapse show state with Chevron icon

One-liner.

i.fa.fa-chevron-right.collapse.in { transform: rotate(180deg); }

In this example it's being used to group collapsible table rows. The only thing you need to do is add the target class name (my-collapse-name) to your icon:

<tr data-toggle="collapse" data-target=".my-collapse-name">
    <th><i class="fa fa-chevron-right my-collapse-name"></span></th>
    <th>Master Row - Title</th>
</tr>
<tr class="collapse my-collapse-name">
    <td></td>
    <td>Detail Row - Content</td>
</tr>

You could accomplish the same with Bootstrap's native caret class by using <span class='caret my-collapse-name'></span> and span.caret.collapse.in { transform: rotate(90deg); }

How does lock work exactly?

The lock statement is translated by C# 3.0 to the following:

var temp = obj;

Monitor.Enter(temp);

try
{
    // body
}
finally
{
    Monitor.Exit(temp);
}

In C# 4.0 this has changed and it is now generated as follows:

bool lockWasTaken = false;
var temp = obj;
try
{
    Monitor.Enter(temp, ref lockWasTaken);
    // body
}
finally
{
    if (lockWasTaken)
    {
        Monitor.Exit(temp); 
    }
}

You can find more info about what Monitor.Enter does here. To quote MSDN:

Use Enter to acquire the Monitor on the object passed as the parameter. If another thread has executed an Enter on the object but has not yet executed the corresponding Exit, the current thread will block until the other thread releases the object. It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock.

The Monitor.Enter method will wait infinitely; it will not time out.

Extracting columns from text file with different delimiters in Linux

You can use cut with a delimiter like this:

with space delim:

cut -d " " -f1-100,1000-1005 infile.csv > outfile.csv

with tab delim:

cut -d$'\t' -f1-100,1000-1005 infile.csv > outfile.csv

I gave you the version of cut in which you can extract a list of intervals...

Hope it helps!

How to convert the following json string to java object?

Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(response);// response will be the json String
YourPojo emp = gson.fromJson(object, YourPojo.class); 

Android Studio Stuck at Gradle Download on create new project

Invalidate Caches and Restart

It worked for me.

LINQ - Left Join, Group By, and Count

LATE ANSWER:

You shouldn't need the left join at all if all you're doing is Count(). Note that join...into is actually translated to GroupJoin which returns groupings like new{parent,IEnumerable<child>} so you just need to call Count() on the group:

from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into g
select new { ParentId = p.Id, Count = g.Count() }

In Extension Method syntax a join into is equivalent to GroupJoin (while a join without an into is Join):

context.ParentTable
    .GroupJoin(
                   inner: context.ChildTable
        outerKeySelector: parent => parent.ParentId,
        innerKeySelector: child => child.ParentId,
          resultSelector: (parent, children) => new { parent.Id, Count = children.Count() }
    );

Is Spring annotation @Controller same as @Service?

You can declare a @service as @Controller.

You can NOT declare an @Controller as @Service

@Service

It is regular. You are just declaring class as a Component.

@Controller

It is a little more special than Component. The dispatcher will search for @RequestMapping here. So a class annotated with @Controller, will be additionally empowered with declaring URLs through which APIs are called

Tracking the script execution time in PHP

$_SERVER['REQUEST_TIME']

check out that too. i.e.

...
// your codes running
...
echo (time() - $_SERVER['REQUEST_TIME']);

How to make a phone call programmatically?

Tried this on my phone and it works perfectly.

Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:900..." ));
startActivity(intent);

Add this permission in manifest file.

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

How to convert a string to character array in c (or) how to extract a single char form string?

In C, a string is actually stored as an array of characters, so the 'string pointer' is pointing to the first character. For instance,

char myString[] = "This is some text";

You can access any character as a simple char by using myString as an array, thus:

char myChar = myString[6];
printf("%c\n", myChar); // Prints s

Hope this helps! David

How to initialize array to 0 in C?

Global variables and static variables are automatically initialized to zero. If you have simply

char ZEROARRAY[1024];

at global scope it will be all zeros at runtime. But actually there is a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. You could write:

char ZEROARRAY[1024] = {0};

The compiler would fill the unwritten entries with zeros. Alternatively you could use memset to initialize the array at program startup:

memset(ZEROARRAY, 0, 1024);

That would be useful if you had changed it and wanted to reset it back to all zeros.

jQuery won't parse my JSON from AJAX query

I was getting status = parseerror and xhr.status = 200.

The issue for me was the URL's inside the JSON response had '\' switching to '/' fixed this.

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

Yet another Googlemare Landmine.... Somehow, if you mess up, the icon line on your .gen file dies. (Empirical proof of mine after struggling 2 hours)

Insert a new icon 72x72 icon on the hdpi folder with a different name from the original, and update the name on the manifest also.

The icon somehow resurrects on the Gen file and voila!! time to move on.

XML Parsing - Read a Simple XML File and Retrieve Values

Are you familiar with the DataSet class?

The DataSet can also load XML documents and you may find it easier to iterate.

http://msdn.microsoft.com/en-us/library/system.data.dataset.readxml.aspx

DataSet dt = new DataSet();
dt.ReadXml(@"c:\test.xml");

Counting DISTINCT over multiple columns

How about this,

Select DocumentId, DocumentSessionId, count(*) as c 
from DocumentOutputItems 
group by DocumentId, DocumentSessionId;

This will get us the count of all possible combinations of DocumentId, and DocumentSessionId

Concatenating variables in Bash

Try doing this, there's no special character to concatenate in bash :

mystring="${arg1}12${arg2}endoffile"

explanations

If you don't put brackets, you will ask to concatenate $arg112 + $argendoffile (I guess that's not what you asked) like in the following example :

mystring="$arg112$arg2endoffile"

The brackets are delimiters for the variables when needed. When not needed, you can use it or not.

another solution

(less portable : require bash > 3.1)

$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile

See http://mywiki.wooledge.org/BashFAQ/013

SQL ORDER BY multiple columns

yes,the sorting proceed differently. in first scenario, orders based on column1 and in addition to that process further by sorting colmun2 based on column1 .. in second scenario ,it orders completely based on column 1 only... please proceed with a simple example...u will get quickly..

Android: checkbox listener

If you are looking to do this in Kotlin with the interface implementation.

class MainActivity: AppCompatActivity(),CompoundButton.OnCheckedChangeListener{

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

      val yourCheckBox = findViewById<CheckBox>(R.id.check_box)
      yourCheckBox.setOnCheckedChangeListener(this)

    }

 override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        when(buttonView?.id){
            R.id.check_box -> Log.d("Checked: ","$isChecked")
        }
    }

}

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

How do you return a JSON object from a Java Servlet

response.setContentType("text/json");

//create the JSON string, I suggest using some framework.

String your_string;

out.write(your_string.getBytes("UTF-8"));

Excel 2013 VBA Clear All Filters macro

For tables try this to check if it's on and turn off:

If wrkSheetCodeName.ListObjects("TableName").ShowAutoFilter Then
    wrkSheetCodeName.ListObjects("TableName").Range.AutoFilter
End if

To Turn back on:

wrkSheetCodeName.ListObjects("TableName").Range.AutoFilter

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

How to select rows with NaN in particular column?

@qbzenker provided the most idiomatic method IMO

Here are a few alternatives:

In [28]: df.query('Col2 != Col2') # Using the fact that: np.nan != np.nan
Out[28]:
   Col1  Col2  Col3
1     0   NaN   0.0

In [29]: df[np.isnan(df.Col2)]
Out[29]:
   Col1  Col2  Col3
1     0   NaN   0.0

Converting A String To Hexadecimal In Java

Convert a letter in hex code and hex code in letter.

        String letter = "a";
    String code;
    int decimal;

    code = Integer.toHexString(letter.charAt(0));
    decimal = Integer.parseInt(code, 16);

    System.out.println("Hex code to " + letter + " = " + code);
    System.out.println("Char to " + code + " = " + (char) decimal);

Android - styling seek bar

Simple Way to change the seek bar color ...

 <ProgressBar
            android:id="@+id/progress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:theme="@style/Progress_color"/>

Style : Progress_color

 <style name="Progress_color">
    <item name="colorAccent">@color/white</item> <!-- Whatever color you want-->
</style>

java class change ProgressDrawable()

seek_bar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.MULTIPLY);

Using LIMIT within GROUP BY to get N results per group?

Please try below stored procedure. I have already verified. I am getting proper result but without using groupby.

CREATE DEFINER=`ks_root`@`%` PROCEDURE `first_five_record_per_id`()
BEGIN
DECLARE query_string text;
DECLARE datasource1 varchar(24);
DECLARE done INT DEFAULT 0;
DECLARE tenants varchar(50);
DECLARE cur1 CURSOR FOR SELECT rid FROM demo1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    SET @query_string='';

      OPEN cur1;
      read_loop: LOOP

      FETCH cur1 INTO tenants ;

      IF done THEN
        LEAVE read_loop;
      END IF;

      SET @datasource1 = tenants;
      SET @query_string = concat(@query_string,'(select * from demo  where `id` = ''',@datasource1,''' order by rate desc LIMIT 5) UNION ALL ');

       END LOOP; 
      close cur1;

    SET @query_string  = TRIM(TRAILING 'UNION ALL' FROM TRIM(@query_string));  
  select @query_string;
PREPARE stmt FROM @query_string;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

END

error: pathspec 'test-branch' did not match any file(s) known to git

The modern Git should able to detect remote branches and create a local one on checkout.

However if you did a shallow clone (e.g. with --depth 1), try the following commands to correct it:

git config remote.origin.fetch '+refs/heads/*:refs/remotes/origin/*'
git fetch --all

and try to checkout out the branch again.

Alternatively try to unshallow your clone, e.g. git fetch --unshallow and try again.

See also: How to fetch all remote branches?

HTML: How to limit file upload to be only images?

Checkout a project called Uploadify. http://www.uploadify.com/

It's a Flash + jQuery based file uploader. This uses Flash's file selection dialog, which gives you the ability to filter file types, select multiple files at the same time, etc.

Embed youtube videos that play in fullscreen automatically

This was pretty well answered over here: How to make a YouTube embedded video a full page width one?

If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)

<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

of the video it should play on load. Here's a demo over at jsfiddle.

How do I check for vowels in JavaScript?

I kind of like this method which I think covers all the bases:

const matches = str.match(/aeiou/gi];
return matches ? matches.length : 0;

CMake unable to determine linker language with C++

I managed to solve mine, by changing

add_executable(file1.cpp)

to

add_executable(ProjectName file1.cpp)

What is SELF JOIN and when would you use it?

SQL self-join simply is a normal join which is used to join a table to itself.

Example:

Select *
FROM Table t1, Table t2
WHERE t1.Id = t2.ID

Oracle: not a valid month

You can also change the value of this database parameter for your session by using the ALTER SESSION command and use it as you wanted

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MM-YYYY';
SELECT TO_DATE('05-12-2015') FROM dual;

05/12/2015

Powershell import-module doesn't find modules

I experienced the same error and tried numerous things before I succeeded. The solution was to prepend the path of the script to the relative path of the module like this:

// Note that .Path will only be available during script-execution
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path

Import-Module $ScriptPath\Modules\Builder.psm1

Btw you should take a look at http://msdn.microsoft.com/en-us/library/dd878284(v=vs.85).aspx which states:

Beginning in Windows PowerShell 3.0, modules are imported automatically when any cmdlet or function in the module is used in a command. This feature works on any module in a directory that this included in the value of the PSModulePath environment variable ($env:PSModulePath)

How do I select the parent form based on which submit button is clicked?

You can select the form like this:

$("#submit").click(function(){
    var form = $(this).parents('form:first');
    ...
});

However, it is generally better to attach the event to the submit event of the form itself, as it will trigger even when submitting by pressing the enter key from one of the fields:

$('form#myform1').submit(function(e){
     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission
});

To select fields inside the form, use the form context. For example:

$("input[name='somename']",form).val();

RSpec: how to test if a method was called?

it "should call 'bar' with appropriate arguments" do
  expect(subject).to receive(:bar).with("an argument I want")
  subject.foo
end

Getting the last argument passed to a shell script

From oldest to newer solutions:

The most portable solution, even older sh (works with spaces and glob characters) (no loop, faster):

eval printf "'%s\n'" "\"\${$#}\""

Since version 2.01 of bash

$ set -- The quick brown fox jumps over the lazy dog

$ printf '%s\n'     "${!#}     ${@:(-1)} ${@: -1} ${@:~0} ${!#}"
dog     dog dog dog dog

For ksh, zsh and bash:

$ printf '%s\n' "${@: -1}    ${@:~0}"     # the space beetwen `:`
                                          # and `-1` is a must.
dog   dog

And for "next to last":

$ printf '%s\n' "${@:~1:1}"
lazy

Using printf to workaround any issues with arguments that start with a dash (like -n).

For all shells and for older sh (works with spaces and glob characters) is:

$ set -- The quick brown fox jumps over the lazy dog "the * last argument"

$ eval printf "'%s\n'" "\"\${$#}\""
The last * argument

Or, if you want to set a last var:

$ eval last=\${$#}; printf '%s\n' "$last"
The last * argument

And for "next to last":

$ eval printf "'%s\n'" "\"\${$(($#-1))}\""
dog

Create the perfect JPA entity

I'll try to answer several key points: this is from long Hibernate/ persistence experience including several major applications.

Entity Class: implement Serializable?

Keys needs to implement Serializable. Stuff that's going to go in the HttpSession, or be sent over the wire by RPC/Java EE, needs to implement Serializable. Other stuff: not so much. Spend your time on what's important.

Constructors: create a constructor with all required fields of the entity?

Constructor(s) for application logic, should have only a few critical "foreign key" or "type/kind" fields which will always be known when creating the entity. The rest should be set by calling the setter methods -- that's what they're for.

Avoid putting too many fields into constructors. Constructors should be convenient, and give basic sanity to the object. Name, Type and/or Parents are all typically useful.

OTOH if application rules (today) require a Customer to have an Address, leave that to a setter. That is an example of a "weak rule". Maybe next week, you want to create a Customer object before going to the Enter Details screen? Don't trip yourself up, leave possibility for unknown, incomplete or "partially entered" data.

Constructors: also, package private default constructor?

Yes, but use 'protected' rather than package private. Subclassing stuff is a real pain when the necessary internals are not visible.

Fields/Properties

Use 'property' field access for Hibernate, and from outside the instance. Within the instance, use the fields directly. Reason: allows standard reflection, the simplest & most basic method for Hibernate, to work.

As for fields 'immutable' to the application -- Hibernate still needs to be able to load these. You could try making these methods 'private', and/or put an annotation on them, to prevent application code making unwanted access.

Note: when writing an equals() function, use getters for values on the 'other' instance! Otherwise, you'll hit uninitialized/ empty fields on proxy instances.

Protected is better for (Hibernate) performance?

Unlikely.

Equals/HashCode?

This is relevant to working with entities, before they've been saved -- which is a thorny issue. Hashing/comparing on immutable values? In most business applications, there aren't any.

A customer can change address, change the name of their business, etc etc -- not common, but it happens. Corrections also need to be possible to make, when the data was not entered correctly.

The few things that are normally kept immutable, are Parenting and perhaps Type/Kind -- normally the user recreates the record, rather than changing these. But these do not uniquely identify the entity!

So, long and short, the claimed "immutable" data isn't really. Primary Key/ ID fields are generated for the precise purpose, of providing such guaranteed stability & immutability.

You need to plan & consider your need for comparison & hashing & request-processing work phases when A) working with "changed/ bound data" from the UI if you compare/hash on "infrequently changed fields", or B) working with "unsaved data", if you compare/hash on ID.

Equals/HashCode -- if a unique Business Key is not available, use a non-transient UUID which is created when the entity is initialized

Yes, this is a good strategy when required. Be aware that UUIDs are not free, performance-wise though -- and clustering complicates things.

Equals/HashCode -- never refer to related entities

"If related entity (like a parent entity) needs to be part of the Business Key then add a non insertable, non updatable field to store the parent id (with the same name as the ManytoOne JoinColumn) and use this id in the equality check"

Sounds like good advice.

Hope this helps!

Git merge is not possible because I have unmerged files

I repeatedly had the same challenge sometime ago. This problem occurs mostly when you are trying to pull from the remote repository and you have some files on your local instance conflicting with the remote version, if you are using git from an IDE such as IntelliJ, you will be prompted and allowed to make a choice if you want to retain your own changes or you prefer the changes in the remote version to overwrite yours'. If you don't make any choice then you fall into this conflict. all you need to do is run:

git merge --abort # The unresolved conflict will be cleared off

And you can continue what you were doing before the break.

how can I display tooltip or item information on mouse over?

Use the title attribute while alt is important for SEO stuff.

How to unescape HTML character entities in Java?

In my case i use the replace method by testing every entity in every variable, my code looks like this:

text = text.replace("&Ccedil;", "Ç");
text = text.replace("&ccedil;", "ç");
text = text.replace("&Aacute;", "Á");
text = text.replace("&Acirc;", "Â");
text = text.replace("&Atilde;", "Ã");
text = text.replace("&Eacute;", "É");
text = text.replace("&Ecirc;", "Ê");
text = text.replace("&Iacute;", "Í");
text = text.replace("&Ocirc;", "Ô");
text = text.replace("&Otilde;", "Õ");
text = text.replace("&Oacute;", "Ó");
text = text.replace("&Uacute;", "Ú");
text = text.replace("&aacute;", "á");
text = text.replace("&acirc;", "â");
text = text.replace("&atilde;", "ã");
text = text.replace("&eacute;", "é");
text = text.replace("&ecirc;", "ê");
text = text.replace("&iacute;", "í");
text = text.replace("&ocirc;", "ô");
text = text.replace("&otilde;", "õ");
text = text.replace("&oacute;", "ó");
text = text.replace("&uacute;", "ú");

In my case this worked very well.

What exceptions should be thrown for invalid or unexpected parameters in .NET?

Short answer:
Neither

Longer answer:
using Argument*Exception (except in a library that is a product on its on, such as component library) is a smell. Exceptions are to handle exceptional situation, not bugs, and not user's (i.e. API consumer) shortfalls.

Longest answer:
Throwing exceptions for invalid arguments is rude, unless you write a library.
I prefer using assertions, for two (or more) reasons:

  • Assertions don't need to be tested, while throw assertions do, and test against ArgumentNullException looks ridiculous (try it).
  • Assertions better communicate the intended use of the unit, and is closer to being executable documentation than a class behavior specification.
  • You can change behavior of assertion violation. For example in debug compilation a message box is fine, so that your QA will hit you with it right away (you also get your IDE breaking on the line where it happens), while in unit test you can indicate assertion failure as a test failure.

Here is what handling of null exception looks like (being sarcastic, obviously):

try {
    library.Method(null);
}
catch (ArgumentNullException e) {
    // retry with real argument this time
    library.Method(realArgument);
}

Exceptions shall be used when situation is expected but exceptional (things happen that are outside of consumer's control, such as IO failure). Argument*Exception is an indication of a bug and shall be (my opinion) handled with tests and assisted with Debug.Assert

BTW: In this particular case, you could have used Month type, instead of int. C# falls short when it comes to type safety (Aspect# rulez!) but sometimes you can prevent (or catch at compile time) those bugs all together.

And yes, MicroSoft is wrong about that.

How do I decrease the size of my sql server log file?

Welcome to the fickle world of SQL Server log management.

SOMETHING is wrong, though I don't think anyone will be able to tell you more than that without some additional information. For example, has this database ever been used for Transactional SQL Server replication? This can cause issues like this if a transaction hasn't been replicated to a subscriber.

In the interim, this should at least allow you to kill the log file:

  1. Perform a full backup of your database. Don't skip this. Really.
  2. Change the backup method of your database to "Simple"
  3. Open a query window and enter "checkpoint" and execute
  4. Perform another backup of the database
  5. Change the backup method of your database back to "Full" (or whatever it was, if it wasn't already Simple)
  6. Perform a final full backup of the database.

You should now be able to shrink the files (if performing the backup didn't do that for you).

Good luck!

jQuery Validate Required Select

how to validate the select "qualifica" it has 3 choose

$(document).ready(function(){

    $('.validateForm').validate({
        rules: {
            fullname: 'required',
            ragionesociale: 'required',
            partitaiva: 'required',
            recapitotelefonico: 'required',
            qualifica: 'required',
            email: {
                required: true,
                email: true
            },
        },
        submitHandler: function(form) {

            var fullname = $('#fullname').val(),
                            ragionesociale = $('#ragionesociale').val(),
                            partitaiva = $('#partitaiva').val(),
                            email = $('#email').val(),
                            recapitotelefonico = $('#recapitotelefonico').val(),
                            qualifica = $('#qualifica').val(),
                            dataString = 'fullname=' + fullname + '&ragionesociale=' + ragionesociale + '&partitaiva=' + partitaiva + '&email=' + email + '&recapitotelefonico=' + recapitotelefonico + '&qualifica=' + qualifica;

            $.ajax({
                type: "POST",
                url: "util/sender.php",
                data: dataString,
                success: function() {

                    window.location.replace("./thank-you-page.php");


                }
            });
            return false;
        }
    });

});

Viewing contents of a .jar file

java -xf some-j.jar will unzip a JAR file.

BAT file to open CMD in current directory

I'm thinking that if you are creating a batch script that relies on the Current Directory being set to the folder that contains the batch file, that you are setting yourself up for trouble when you try to execute the batch file using a fully qualified path as you would from a scheduler.

Better to add this line to your batch file too:

REM Change Current Directory to the location of this batch file 
CD /D %~dp0

unless you are fully qualifying all of your paths.

How do I keep the screen on in my App?

There are multiple ways you can do it:

Solution 1:

class MainActivity extends AppCompactActivity {
    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);    
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
}

Solution 2:

In activity_main.xml file, simply add:

<android:KeepScreenOn="true"/>

My advice: please don't use WakeLock. If you use it, you have to define extra permission, and mostly this thing is useful in CPU's development environment.

Also, make sure to turn off the screen while closing the activity. You can do it in this way:

public void onDestry() {
    getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

Pandas dataframe groupby plot

Simple plot,

you can use:

df.plot(x='Date',y='adj_close')

Or you can set the index to be Date beforehand, then it's easy to plot the column you want:

df.set_index('Date', inplace=True)
df['adj_close'].plot()

If you want a chart with one series by ticker on it

You need to groupby before:

df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)

enter image description here


If you want a chart with individual subplots:

grouped = df.groupby('ticker')

ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))

fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)

for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
    grouped.get_group(key).plot(ax=ax)

ax.legend()
plt.show()

enter image description here

MVC4 Passing model from view to controller

I hope this complete example will help you.

This is the TaxiInfo class which holds information about a taxi ride:

namespace Taxi.Models
{
    public class TaxiInfo
    {
        public String Driver { get; set; }
        public Double Fare { get; set; }
        public Double Distance { get; set; }
        public String StartLocation { get; set; }
        public String EndLocation { get; set; }
    }
}

We also have a convenience model which holds a List of TaxiInfo(s):

namespace Taxi.Models
{
    public class TaxiInfoSet
    {
        public List<TaxiInfo> TaxiInfoList { get; set; }

        public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
        {
            TaxiInfoList = new List<TaxiInfo>();

            foreach(var TaxiInfo in TaxiInfos)
            {
                TaxiInfoList.Add(TaxiInfo);
            }
        }
    }
}

Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:

public ActionResult Index()
{
    var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
    var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };

    return View(new TaxiInfoSet(taxi1,taxi2));
}

The code for the view is as follows:

@model Taxi.Models.TaxiInfoSet
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@foreach(var TaxiInfo in Model.TaxiInfoList){
    <form>
        <h1>Cost: [email protected]</h1>
        <h2>Distance: @(TaxiInfo.Distance) km</h2>
        <p>
            Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
        </p>
        @Html.ActionLink("Home","Booking",TaxiInfo)
    </form>
}

The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:

    public ActionResult Booking(TaxiInfo Taxi)
    {
        return View(Taxi);
    }

This returns a the following view:

@model Taxi.Models.TaxiInfo

@{
    ViewBag.Title = "Booking";
}

<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>

A visual tour:

The Index view

The Booking view

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

To add to Lauritz's answer, I created a decorator/wrapper for exception handling and the wrapper logs which type of exception occurred.

class general_function_handler(object):
    def __init__(self, func):
        self.func = func
    def __get__(self, obj, type=None):
        return self.__class__(self.func.__get__(obj, type))
    def __call__(self, *args, **kwargs):
        try:
            retval = self.func(*args, **kwargs)
        except Exception, e :
            logging.warning('Exception in %s' % self.func)
            template = "An exception of type {0} occured. Arguments:\n{1!r}"
            message = template.format(type(e).__name__, e.args)
            logging.exception(message)
            sys.exit(1) # exit on all exceptions for now
        return retval

This can be called on a class method or a standalone function with the decorator:

@general_function_handler

See my blog about for the full example: http://ryaneirwin.wordpress.com/2014/05/31/python-decorators-and-exception-handling/

Execute Insert command and return inserted Id in Sql

SQL Server stored procedure:

CREATE PROCEDURE [dbo].[INS_MEM_BASIC]
    @na varchar(50),
    @occ varchar(50),
    @New_MEM_BASIC_ID int OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO Mem_Basic
    VALUES (@na, @occ)

    SELECT @New_MEM_BASIC_ID = SCOPE_IDENTITY()
END

C# code:

public int CreateNewMember(string Mem_NA, string Mem_Occ )
{
    // values 0 --> -99 are SQL reserved.
    int new_MEM_BASIC_ID = -1971;   
    SqlConnection SQLconn = new SqlConnection(Config.ConnectionString);
    SqlCommand cmd = new SqlCommand("INS_MEM_BASIC", SQLconn);

    cmd.CommandType = CommandType.StoredProcedure;

    SqlParameter outPutVal = new SqlParameter("@New_MEM_BASIC_ID", SqlDbType.Int);

    outPutVal.Direction = ParameterDirection.Output;
    cmd.Parameters.Add(outPutVal);
    cmd.Parameters.Add("@na", SqlDbType.Int).Value = Mem_NA;
    cmd.Parameters.Add("@occ", SqlDbType.Int).Value = Mem_Occ;

    SQLconn.Open();
    cmd.ExecuteNonQuery();
    SQLconn.Close();

    if (outPutVal.Value != DBNull.Value) new_MEM_BASIC_ID = Convert.ToInt32(outPutVal.Value);
        return new_MEM_BASIC_ID;
}

I hope these will help to you ....

You can also use this if you want ...

public int CreateNewMember(string Mem_NA, string Mem_Occ )
{
    using (SqlConnection con=new SqlConnection(Config.ConnectionString))
    {
        int newID;
        var cmd = "INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ);SELECT CAST(scope_identity() AS int)";

        using(SqlCommand cmd=new SqlCommand(cmd, con))
        {
            cmd.Parameters.AddWithValue("@na", Mem_NA);
            cmd.Parameters.AddWithValue("@occ", Mem_Occ);

            con.Open();
            newID = (int)insertCommand.ExecuteScalar();

            if (con.State == System.Data.ConnectionState.Open) con.Close();
                return newID;
        }
    }
}

How to save an image to localStorage and display it on the next page?

If your images keep getting cropped, here's some code to get the dimensions of the image file before saving to localstorage.

First, I would create some hidden input boxes to hold the width and height values

<input id="file-h" hidden type="text"/>
<input id="file-w" hidden type="text"/>

Then get the dimensions of your file into the input boxes

var _URL = window.URL || window.webkitURL;
$("#file-input").change(function(e) {
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function() {
            $("#file-h").val(this.height);
            $("#file-w").val(this.width);
        };
        img.onerror = function() {
            alert( "not a valid file: " + file.type);
        };
        img.src = _URL.createObjectURL(file);
    }
});

Lastly, change the width and height objects used in the getBase64Image() function by pointing to your input box values

FROM

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

TO

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = $("#file-w").val();
    canvas.height = $("#file-h").val();

Also, you are going to have to maintain a size of about 300kb for all files. There are posts on stackoverflow that cover file size validation using Javascript.

What are the different NameID format used for?

Refer to Section 8.3 of this SAML core pdf of oasis SAML specification.

SP and IdP usually communicate each other about a subject. That subject should be identified through a NAME-IDentifier , which should be in some format so that It is easy for the other party to identify it based on the Format.

All these

1.urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified [default]

2.urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress

3.urn:oasis:names:tc:SAML:2.0:nameid-format:persistent

4.urn:oasis:names:tc:SAML:2.0:nameid-format:transient

are format for the Name Identifiers.

The name format for a transient ID in SAML 1 is urn:mace:shibboleth:1.0:nameIdentifier and in SAML 2 is urn:oasis:names:tc:SAML:2.0:nameid-format:transient

Transient is for [section 8.3.8 of SAML Core]

Indicates that the content of the element is an identifier with transient semantics and SHOULD be treated as an opaque and temporary value by the relying party.

Unspecified can be used and it purely depends on the entities implementation on their own wish.

How to use Utilities.sleep() function

Serge is right - my workaround:

function mySleep (sec)
{
  SpreadsheetApp.flush();
  Utilities.sleep(sec*1000);
  SpreadsheetApp.flush();
}

OS X Terminal UTF-8 issues

My terminal was just acting silly, not printing out åäö. I found (and set) this setting: enter image description here

Under Terminal -> Preferences... -> Profiles -> Advanced.

Seems to have fixed my problem.

How to prevent Browser cache for php site

Prevent browser cache is not a good idea depending on the case. Looking for a solution I found solutions like this:

<link rel="stylesheet" type="text/css" href="meu.css?v=<?=filemtime($file);?>">

the problem here is that if the file is overwritten during an update on the server, which is my scenario, the cache is ignored because timestamp is modified even the content of the file is the same.

I use this solution to force browser to download assets only if its content is modified:

<link rel="stylesheet" type="text/css" href="meu.css?v=<?=hash_file('md5', $file);?>">

How do I create a new class in IntelliJ without using the mouse?

For Mac Os, command + 1 , then press control + return

Convert object of any type to JObject with Json.NET

If you have an object and wish to become JObject you can use:

JObject o = (JObject)JToken.FromObject(miObjetoEspecial);

like this :

Pocion pocionDeVida = new Pocion{
tipo = "vida",
duracion = 32,
};

JObject o = (JObject)JToken.FromObject(pocionDeVida);
Console.WriteLine(o.ToString());
// {"tipo": "vida", "duracion": 32,}

What's the yield keyword in JavaScript?

Before you learn about yield you need to know about generators. Generators are created using the function* syntax. Generator functions do not execute code but instead returns a type of iterator called a generator. When a value is given using the next method, the generator function keeps executing until it comes across a yield keyword. Using yield gives you back an object containing two values, one is value and the other is done (boolean). The value can be an array, object etc.

set initial viewcontroller in appdelegate - swift

Swift 3, Swift 4:

Change first line to

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool

the rest is same.

Swift 5+:

Instantiate root view controller from storyboard:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // this line is important
        self.window = UIWindow(frame: UIScreen.main.bounds)

        // In project directory storyboard looks like Main.storyboard,
        // you should use only part before ".storyboard" as its name,
        // so in this example name is "Main".
        let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
        
        // controller identifier sets up in storyboard utilities
        // panel (on the right), it is called 'Storyboard ID'
        let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as! YourViewController

        self.window?.rootViewController = viewController
        self.window?.makeKeyAndVisible()        
        return true
    }

If you want to use UINavigationController as root:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // this line is important
        self.window = UIWindow(frame: UIScreen.main.bounds)

        let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as! YourViewController
        let navigationController = UINavigationController.init(rootViewController: viewController)
        self.window?.rootViewController = navigationController

        self.window?.makeKeyAndVisible()        
        return true
    }

Instantiate root view controller from xib:

It is almost the same, but instead of lines

let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as! YourViewController

you'll have to write

let viewController = YourViewController(nibName: "YourViewController", bundle: nil)

How can I make robocopy silent in the command line except for progress?

The > null does not work in the quotes. It sees the > null as the batch filename.

The robocopy no output worked!!!

Here is the new batch file:

robocopy /mir /B /r:1 /nfl /ndl /njh /njs /nc /ns /np c:\EnvBackup c:\offsite_backup\EnvBackup

robocopy /mir /B /r:1 /nfl /ndl /njh /njs /nc /ns /np c:\shares c:\offsite_backup\shares

robocopy /mir /B /r:1 /nfl /ndl /njh /njs /nc /ns /np c:\Quickbooks_Backup c:\offsite_backup\Quickbooks_Backup

Is there an opposite to display:none?

display: none doesn’t have a literal opposite like visibility:hidden does.

The visibility property decides whether an element is visible or not. It therefore has two states (visible and hidden), which are opposite to each other.

The display property, however, decides what layout rules an element will follow. There are several different kinds of rules for how elements will lay themselves out in CSS, so there are several different values (block, inline, inline-block etc — see the documentation for these values here ).

display:none removes an element from the page layout entirely, as if it wasn’t there.

All other values for display cause the element to be a part of the page, so in a sense they’re all opposite to display:none.

But there isn’t one value that’s the direct converse of display:none - just like there's no one hair style that's the opposite of "bald".

Only read selected columns

You do it like this:

df = read.table("file.txt", nrows=1, header=TRUE, sep="\t", stringsAsFactors=FALSE)
colClasses = as.list(apply(df, 2, class))
needCols = c("Year", "Jan", "Feb", "Mar", "Apr", "May", "Jun")
colClasses[!names(colClasses) %in% needCols] = list(NULL)
df = read.table("file.txt", header=TRUE, colClasses=colClasses, sep="\t", stringsAsFactors=FALSE)

Git pull till a particular commit

This works for me:

git pull origin <sha>

e.g.

[dbn src]$ git fetch
[dbn src]$ git status
On branch current_feature
Your branch and 'origin/master' have diverged,
and have 2 and 7 different commits each, respectively.
...
[dbn src]$ git log -3 --pretty=oneline origin/master
f4d10ad2a5eda447bea53fed0b421106dbecea66 CASE-ID1: some descriptive msg
28eb00a42e682e32bdc92e5753a4a9c315f62b42 CASE-ID2: I'm so good at writing commit titles
ff39e46b18a66b21bc1eed81a0974e5c7de6a3e5 CASE-ID2: woooooo
[dbn src]$ git pull origin 28eb00a42e682e32bdc92e5753a4a9c315f62b42
[dbn src]$ git status
On branch current_feature
Your branch and 'origin/master' have diverged,
and have 2 and 1 different commits each, respectively.
...

This pulls 28eb00, ff39e4, and everything before, but doesn't pull f4d10ad. It allows the use of pull --rebase, and honors pull settings in your gitconfig. This works because you're basically treating 28eb00 as a branch.

For the version of git that I'm using, this method requires a full commit hash - no abbreviations or aliases are allowed. You could do something like:

[dbn src]$ git pull origin `git rev-parse origin/master^`

dlib installation on Windows 10

You need to install Cmake.

dlib is an c++ libary with python bindings. It needs to be builded first. My guess is this will happen automatically once you have installed Cmake

Escaping double quotes in JavaScript onClick event handler

While I agree with CMS about doing this in an unobtrusive manner (via a lib like jquery or dojo), here's what also work:

<script type="text/javascript">
function parse(a, b, c) {
    alert(c);
  }

</script>

<a href="#x" onclick="parse('#', false, 'xyc&quot;foo');return false;">Test</a>

The reason it barfs is not because of JavaScript, it's because of the HTML parser. It has no concept of escaped quotes to it trundles along looking for the end quote and finds it and returns that as the onclick function. This is invalid javascript though so you don't find about the error until JavaScript tries to execute the function..

Can media queries resize based on a div element instead of the screen?

I've just created a javascript shim to achieve this goal. Take a look if you want, it's a proof-of-concept, but take care: it's a early version and still needs some work.

https://github.com/marcj/css-element-queries

Using Google Text-To-Speech in Javascript

Here is the code snippet I found:

var audio = new Audio();
audio.src ='http://translate.google.com/translate_tts?ie=utf-8&tl=en&q=Hello%20World.';
audio.play();

.substring error: "is not a function"

You can use substr

for example:

new Date().getFullYear().toString().substr(-2)

Inserting values into a SQL Server database using ado.net via C#

you should remove last comma and as nrodic said your command is not correct.

you should change it like this :

SqlCommand cmd = new SqlCommand("INSERT INTO dbo.regist (" + " FirstName, Lastname, Username, Password, Age, Gender,Contact " + ") VALUES (" + " textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, comboBox1.Text,comboBox2.Text,textBox7.Text" + ")", cn);

How do you check if a variable is an array in JavaScript?

The universal solution is below:

Object.prototype.toString.call(obj)=='[object Array]'

Starting from ECMAScript 5, a formal solution is :

Array.isArray(arr)

Also, for old JavaScript libs, you can find below solution although it's not accurate enough:

var is_array = function (value) {
    return value &&
    typeof value === 'object' &&
    typeof value.length === 'number' &&
    typeof value.splice === 'function' &&
    !(value.propertyIsEnumerable('length'));
};

The solutions are from http://www.pixelstech.net/topic/85-How-to-check-whether-an-object-is-an-array-or-not-in-JavaScript

Output PowerShell variables to a text file

You can concatenate an array of values together using PowerShell's `-join' operator. Here is an example:

$FilePath = '{0}\temp\scripts\pshell\dump.txt' -f $env:SystemDrive;

$Computer = 'pc1';
$Speed = 9001;
$RegCheck = $true;

$Computer,$Speed,$RegCheck -join ',' | Out-File -FilePath $FilePath -Append -Width 200;

Output

pc1,9001,True

How to remove the Flutter debug banner?

Here are 3 ways to do it

  • 1 : On your MaterialApp set debugShowCheckedModeBanner to false.

     MaterialApp(
       debugShowCheckedModeBanner: false
     )
    

    The slow banner will also automatically be removed on release build.

  • 2 : If you are using Android Studio, you can find the option in the Flutter Inspector tab --> More Actions. enter image description here

  • 3 : There is also another way for removing the "debug" banner from the flutter app. Now after new release there is no "debugShowCheckedModeBanner: false," code line in main. dart file. So I think these methods are effective:

    --> If you are using VS Code, then install "Dart DevTools" from extensions. After installation, you can easily find "Dart DevTools" text icon at the bottom of VS Code. When you click on that text icon, a link will be open in google chrome. From that link page, you can easily remove the banner by just tapping on the banner icon as shown.

enter image description here

For more info: How_to_remove_debug_banner_in_flutter_on_android_emulator

jQuery preventDefault() not triggered

Try this one:

   $("div.subtab_left li.notebook a").click(function(e) {
    e.preventDefault();
    return false;   
    });