Programs & Examples On #Referential integrity

What's wrong with foreign keys?

Verifying foreign key constraints takes some CPU time, so some folks omit foreign keys to get some extra performance.

Create unique constraint with null columns

I think there is a semantic problem here. In my view, a user can have a (but only one) favourite recipe to prepare a specific menu. (The OP has menu and recipe mixed up; if I am wrong: please interchange MenuId and RecipeId below) That implies that {user,menu} should be a unique key in this table. And it should point to exactly one recipe. If the user has no favourite recipe for this specific menu no row should exist for this {user,menu} key pair. Also: the surrogate key (FaVouRiteId) is superfluous: composite primary keys are perfectly valid for relational-mapping tables.

That would lead to the reduced table definition:

CREATE TABLE Favorites
( UserId uuid NOT NULL REFERENCES users(id)
, MenuId uuid NOT NULL REFERENCES menus(id)
, RecipeId uuid NOT NULL REFERENCES recipes(id)
, PRIMARY KEY (UserId, MenuId)
);

Jquery insert new row into table at a certain index

Try this:

var i = 3;

$('#my_table > tbody > tr:eq(' + i + ')').after(html);

or this:

var i = 3;

$('#my_table > tbody > tr').eq( i ).after(html);

or this:

var i = 4;

$('#my_table > tbody > tr:nth-child(' + i + ')').after(html);

All of these will place the row in the same position. nth-child uses a 1 based index.

How to convert String object to Boolean Object?

We created soyuz-to library to simplify this problem (convert X to Y). It's just a set of SO answers for similar questions. This might be strange to use the library for such a simple problem, but it really helps in a lot of similar cases.

import io.thedocs.soyuz.to;

Boolean aBoolean = to.Boolean("true");

Please check it - it's very simple and has a lot of other useful features

Converting integer to string in Python

To manage non-integer inputs:

number = raw_input()
try:
    value = int(number)
except ValueError:
    value = 0

How to write a function that takes a positive integer N and returns a list of the first N natural numbers

Here are a few ways to create a list with N of continuous natural numbers starting from 1.

1 range:

def numbers(n): 
    return range(1, n+1);

2 List Comprehensions:

def numbers(n):
    return [i for i in range(1, n+1)]

You may want to look into the method xrange and the concepts of generators, those are fun in python. Good luck with your Learning!

removing html element styles via javascript

The class attribute can contain multiple styles, so you could specify it as

<tr class="row-even highlight">

and do string manipulation to remove 'highlight' from element.className

element.className=element.className.replace('hightlight','');

Using jQuery would make this simpler as you have the methods

$("#id").addClass("highlight");
$("#id").removeClass("hightlight");

that would enable you to toggle highlighting easily

How to add new column to an dataframe (to the front not end)?

The previous answers show 3 approaches

  1. By creating a new data frame
  2. By using "cbind"
  3. By adding column "a", and sort data frame by columns using column names or indexes

Let me show #4 approach "By using "cbind" and "rename" that works for my case

1. Create data frame

df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))

2. Get values for "new" column

new_column = c(0, 0, 0)

3. Combine "new" column with existed

df <- cbind(new_column, df)

4. Rename "new" column name

colnames(df)[1] <- "a"

How to change date format from DD/MM/YYYY or MM/DD/YYYY to YYYY-MM-DD?

The following will do.

string datestring = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);

Python Dictionary contains List as Value - How to update?

Probably something like this:

original_list = dictionary.get('C1')
new_list = []
for item in original_list:
  new_list.append(item+10)
dictionary['C1'] = new_list

How can I compile and run c# program without using visual studio?

There are different ways for this:

1.Building C# Applications Using csc.exe

While it is true that you might never decide to build a large-scale application using nothing but the C# command-line compiler, it is important to understand the basics of how to compile your code files by hand.

2.Building .NET Applications Using Notepad++

Another simple text editor I’d like to quickly point out is the freely downloadable Notepad++ application. This tool can be obtained from http://notepad-plus.sourceforge.net. Unlike the primitive Windows Notepad application, Notepad++ allows you to author code in a variety of languages and supports

3.Building .NET Applications Using SharpDevelop

As you might agree, authoring C# code with Notepad++ is a step in the right direction, compared to Notepad. However, these tools do not provide rich IntelliSense capabilities for C# code, designers for building graphical user interfaces, project templates, or database manipulation utilities. To address such needs, allow me to introduce the next .NET development option: SharpDevelop (also known as "#Develop").You can download it from http://www.sharpdevelop.com.

Simple WPF RadioButton Binding?

Actually, using the converter like that breaks two-way binding, plus as I said above, you can't use that with enumerations either. The better way to do this is with a simple style against a ListBox, like this:

Note: Contrary to what DrWPF.com stated in their example, do not put the ContentPresenter inside the RadioButton or else if you add an item with content such as a button or something else, you will not be able to set focus or interact with it. This technique solves that. Also, you need to handle the graying of the text as well as removing of margins on labels or else it will not render correctly. This style handles both for you as well.

<Style x:Key="RadioButtonListItem" TargetType="{x:Type ListBoxItem}" >

    <Setter Property="Template">
        <Setter.Value>

            <ControlTemplate TargetType="ListBoxItem">

                <DockPanel LastChildFill="True" Background="{TemplateBinding Background}" HorizontalAlignment="Stretch" VerticalAlignment="Center" >

                    <RadioButton IsChecked="{TemplateBinding IsSelected}" Focusable="False" IsHitTestVisible="False" VerticalAlignment="Center" Margin="0,0,4,0" />

                    <ContentPresenter
                        Content             = "{TemplateBinding ContentControl.Content}"
                        ContentTemplate     = "{TemplateBinding ContentControl.ContentTemplate}"
                        ContentStringFormat = "{TemplateBinding ContentControl.ContentStringFormat}"
                        HorizontalAlignment = "{TemplateBinding Control.HorizontalContentAlignment}"
                        VerticalAlignment   = "{TemplateBinding Control.VerticalContentAlignment}"
                        SnapsToDevicePixels = "{TemplateBinding UIElement.SnapsToDevicePixels}" />

                </DockPanel>

            </ControlTemplate>

        </Setter.Value>

    </Setter>

</Style>

<Style x:Key="RadioButtonList" TargetType="ListBox">

    <Style.Resources>
        <Style TargetType="Label">
            <Setter Property="Padding" Value="0" />
        </Style>
    </Style.Resources>

    <Setter Property="BorderThickness" Value="0" />
    <Setter Property="Background"      Value="Transparent" />

    <Setter Property="ItemContainerStyle" Value="{StaticResource RadioButtonListItem}" />

    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBox}">
                <ItemsPresenter SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>

    <Style.Triggers>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="TextBlock.Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
        </Trigger>
    </Style.Triggers>

</Style>

<Style x:Key="HorizontalRadioButtonList" BasedOn="{StaticResource RadioButtonList}" TargetType="ListBox">
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel Background="Transparent" Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
</Style>

You now have the look and feel of radio buttons, but you can do two-way binding, and you can use an enumeration. Here's how...

<ListBox Style="{StaticResource RadioButtonList}"
    SelectedValue="{Binding SomeVal}"
    SelectedValuePath="Tag">

    <ListBoxItem Tag="{x:Static l:MyEnum.SomeOption}"     >Some option</ListBoxItem>
    <ListBoxItem Tag="{x:Static l:MyEnum.SomeOtherOption}">Some other option</ListBoxItem>
    <ListBoxItem Tag="{x:Static l:MyEnum.YetAnother}"     >Yet another option</ListBoxItem>

</ListBox>

Also, since we explicitly separated out the style that tragets the ListBoxItem rather than putting it inline, again as the other examples have shown, you can now create a new style off of it to customize things on a per-item basis such as spacing. (This will not work if you simply try to target ListBoxItem as the keyed style overrides generic control targets.)

Here's an example of putting a margin of 6 above and below each item. (Note how you have to explicitly apply the style via the ItemContainerStyle property and not simply targeting ListBoxItem in the ListBox's resource section for the reason stated above.)

<Window.Resources>
    <Style x:Key="SpacedRadioButtonListItem" TargetType="ListBoxItem" BasedOn="{StaticResource RadioButtonListItem}">
        <Setter Property="Margin" Value="0,6" />
    </Style>
</Window.Resources>

<ListBox Style="{StaticResource RadioButtonList}"
    ItemContainerStyle="{StaticResource SpacedRadioButtonListItem}"
    SelectedValue="{Binding SomeVal}"
    SelectedValuePath="Tag">

    <ListBoxItem Tag="{x:Static l:MyEnum.SomeOption}"     >Some option</ListBoxItem>
    <ListBoxItem Tag="{x:Static l:MyEnum.SomeOtherOption}">Some other option</ListBoxItem>
    <ListBoxItem Tag="{x:Static l:MyEnum.YetAnother}"     >Ter another option</ListBoxItem>

</ListBox>

How to view the committed files you have not pushed yet?

The previous answers are all good, but they all show origin/master. These days, following the best practices, I rarely work directly on a master branch, let alone from origin repo.

So if you are like me who work in a branch, here are tips:

  1. Say you are already on a branch. If not, git checkout that branch
  2. git log # to show a list of commit such as x08d46ffb1369e603c46ae96, You need only the latest commit which comes first.
  3. git show --name-only x08d46ffb1369e603c46ae96 # to show the files commited
  4. git show x08d46ffb1369e603c46ae96 # show the detail diff of each changed file

Or more simply, just use HEAD:

  1. git show --name-only HEAD # to show a list of files committed
  2. git show HEAD # to show the detail diff.

How can I create a blank/hardcoded column in a sql query?

Thank you, in PostgreSQL this works for boolean

SELECT
hat,
shoe,
boat,
false as placeholder
FROM
objects

How to set the context path of a web application in Tomcat 7.0

In Tomcat 8.X ,under tomcat home directory /conf/ folder in server.xml you can add <Context> tag under <Host> tag as shown below . But you have to restart the server in order to take effect

  <Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="true">

     <Context docBase="${catalina.base}\webapps\<Your App Directory Name>" path="<your app path you wish>" reloadable="true" />
  </Host>

OR if you are using Tomcat 7.X you can add context.xml file in WEB-INF folder in your project . The contents of the file i used is as shown . and it worked fine for me . you don't have to restart server in this case .

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

<Context docBase="${catalina.base}\webapps\<My App Directory Name>" path="<your app path you wish>" reloadable="true" />

How do I add a newline to a windows-forms TextBox?

Have you tried something like:

textbox.text = "text" & system.environment.newline & "some more text"

how to add value to a tuple?

    list_of_tuples = [('1', '2', '3', '4'),
                      ('2', '3', '4', '5'),
                      ('3', '4', '5', '6'),
                      ('4', '5', '6', '7')]


    def mod_tuples(list_of_tuples):
        for i in range(0, len(list_of_tuples)):
            addition = ''
            for x in list_of_tuples[i]:
                addition = addition + x
            list_of_tuples[i] = list_of_tuples[i] + (addition,)
        return list_of_tuples

    # check: 
    print mod_tuples(list_of_tuples)

Why AVD Manager options are not showing in Android Studio

After updating Android Studio to the latest version I finally found the AVD Manager:

  1. (Update Android Studio)
  2. Create a new project
  3. Click on the device config dropdown: enter image description here

How can javascript upload a blob?

I tried all the solutions above and in addition, those in related answers as well. Solutions including but not limited to passing the blob manually to a HTMLInputElement's file property, calling all the readAs* methods on FileReader, using a File instance as second argument for a FormData.append call, trying to get the blob data as a string by getting the values at URL.createObjectURL(myBlob) which turned out nasty and crashed my machine.

Now, if you happen to attempt those or more and still find you're unable to upload your blob, it could mean the problem is server-side. In my case, my blob exceeded the http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize and post_max_size limit in PHP.INI so the file was leaving the front end form but getting rejected by the server. You could either increase this value directly in PHP.INI or via .htaccess

C++ vector of char array

You can directly define a char type vector as below.

vector<char> c = {'a', 'b', 'c'};
vector < vector<char> > t = {{'a','a'}, 'b','b'};

How to search in an array with preg_match?

$items = array();
foreach ($haystacks as $haystack) {
    if (preg_match($pattern, $haystack, $matches)
        $items[] = $matches[1];
}

How do I import/include MATLAB functions?

Solution for Windows

Go to File --> Set Path and add the folder containing the functions as Matlab files. (At least for Matlab 2007b on Vista)

How does numpy.histogram() work?

import numpy as np    
hist, bin_edges = np.histogram([1, 1, 2, 2, 2, 2, 3], bins = range(5))

Below, hist indicates that there are 0 items in bin #0, 2 in bin #1, 4 in bin #3, 1 in bin #4.

print(hist)
# array([0, 2, 4, 1])   

bin_edges indicates that bin #0 is the interval [0,1), bin #1 is [1,2), ..., bin #3 is [3,4).

print (bin_edges)
# array([0, 1, 2, 3, 4]))  

Play with the above code, change the input to np.histogram and see how it works.


But a picture is worth a thousand words:

import matplotlib.pyplot as plt
plt.bar(bin_edges[:-1], hist, width = 1)
plt.xlim(min(bin_edges), max(bin_edges))
plt.show()   

enter image description here

URL encode sees “&” (ampersand) as “&amp;” HTML entity

There is HTML and URI encodings. &amp; is & encoded in HTML while %26 is & in URI encoding.

So before URI encoding your string you might want to HTML decode and then URI encode it :)

var div = document.createElement('div');
div.innerHTML = '&amp;AndOtherHTMLEncodedStuff';
var htmlDecoded = div.firstChild.nodeValue;
var urlEncoded = encodeURIComponent(htmlDecoded);

result %26AndOtherHTMLEncodedStuff

Hope this saves you some time

failed to find target with hash string 'android-22'

Just click on the link written in the error:

Open Android SDK Manager

and it will show you the dialogs that will help you to install the required sdk for your project.

Row count on the Filtered data

Rowz = Application.WorksheetFunction.Subtotal(2, Range("A2:A" & Rows(Rows.Count).End(xlUp).Row))

Moving items around in an ArrayList

you can try this simple code, Collections.swap(list, i, j) is what you looking for.

    List<String> list = new ArrayList<String>();
    list.add("1");
    list.add("2");
    list.add("3");
    list.add("4");

    String toMoveUp = "3";
    while (list.indexOf(toMoveUp) != 0) {
        int i = list.indexOf(toMoveUp);
        Collections.swap(list, i, i - 1);
    }

    System.out.println(list);

Detecting a long press with Android

GestureDetector is the best solution.

Here is an interesting alternative. In onTouchEvent on every ACTION_DOWN schedule a Runnable to run in 1 second. On every ACTION_UP or ACTION_MOVE, cancel scheduled Runnable. If cancelation happens less than 1s from ACTION_DOWN event, Runnable won't run.

final Handler handler = new Handler(); 
Runnable mLongPressed = new Runnable() { 
    public void run() { 
        Log.i("", "Long press!");
    }   
};

@Override
public boolean onTouchEvent(MotionEvent event, MapView mapView){
    if(event.getAction() == MotionEvent.ACTION_DOWN)
        handler.postDelayed(mLongPressed, ViewConfiguration.getLongPressTimeout());
    if((event.getAction() == MotionEvent.ACTION_MOVE)||(event.getAction() == MotionEvent.ACTION_UP))
        handler.removeCallbacks(mLongPressed);
    return super.onTouchEvent(event, mapView);
}

How do I concatenate text in a query in sql server?

If you are using SQL Server 2005 or greater, depending on the size of the data in the Notes field, you may want to consider casting to nvarchar(max) instead of casting to a specific length which could result in string truncation.

Select Cast(notes as nvarchar(max)) + 'SomeText' From NotesTable a

Should I use px or rem value units in my CSS?

Half (but only half) snarky answer (the other half is bitter disdain of the reality of bureaucracy):

Use vh

Everything is always sized to browser window.

Always allow scroll down, but disable horizontal scroll.

Set body width to be a static 50vh, and never code css that floats or breaks out of the parent div. (If they try to mock up something that looks like it does, clever use of a background gif can throw them off track.) And style only using tables so everything is held rigidly into place as expected. Include a javascript function to undo any ctrl+/- activity the user may do.

Users will hate you, because the site doesn't flow differently based on what they're using (such as text being too small to read on phones). Your coworkers will hate you because nobody in their right mind does this and it will likely break their work (though not yours). Your programming professors will hate you because this is not a good idea. Your UX designer will hate you because it will reveal the corners they cut in designing UX mock-ups that they have to do in order to meet deadlines.

Nearly everyone will hate you, except the people who tell you to make things match the mock-up and to do so quickly. Those people, however (which generally include the project managers), will be ecstatic by your accuracy and fast turn around time. And everyone knows their opinion is the only one that matters to your paycheck.

Using AES encryption in C#

If you just want to use the built-in crypto provider RijndaelManaged, check out the following help article (it also has a simple code sample):

http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx

And just in case you need the sample in a hurry, here it is in all its plagiarized glory:

using System;
using System.IO;
using System.Security.Cryptography;

namespace RijndaelManaged_Example
{
    class RijndaelExample
    {
        public static void Main()
        {
            try
            {

                string original = "Here is some data to encrypt!";

                // Create a new instance of the RijndaelManaged 
                // class.  This generates a new key and initialization  
                // vector (IV). 
                using (RijndaelManaged myRijndael = new RijndaelManaged())
                {

                    myRijndael.GenerateKey();
                    myRijndael.GenerateIV();
                    // Encrypt the string to an array of bytes. 
                    byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);

                    // Decrypt the bytes to a string. 
                    string roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);

                    //Display the original data and the decrypted data.
                    Console.WriteLine("Original:   {0}", original);
                    Console.WriteLine("Round Trip: {0}", roundtrip);
                }

            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
            }
        }
        static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
        {
            // Check arguments. 
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");
            byte[] encrypted;
            // Create an RijndaelManaged object 
            // with the specified key and IV. 
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.Key = Key;
                rijAlg.IV = IV;

                // Create a decryptor to perform the stream transform.
                ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

                // Create the streams used for encryption. 
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {

                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }


            // Return the encrypted bytes from the memory stream. 
            return encrypted;

        }

        static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments. 
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");

            // Declare the string used to hold 
            // the decrypted text. 
            string plaintext = null;

            // Create an RijndaelManaged object 
            // with the specified key and IV. 
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.Key = Key;
                rijAlg.IV = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

                // Create the streams used for decryption. 
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {

                            // Read the decrypted bytes from the decrypting stream 
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }

            }

            return plaintext;

        }
    }
}

android download pdf from url then open it with a pdf reader

Hi the problem is in FileDownloader class

 urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);

You need to remove the above two lines and everything will work fine. Please mark the question as answered if it is working as expected.

Latest solution for the same problem is updated Android PDF Write / Read using Android 9 (API level 28)

Attaching the working code with screenshots.

enter image description here

enter image description here

MainActivity.java

package com.example.downloadread;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void download(View v)
    {
        new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf"); 
    }

    public void view(View v)
    {
        File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "maven.pdf");  // -> filename = maven.pdf
        Uri path = Uri.fromFile(pdfFile);
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(path, "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try{
            startActivity(pdfIntent);
        }catch(ActivityNotFoundException e){
            Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
        }
    }

    private class DownloadFile extends AsyncTask<String, Void, Void>{

        @Override
        protected Void doInBackground(String... strings) {
            String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
            String fileName = strings[1];  // -> maven.pdf
            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File folder = new File(extStorageDirectory, "testthreepdf");
            folder.mkdir();

            File pdfFile = new File(folder, fileName);

            try{
                pdfFile.createNewFile();
            }catch (IOException e){
                e.printStackTrace();
            }
            FileDownloader.downloadFile(fileUrl, pdfFile);
            return null;
        }
    }


}

FileDownloader.java

package com.example.downloadread;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class FileDownloader {
    private static final int  MEGABYTE = 1024 * 1024;

    public static void downloadFile(String fileUrl, File directory){
        try {

            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            //urlConnection.setRequestMethod("GET");
            //urlConnection.setDoOutput(true);
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            while((bufferLength = inputStream.read(buffer))>0 ){
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.downloadread"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.downloadread.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="15dp"
        android:text="download"
        android:onClick="download" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/button1"
        android:layout_marginTop="38dp"
        android:text="view"
        android:onClick="view" />

</RelativeLayout>

How to remove all subviews of a view in Swift?

The code can be written simpler as following.

view.subviews.forEach { $0.removeFromSuperview() }

Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0

try to use

<?php require_once($_SERVER['DOCUMENT_ROOT'].'/web/a.php'); ?>

Convert normal Java Array or ArrayList to Json Array in android

This is the correct syntax:

String arlist1 [] = { "value1`", "value2", "value3" };
JSONArray jsonArray1 = new JSONArray(arlist1);

Has anyone ever got a remote JMX JConsole to work?

You are probably experiencing an issue with a firewall. The 'problem' is that the port you specify is not the only port used, it uses 1 or maybe even 2 more ports for RMI, and those are probably blocked by a firewall.

One of the extra ports will not be know up front if you use the default RMI configuration, so you have to open up a big range of ports - which might not amuse the server administrator.

There is a solution that does not require opening up a lot of ports however, I've gotten it to work using the combined source snippets and tips from

http://forums.sun.com/thread.jspa?threadID=5267091 - link doesn't work anymore

http://blogs.oracle.com/jmxetc/entry/connecting_through_firewall_using_jmx

http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html

It's even possible to setup an ssh tunnel and still get it to work :-)

Ant is using wrong java version

If you are not using eclipse. Then you can change the ant java property directly on the file as mentioned here.

http://pissedoff-techie.blogspot.in/2014/09/ant-picks-up-incorrect-java-version.html

What's the best way to validate an XML file against an XSD file?

The Java runtime library supports validation. Last time I checked this was the Apache Xerces parser under the covers. You should probably use a javax.xml.validation.Validator.

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import java.net.URL;
import org.xml.sax.SAXException;
//import java.io.File; // if you use File
import java.io.IOException;
...
URL schemaFile = new URL("http://host:port/filename.xsd");
// webapp example xsd: 
// URL schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
// local file example:
// File schemaFile = new File("/location/to/localfile.xsd"); // etc.
Source xmlFile = new StreamSource(new File("web.xml"));
SchemaFactory schemaFactory = SchemaFactory
    .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
  Schema schema = schemaFactory.newSchema(schemaFile);
  Validator validator = schema.newValidator();
  validator.validate(xmlFile);
  System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
  System.out.println(xmlFile.getSystemId() + " is NOT valid reason:" + e);
} catch (IOException e) {}

The schema factory constant is the string http://www.w3.org/2001/XMLSchema which defines XSDs. The above code validates a WAR deployment descriptor against the URL http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd but you could just as easily validate against a local file.

You should not use the DOMParser to validate a document (unless your goal is to create a document object model anyway). This will start creating DOM objects as it parses the document - wasteful if you aren't going to use them.

force line break in html table cell

I think what you're trying to do is wrap loooooooooooooong words or URLs so they don't push the size of the table out. (I've just been trying to do the same thing!)

You can do this easily with a DIV by giving it the style word-wrap: break-word (and you may need to set its width, too).

div {
    word-wrap: break-word;         /* All browsers since IE 5.5+ */
    overflow-wrap: break-word;     /* Renamed property in CSS3 draft spec */
    width: 100%;
}

However, for tables, you must either wrap the content in a DIV (or other block tag) or apply: table-layout: fixed. This means the columns widths are no longer fluid, but are defined based on the widths of the columns in the first row only (or via specified widths). Read more here.

Sample code:

table {
    table-layout: fixed;
    width: 100%;
}

table td {
    word-wrap: break-word;         /* All browsers since IE 5.5+ */
    overflow-wrap: break-word;     /* Renamed property in CSS3 draft spec */
}

Hope that helps somebody.

VBScript to send email without running Outlook

Yes. Blat or any other self contained SMTP mailer. Blat is a fairly full featured SMTP client that runs from command line

Blat is here

jQuery onclick toggle class name

It can even be made dependent to another attribute changes. like this:

$('.classA').toggleClass('classB', $('input').prop('disabled'));

In this case, classB are added each time the input is disabled

Get raw POST body in Python Flask regardless of Content-Type header

I created a WSGI middleware that stores the raw body from the environ['wsgi.input'] stream. I saved the value in the WSGI environ so I could access it from request.environ['body_copy'] within my app.

This isn't necessary in Werkzeug or Flask, as request.get_data() will get the raw data regardless of content type, but with better handling of HTTP and WSGI behavior.

This reads the entire body into memory, which will be an issue if for example a large file is posted. This won't read anything if the Content-Length header is missing, so it won't handle streaming requests.

from io import BytesIO

class WSGICopyBody(object):
    def __init__(self, application):
        self.application = application

    def __call__(self, environ, start_response):
        length = int(environ.get('CONTENT_LENGTH') or 0)
        body = environ['wsgi.input'].read(length)
        environ['body_copy'] = body
        # replace the stream since it was exhausted by read()
        environ['wsgi.input'] = BytesIO(body)
        return self.application(environ, start_response)

app.wsgi_app = WSGICopyBody(app.wsgi_app)
request.environ['body_copy']

Get the generated SQL statement from a SqlCommand object?

From parameter command to non parameter command, You Can change this one

Using cmd As SqlCommand = Connection.CreateCommand
    cmd.CommandText = "UPDATE someTable SET Value = @Value"
    cmd.CommandText &= " WHERE Id = @Id"
    cmd.Parameters.AddWithValue("@Id", 1234)
    cmd.Parameters.AddWithValue("@Value", "myValue")
    cmd.ExecuteNonQuery
End Using

To

Private sub Update( byval myID as Int32, byval myVal as String)
    Using cmd As SqlCommand = Connection.CreateCommand
        cmd.CommandText = "UPDATE someTable SET Value = '" & myVaL & "'" & _
                          " WHERE Id = " & myID  
        cmd.ExecuteNonQuery
    End Using
End sub

C# - insert values from file into two arrays

var Text = File.ReadAllLines("Path"); foreach (var i in Text) {    var SplitText = i.Split().Where(x=> x.Lenght>1).ToList();    //@Array1 add SplitText[0]    //@Array2 add SpliteText[1]   }  

Javascript string/integer comparisons

The alert() wants to display a string, so it will interpret "2">"10" as a string.

Use the following:

var greater = parseInt("2") > parseInt("10");
alert("Is greater than? " + greater);

var less = parseInt("2") < parseInt("10");
alert("Is less than? " + less);

CRON command to run URL address every 5 minutes

To run a url, you need a program to get that url. You can try wget or curl. See manuals for available options.

React.js: Wrapping one component into another

In addition to Sophie's answer, I also have found a use in sending in child component types, doing something like this:

var ListView = React.createClass({
    render: function() {
        var items = this.props.data.map(function(item) {
            return this.props.delegate({data:item});
        }.bind(this));
        return <ul>{items}</ul>;
    }
});

var ItemDelegate = React.createClass({
    render: function() {
        return <li>{this.props.data}</li>
    }
});

var Wrapper = React.createClass({    
    render: function() {
        return <ListView delegate={ItemDelegate} data={someListOfData} />
    }
});

A Generic error occurred in GDI+ in Bitmap.Save method

Check your folder's permission where the image is saved Right cLick on folder then go :

Properties > Security > Edit > Add-- select "everyone" and check Allow "Full Control"

Flask example with POST

Before actually answering your question:

Parameters in a URL (e.g. key=listOfUsers/user1) are GET parameters and you shouldn't be using them for POST requests. A quick explanation of the difference between GET and POST can be found here.

In your case, to make use of REST principles, you should probably have:

http://ip:5000/users
http://ip:5000/users/<user_id>

Then, on each URL, you can define the behaviour of different HTTP methods (GET, POST, PUT, DELETE). For example, on /users/<user_id>, you want the following:

GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id> 

So, in your example, you want do a POST to /users/user_1 with the POST data being "John". Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.

Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
    if request.method == 'GET':
        """return the information for <user_id>"""
        .
        .
        .
    if request.method == 'POST':
        """modify/update the information for <user_id>"""
        # you can use <user_id>, which is a str but could
        # changed to be int or whatever you want, along
        # with your lxml knowledge to make the required
        # changes
        data = request.form # a multidict containing POST data
        .
        .
        .
    if request.method == 'DELETE':
        """delete user with ID <user_id>"""
        .
        .
        .
    else:
        # POST Error 405 Method Not Allowed
        .
        .
        .

There are a lot of other things to consider like the POST request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.

Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.

C# Switch-case string starting with

Try this and tell my if it works hope it help you:

string value = Convert.ToString(Console.ReadLine());

Switch(value)
{
    Case "abc":

    break;

    default:

    break;
}       

Copy file(s) from one project to another using post build event...VS2010

Call Batch file which will run Xcopy for required files source to destination

call "$(SolutionDir)scripts\copyifnewer.bat"

What is the difference between HTML tags <div> and <span>?

Just for the sake of completeness, I invite you to think about it like this:

  • There are lots of block elements (linebreaks before and after) defined in HTML, and lots of inline tags (no linebreaks).
  • But in modern HTML all elements are supposed to have meanings: a <p> is a paragraph, an <li> is a list item, etc., and we're supposed to use the right tag for the right purpose -- not like in the old days when we indented using <blockquote> whether the content was a quote or not.
  • So, what do you do when there is no meaning to the thing you're trying to do? There's no meaning to a 400px-wide column, is there? You just want your column of text to be 400px wide because that suits your design.
  • For this reason, they added two more elements to HTML: the generic, or meaningless elements <div> and <span>, because otherwise, people would go back to abusing the elements which do have meanings.

What is the best way to generate a unique and short file name in Java

I use the timestamp

i.e

new File( simpleDateFormat.format( new Date() ) );

And have the simpleDateFormat initialized to something like as:

new SimpleDateFormat("File-ddMMyy-hhmmss.SSS.txt");

EDIT

What about

new File(String.format("%s.%s", sdf.format( new Date() ),
                                random.nextInt(9)));

Unless the number of files created in the same second is too high.

If that's the case and the name doesn't matters

 new File( "file."+count++ );

:P

What does hash do in python?

The hash is used by dictionaries and sets to quickly look up the object. A good starting point is Wikipedia's article on hash tables.

How to get full path of a file?

find $PWD -type f | grep "filename"

or

find $PWD -type f -name "*filename*"

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

This can be fixed by changing your URL, example bad:

https://raw.githubusercontent.com/svnpenn/bm/master/yt-dl/yt-dl.js
Content-Type: text/plain; charset=utf-8

Example good:

https://cdn.rawgit.com/svnpenn/bm/master/yt-dl/yt-dl.js
content-type: application/javascript;charset=utf-8

rawgit.com is a caching proxy service for github. You can also go there and interactively derive a corresponding URL for your original raw.githubusercontent.com URL. See its FAQ

jQuery: how to trigger anchor link's click event

Even though this post is caput, I think it's an excellent demonstration of some walls that one can run into with jQuery, i.e. thinking click() actually clicks on an element, rather than just sending a click event bubbling up through the DOM. Let's say you actually need to simulate a click event (i.e. for testing purposes, etc.) If that's the case, provided that you're using a modern browser you can just use HTMLElement.prototype.click (see here for method details as well as a link to the W3 spec). This should work on almost all browsers, especially if you're dealing with links, and you can fall back to window.open pretty easily if you need to:

var clickLink = function(linkEl) {
  if (HTMLElement.prototype.click) {
    // You'll want to create a new element so you don't alter the page element's
    // attributes, unless of course the target attr is already _blank
    // or you don't need to alter anything
    var linkElCopy = $.extend(true, Object.create(linkEl), linkEl);
    $(linkElCopy).attr('target', '_blank');
    linkElCopy.click();
  } else {
    // As Daniel Doezema had said
    window.open($(linkEl).attr('href'));
  }
};

Laravel: How do I parse this json data in view blade?

For such case, you can do like this

@foreach (json_decode($leads->member) as $member)
     {{ $genre }}
@endforeach

Change Bootstrap input focus blue glow

This will work 100% use this:

.form-control, .form-control:focus{
   box-shadow: 0 0 0 0 rgba(255, 255, 255, 0);
   border: rgba(255, 255, 255, 0);
}

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

What range of values can integer types store in C++

The size of the numerical types is not defined in the C++ standard, although the minimum sizes are. The way to tell what size they are on your platform is to use numeric limits

For example, the maximum value for a int can be found by:

std::numeric_limits<int>::max();

Computers don't work in base 10, which means that the maximum value will be in the form of 2n-1 because of how the numbers of represent in memory. Take for example eight bits (1 byte)

  0100 1000

The right most bit (number) when set to 1 represents 20, the next bit 21, then 22 and so on until we get to the left most bit which if the number is unsigned represents 27.

So the number represents 26 + 23 = 64 + 8 = 72, because the 4th bit from the right and the 7th bit right the left are set.

If we set all values to 1:

11111111

The number is now (assuming unsigned)
128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255 = 28 - 1
And as we can see, that is the largest possible value that can be represented with 8 bits.

On my machine and int and a long are the same, each able to hold between -231 to 231 - 1. In my experience the most common size on modern 32 bit desktop machine.

Differences between key, superkey, minimal superkey, candidate key and primary key

Here I copy paste some of the information that I have collected

Key A key is a single or combination of multiple fields. Its purpose is to access or retrieve data rows from table according to the requirement. The keys are defined in tables to access or sequence the stored data quickly and smoothly. They are also used to create links between different tables.

Types of Keys

Primary Key The attribute or combination of attributes that uniquely identifies a row or record in a relation is known as primary key.

Secondary key A field or combination of fields that is basis for retrieval is known as secondary key. Secondary key is a non-unique field. One secondary key value may refer to many records.

Candidate Key or Alternate key A relation can have only one primary key. It may contain many fields or combination of fields that can be used as primary key. One field or combination of fields is used as primary key. The fields or combination of fields that are not used as primary key are known as candidate key or alternate key.

Composite key or concatenate key A primary key that consists of two or more attributes is known as composite key.

Sort Or control key A field or combination of fields that is used to physically sequence the stored data called sort key. It is also known s control key.

A superkey is a combination of attributes that can be uniquely used to identify a database record. A table might have many superkeys. Candidate keys are a special subset of superkeys that do not have any extraneous information in them.

Example for super key: Imagine a table with the fields <Name>, <Age>, <SSN> and <Phone Extension>. This table has many possible superkeys. Three of these are <SSN>, <Phone Extension, Name> and <SSN, Name>. Of those listed, only <SSN> is a candidate key, as the others contain information not necessary to uniquely identify records.

Foreign Key A foreign key is an attribute or combination of attribute in a relation whose value match a primary key in another relation. The table in which foreign key is created is called as dependent table. The table to which foreign key is refers is known as parent table.

Allow Access-Control-Allow-Origin header using HTML5 fetch API

Like epascarello said, the server that hosts the resource needs to have CORS enabled. What you can do on the client side (and probably what you are thinking of) is set the mode of fetch to CORS (although this is the default setting I believe):

fetch(request, {mode: 'cors'});

However this still requires the server to enable CORS as well, and allow your domain to request the resource.

Check out the CORS documentation, and this awesome Udacity video explaining the Same Origin Policy.

You can also use no-cors mode on the client side, but this will just give you an opaque response (you can't read the body, but the response can still be cached by a service worker or consumed by some API's, like <img>):

fetch(request, {mode: 'no-cors'})
.then(function(response) {
  console.log(response); 
}).catch(function(error) {  
  console.log('Request failed', error)  
});

Change Circle color of radio button

Sometimes you just need to override colorControlNormal like this:

    <style name="RadioButtonStyle" parent="AppTheme">
       <item name="colorControlNormal">@color/pink</item>
       <item name="colorAccent">@color/colorPrimary</item>
       <item name="android:textColorSecondary">@color/black</item>
    </style>

And you will get a button like this:

enter image description here

colorControlNormal used for unchecked state and colorAccent for checked.

C# windows application Event: CLR20r3 on application start

I encountered the same problem when I built an application on a Windows 7 box that had previously been maintained on an XP machine.

The program ran fine when built for Debug, but failed with this error when built for Release. I found the answer on the project's Properties page. Go to the "Build" tab and try changing the Platform Target from "Any CPU" to "x86".

Proper way to rename solution (and directories) in Visual Studio

I'm new to VS. I just had that same problem: Needed to rename an started project after a couple weeks work. This what I did and it worked.

  1. Just in case, make a backup of your folder Project, although you won't be touching it, but just in case!
  2. Create a new project and save it using the name you wish for your 'new' project, meaning the name you want to change your 'old' project to.
  3. Build it. After that you'll have a Project with the name you wanted but that it does not anything at all but open a window (a Windows Form App in my case).
  4. With the new proyect opened, click on Project->Add Existing Ítem and using Windows Explorer locate your 'old' folder Project and select all the files under ...Visual Studio xxx\Projects\oldApp\oldApp
  5. Select all files in there (.vb, .resx) and add them to your 'new' Project (the one that should be already opened).
  6. Almost last step would be to open your Project file using the Solution
    Explorer and in the 1st tab change the default startup form to the form it should be.
  7. Rebuild everything.

Maybe more steps but less or no typing at all, just some mouse clicks. Hope it helps :)

ASP.NET MVC3 Razor - Html.ActionLink style

Reviving an old question because it seems to appear at the top of search results.

I wanted to retain transition effects while still being able to style the actionlink so I came up with this solution.

  1. I wrapped the action link with a div that would contain the parent style:
<div class="parent-style-one">
      @Html.ActionLink("Homepage", "Home", "Home")
</div>
  1. Next I create the CSS for the div, this will be the parent css and will be inherited by the child elements such as the action link.
  .parent-style-one {
     /* your styles here */
  }
  1. Because all an action link is, is an element when broken down as html so you just need to target that element in your css selection:
  .parent-style-one a {
     text-decoration: none;
  }
  1. For transition effects I did this:
  .parent-style-one a:hover {
        text-decoration: underline;
        -webkit-transition-duration: 1.1s; /* Safari */
        transition-duration: 1.1s;         
  }

This way I only target the child elements of the div in this case the action link and still be able to apply transition effects.

Wipe data/Factory reset through ADB

After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.

 * The arguments which may be supplied in the recovery.command file:
 *   --send_intent=anystring - write the text out to recovery.intent
 *   --update_package=path - verify install an OTA package file
 *   --wipe_data - erase user data (and cache), then reboot
 *   --wipe_cache - wipe cache (but not user data), then reboot
 *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs

Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:

adb shell
recovery --wipe_data

Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.

EDIT:

For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command

For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c

Check If only numeric values were entered in input. (jQuery)

You can use jQuery method to check whether a value is numeric or other type.

$.isNumeric()

Example

$.isNumeric("46")

true

$.isNumeric(46)

true

$.isNumeric("dfd")

false

Display current path in terminal only

If you just want to get the information of current directory, you can type:

pwd

and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.

How to get full REST request body using Jersey?

Since you're transferring data in xml, you could also (un)marshal directly from/to pojos.

There's an example (and more info) in the jersey user guide, which I copy here:

POJO with JAXB annotations:

@XmlRootElement
public class Planet {
    public int id;
    public String name;
    public double radius;
}

Resource:

@Path("planet")
public class Resource {

    @GET
    @Produces(MediaType.APPLICATION_XML)
    public Planet getPlanet() {
        Planet p = new Planet();
        p.id = 1;
        p.name = "Earth";
        p.radius = 1.0;

        return p;
    }

    @POST
    @Consumes(MediaType.APPLICATION_XML)
    public void setPlanet(Planet p) {
        System.out.println("setPlanet " + p.name);
    }

}      

The xml that gets produced/consumed:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<planet>
    <id>1</id>
    <name>Earth</name>
    <radius>1.0</radius>
</planet>

How to access URL segment(s) in blade in Laravel 5?

Here is code you can get url segment.

{{ Request::segment(1) }}

If you don't want the data to be escaped then use {!! !!} else use {{ }}.

{!! Request::segment(1) !!}

https://laravel.com/docs/4.2/requests

Definitive way to trigger keypress events with jQuery

It can be accomplished like this docs

$('input').trigger("keydown", {which: 50});

Java regex to extract text between tags

A generic,simpler and a bit primitive approach to find tag, attribute and value

    Pattern pattern = Pattern.compile("<(\\w+)( +.+)*>((.*))</\\1>");
    System.out.println(pattern.matcher("<asd> TEST</asd>").find());
    System.out.println(pattern.matcher("<asd TEST</asd>").find());
    System.out.println(pattern.matcher("<asd attr='3'> TEST</asd>").find());
    System.out.println(pattern.matcher("<asd> <x>TEST<x>asd>").find());
    System.out.println("-------");
    Matcher matcher = pattern.matcher("<as x> TEST</as>");
    if (matcher.find()) {
        for (int i = 0; i <= matcher.groupCount(); i++) {
            System.out.println(i + ":" + matcher.group(i));
        }
    }

Uncaught TypeError: (intermediate value)(...) is not a function

To make semicolon rules simple

Every line that begins with a (, [, `, or any operator (/, +, - are the only valid ones), must begin with a semicolon.

func()
;[0].concat(myarr).forEach(func)
;(myarr).forEach(func)
;`hello`.forEach(func)
;/hello/.exec(str)
;+0
;-0

This prevents a

func()[0].concat(myarr).forEach(func)(myarr).forEach(func)`hello`.forEach(func)/hello/.forEach(func)+0-0

monstrocity.

Additional Note

To mention what will happen: brackets will index, parentheses will be treated as function parameters. The backtick would transform into a tagged template, and regex or explicitly signed integers will turn into operators. Of course, you can just add a semicolon to the end of every line. It's good to keep mind though when you're quickly prototyping and are dropping your semicolons.

Also, adding semicolons to the end of every line won't help you with the following, so keep in mind statements like

return // Will automatically insert semicolon, and return undefined.
    (1+2);
i // Adds a semicolon
   ++ // But, if you really intended i++ here, your codebase needs help.

The above case will happen to return/continue/break/++/--. Any linter will catch this with dead-code or ++/-- syntax error (++/-- will never realistically happen).

Finally, if you want file concatenation to work, make sure each file ends with a semicolon. If you're using a bundler program (recommended), it should do this automatically.

How to compile a c++ program in Linux?

Try this:

g++ -o hi hi.cpp

gcc is only for C

Escaping HTML strings with jQuery

ES6 one liner for the solution from mustache.js

const escapeHTML = str => (str+'').replace(/[&<>"'`=\/]/g, s => ({'&': '&amp;','<': '&lt;','>': '&gt;','"': '&quot;',"'": '&#39;','/': '&#x2F;','`': '&#x60;','=': '&#x3D;'})[s]);

load scripts asynchronously

Well, x.parentNode returns the HEAD element, so you are inserting the script just before the head tag. Maybe that's the problem.

Try x.parentNode.appendChild() instead.

Error handling in getJSON calls

_x000D_
_x000D_
$.getJSON("example.json", function() {_x000D_
  alert("success");_x000D_
})_x000D_
.success(function() { alert("second success"); })_x000D_
.error(function() { alert("error"); })
_x000D_
_x000D_
_x000D_

It is fixed in jQuery 2.x; In jQuery 1.x you will never get an error callback

Update multiple tables in SQL Server using INNER JOIN

You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :

BEGIN TRANSACTION

update A
set A.ORG_NAME =  @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID

update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
    on B.ORG_ID = A.ORG_ID
    and A.ORG_ID = @ORG_ID

COMMIT

Change primary key column in SQL Server

Assuming that your current primary key constraint is called pk_history, you can replace the following lines:

ALTER TABLE history ADD PRIMARY KEY (id)

ALTER TABLE history
DROP CONSTRAINT userId
DROP CONSTRAINT name

with these:

ALTER TABLE history DROP CONSTRAINT pk_history

ALTER TABLE history ADD CONSTRAINT pk_history PRIMARY KEY (id)

If you don't know what the name of the PK is, you can find it with the following query:

SELECT * 
  FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
 WHERE TABLE_NAME = 'history'

Does IE9 support console.log, and is it a real function?

After reading the article from Marc Cliament's comment above, I've now changed my all-purpose cross-browser console.log function to look like this:

function log()
{
    "use strict";

    if (typeof(console) !== "undefined" && console.log !== undefined)
    {
        try
        {
            console.log.apply(console, arguments);
        }
        catch (e)
        {
            var log = Function.prototype.bind.call(console.log, console);
            log.apply(console, arguments);
        }
    }
}

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

After battling with this for a day on a new machine I came across the following links. I was missing the rewrite modules. This fixed everything.

http://forums.iis.net/t/1176834.aspx

http://learn.iis.net/page.aspx/460/using-the-url-rewrite-module/

Android Writing Logs to text File

You can use the library I've written. It's very easy to use:

Add this dependency to your gradle file:

dependencies {
    compile 'com.github.danylovolokh:android-logger:1.0.2'
}

Initialize the library in the Application class:

File logsDirectory = AndroidLogger.getDefaultLogFilesDirectory(this);
    int logFileMaxSizeBytes = 2 * 1024 * 1024; // 2Mb
    try {
        AndroidLogger.initialize(
                this,
                logsDirectory,
                "Log_File_Name",
                logFileMaxSizeBytes,
                false
                );
    } catch (IOException e) {
        // Some error happened - most likely there is no free space on the system
    }

This is how you use the library:

AndroidLogger.v("TAG", "Verbose Message");

And this is how to retrieve the logs:

AndroidLogger.processPendingLogsStopAndGetLogFiles(new AndroidLogger.GetFilesCallback() {
        @Override
        public void onFiles(File[] logFiles) {
            // get everything you need from these files
            try {
                AndroidLogger.reinitAndroidLogger();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

Here is the link to the github page with more information: https://github.com/danylovolokh/AndroidLogger

Hope it helps.

Read file As String

this is working for me

i use this path

String FILENAME_PATH =  "/mnt/sdcard/Download/Version";

public static String getStringFromFile (String filePath) throws Exception {
    File fl = new File(filePath);
    FileInputStream fin = new FileInputStream(fl);
    String ret = convertStreamToString(fin);
    //Make sure you close all streams.
    fin.close();        
    return ret;

}

How do I use the built in password reset/change views with my own templates

The documentation says that there only one context variable, form.

If you're having trouble with login (which is common), the documentation says there are three context variables:

  • form: A Form object representing the login form. See the forms documentation for more on Form objects.
  • next: The URL to redirect to after successful login. This may contain a query string, too.
  • site_name: The name of the current Site, according to the SITE_ID setting.

Generating a WSDL from an XSD file

I'd like to differ with marc_s on this, who wrote:

a XSD describes the DATA aspects e.g. of a webservice - the WSDL describes the FUNCTIONS of the web services (method calls). You cannot typically figure out the method calls from your data alone.

WSDL does not describe functions. WSDL defines a network interface, which itself is comprised of endpoints that get messages and then sometimes reply with messages. WSDL describes the endpoints, and the request and reply messages. It is very much message oriented.

We often think of WSDL as a set of functions, but this is because the web services tools typically generate client-side proxies that expose the WSDL operations as methods or function calls. But the WSDL does not require this. This is a side effect of the tools.

EDIT: Also, in the general case, XSD does not define data aspects of a web service. XSD defines the elements that may be present in a compliant XML document. Such a document may be exchanged as a message over a web service endpoint, but it need not be.


Getting back to the question I would answer the original question a little differently. I woudl say YES, it is possible to generate a WSDL file given a xsd file, in the same way it is possible to generate an omelette using eggs.

EDIT: My original response has been unclear. Let me try again. I do not suggest that XSD is equivalent to WSDL, nor that an XSD is sufficient to produce a WSDL. I do say that it is possible to generate a WSDL, given an XSD file, if by that phrase you mean "to generate a WSDL using an XSD file". Doing so, you will augment the information in the XSD file to generate the WSDL. You will need to define additional things - message parts, operations, port types - none of these are present in the XSD. But it is possible to "generate a WSDL, given an XSD", with some creative effort.

If the phrase "generate a WSDL given an XSD" is taken to imply "mechanically transform an XSD into a WSDL", then the answer is NO, you cannot do that. This much should be clear given my description of the WSDL above.

When generating a WSDL using an XSD file, you will typically do something like this (note the creative steps in this procedure):

  1. import the XML schema into the WSDL (wsdl:types element)
  2. add to the set of types or elements with additional ones, or wrappers (let's say arrays, or structures containing the basic types) as desired. The result of #1 and #2 comprise all the types the WSDL will use.
  3. define a set of in and out messages (and maybe faults) in terms of those previously defined types.
  4. Define a port-type, which is the collection of pairings of in.out messages. You might think of port-type as a WSDL analog to a Java interface.
  5. Specify a binding, which implements the port-type and defines how messages will be serialized.
  6. Specify a service, which implements the binding.

Most of the WSDL is more or less boilerplate. It can look daunting, but that is mostly because of those scary and plentiful angle brackets, I've found.

Some have suggested that this is a long-winded manual process. Maybe. But this is how you can build interoperable services. You can also use tools for defining WSDL. Dynamically generating WSDL from code will lead to interop pitfalls.

SQL Update to the SUM of its joined values

An alternate to the above solutions is using Aliases for Tables:

UPDATE T1 SET T1.extrasPrice = (SELECT SUM(T2.Price) FROM BookingPitchExtras T2 WHERE T2.pitchID = T1.ID)
FROM BookingPitches T1;

milliseconds to days

If you don't have another time interval bigger than days:

int days = (int) (milliseconds / (1000*60*60*24));

If you have weeks too:

int days = (int) ((milliseconds / (1000*60*60*24)) % 7);
int weeks = (int) (milliseconds / (1000*60*60*24*7));

It's probably best to avoid using months and years if possible, as they don't have a well-defined fixed length. Strictly speaking neither do days: daylight saving means that days can have a length that is not 24 hours.

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

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

How do I get currency exchange rates via an API such as Google Finance?

Here are some exchange APIs with PHP example.

[ Open Exchange Rates API ]

Provides 1,000 requests per month free. You must register and grab the App ID. The base currency USD for free account. Check the supported currencies and documentation.

// open exchange URL // valid app_id * REQUIRED *
$exchange_url = 'https://openexchangerates.org/api/latest.json';
$params = array(
    'app_id' => 'YOUR_APP_ID'
);

// make cURL request // parse JSON
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => $exchange_url . '?' . http_build_query($params),
    CURLOPT_RETURNTRANSFER => true
));
$response = json_decode(curl_exec($curl));
curl_close($curl);

if (!empty($response->rates)) {
    // convert 150 USD to JPY ( Japanese Yen )
    echo $response->rates->JPY * 150;
}

150 USD = 18039.09015 JPY

[ Currency Layer API ]

Provides 1,000 requests per month free. You must register and grab the Access KEY. Custom base currency is not supported in free account. Check the documentation.

$exchange_url = 'http://apilayer.net/api/live';
$params = array(
    'access_key' => 'YOUR_ACCESS_KEY',
    'source' => 'USD',
    'currencies' => 'JPY',
    'format' => 1 // 1 = JSON
);

// make cURL request // parse JSON
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => $exchange_url . '?' . http_build_query($params),
    CURLOPT_RETURNTRANSFER => true
));
$response = json_decode(curl_exec($curl));
curl_close($curl);

if (!empty($response->quotes)) {
    // convert 150 USD to JPY ( Japanese Yen )
    echo '150 USD = ' . $response->quotes->USDJPY * 150 . ' JPY';
}

150 USD = 18036.75045 JPY

jQuery select by attribute using AND and OR operators

To properly select the elements using the logical operations that you've stated, you just need jQuery.filter() for the AND operation, not "special filter functions". You also need jQuery.add() for the OR operation.

var elements = $('[myc="blue"]').filter('[myid="1"').add('[myid="3"');

Alternatively, it is possible to accomplish using shorthand in a single selector, where jamming selectors together acts as an AND and separating with a comma acts as an OR:

var elements = $('[myc="blue"][myid="1"], [myid="3"]');

Loop through files in a directory using PowerShell

To get the content of a directory you can use

$files = Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files\"

Then you can loop over this variable as well:

for ($i=0; $i -lt $files.Count; $i++) {
    $outfile = $files[$i].FullName + "out" 
    Get-Content $files[$i].FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}

An even easier way to put this is the foreach loop (thanks to @Soapy and @MarkSchultheiss):

foreach ($f in $files){
    $outfile = $f.FullName + "out" 
    Get-Content $f.FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}

How to include "zero" / "0" results in COUNT aggregate?

USE join to get 0 count in the result using GROUP BY.

simply 'join' does Inner join in MS SQL so , Go for left or right join.

If the table which contains the primary key is mentioned first in the QUERY then use LEFT join else RIGHT join.

EG:

select WARDNO,count(WARDCODE) from MAIPADH 
right join  MSWARDH on MSWARDH.WARDNO= MAIPADH.WARDCODE
group by WARDNO

.

select WARDNO,count(WARDCODE) from MSWARDH
left join  MAIPADH on MSWARDH.WARDNO= MAIPADH.WARDCODE group by WARDNO

Take group by from the table which has Primary key and count from the another table which has actual entries/details.

"X does not name a type" error in C++

  1. Forward declare User
  2. Put the declaration of MyMessageBox before User

How to print color in console using System.out.println?

The best way to color console text is to use ANSI escape codes. In addition of text color, ANSI escape codes allows background color, decorations and more.

Unix

If you use springboot, there is a specific enum for text coloring: org.springframework.boot.ansi.AnsiColor

Jansi library is a bit more advanced (can use all the ANSI escape codes fonctions), provides an API and has a support for Windows using JNA.

Otherwise, you can manually define your own color, as shown is other responses.

Windows 10

Windows 10 (since build 10.0.10586 - nov. 2015) supports ANSI escape codes (MSDN documentation) but it's not enabled by default. To enable it:

  • With SetConsoleMode API, use ENABLE_VIRTUAL_TERMINAL_PROCESSING (0x0400) flag. Jansi uses this option.
  • If SetConsoleMode API is not used, it is possible to change the global registry key HKEY_CURRENT_USER\Console\VirtualTerminalLevel by creating a dword and set it to 0 or 1 for ANSI processing: "VirtualTerminalLevel"=dword:00000001

Before Windows 10

Windows console does not support ANSI colors. But it's possible to use console which does.

Extract matrix column values by matrix column name

Yes. But place your "test" after the comma if you want the column...

> A <- matrix(sample(1:12,12,T),ncol=4)

> rownames(A) <- letters[1:3]

> colnames(A) <- letters[11:14]
> A[,"l"]
 a  b  c 
 6 10  1 

see also help(Extract)

How to manually install an artifact in Maven 2?

I had to add packaging, so:

mvn install:install-file \
  -DgroupId=javax.transaction \
  -DartifactId=jta \
  -Dversion=1.0.1B \
  -Dfile=jta-1.0.1B.jar \
  -DgeneratePom=true \
  -Dpackaging=jar

Modify SVG fill color when being served as Background-Image

In some (very specific) situations this might be achieved by using a filter. For example, you can change a blue SVG image to purple by rotating the hue 45 degrees using filter: hue-rotate(45deg);. Browser support is minimal but it's still an interesting technique.

Demo

How to find the port for MS SQL Server 2008?

This may also be done via a port scan, which is the only possible method if you don't have admin access to a remote server.

Using Nmap (http://nmap.org/zenmap/) to do an "Intense TCP scan" will give you results like this for all instances on the server:

[10.0.0.1\DATABASE]    
Instance name: DATABASE
Version: Microsoft SQL Server 2008 R2 RTM    
Product: Microsoft SQL Server 2008 R2    
Service pack level: RTM    
TCP port: 49843    
Named pipe: \\10.0.0.1\pipe\MSSQL$DATABASE\sql\query

Important note: To test with query analyzer or MS SQL Server Management Studio you must form your server name and port differently than you would normally connect to a port, over HTTP for instance, using a comma instead of a colon.

  • Management Studio Server Name: 10.0.0.1,49843
  • Connection String: Data Source=10.0.0.1,49843

however

  • JDBC Connection String: jdbc:microsoft:sqlserver://10.0.0.1:49843;DatabaseName=DATABASE

text-align: right; not working for <label>

You can make a text align to the right inside of any element, including labels.

Html:

<label>Text</label>

Css:

label {display:block; width:x; height:y; text-align:right;}

This way, you give a width and height to your label and make any text inside of it align to the right.

How to alter a column and change the default value?

For DEFAULT CURRENT_TIMESTAMP:

ALTER TABLE tablename
 CHANGE COLUMN columnname1 columname1 DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
 CHANGE COLUMN columnname2 columname2 DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;

Please note double columnname declaration

Removing DEFAULT CURRENT_TIMESTAMP:

ALTER TABLE tablename
 ALTER COLUMN columnname1 DROP DEFAULT,
 ALTER COLUMN columnname2 DROPT DEFAULT;

SQL Server IF EXISTS THEN 1 ELSE 2

You can define a variable @Result to fill your data in it

DECLARE @Result AS INT

IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') 
SET @Result = 1 
else
SET @Result = 2

In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

I would use something like this for fixed length, like hashes:

md5sum = String.format("%032x", new BigInteger(1, md.digest()));

The 0 in the mask does the padding...

Why should the static field be accessed in a static way?

There's actually a good reason:
The non-static access does not always work, for reasons of ambiguity.

Suppose we have two classes, A and B, the latter being a subclass of A, with static fields with the same name:

public class A {
    public static String VALUE = "Aaa";
}

public class B extends A {
    public static String VALUE = "Bbb";
}

Direct access to the static variable:

A.VALUE (="Aaa")
B.VALUE (="Bbb")

Indirect access using an instance (gives a compiler warning that VALUE should be statically accessed):

new B().VALUE (="Bbb")

So far, so good, the compiler can guess which static variable to use, the one on the superclass is somehow farther away, seems somehow logical.

Now to the point where it gets tricky: Interfaces can also have static variables.

public interface C {
    public static String VALUE = "Ccc";
}

public interface D {
    public static String VALUE = "Ddd";
}

Let's remove the static variable from B, and observe following situations:

  • B implements C, D
  • B extends A implements C
  • B extends A implements C, D
  • B extends A implements C where A implements D
  • B extends A implements C where C extends D
  • ...

The statement new B().VALUE is now ambiguous, as the compiler cannot decide which static variable was meant, and will report it as an error:

error: reference to VALUE is ambiguous
both variable VALUE in C and variable VALUE in D match

And that's exactly the reason why static variables should be accessed in a static way.

Vim: How to insert in visual block mode?

  1. press ctrl and v // start select
  2. press shift and i // then type in any text
  3. press esc esc // press esc twice

javax.persistence.NoResultException: No entity found for query

Another option is to use uniqueResultOptional() method, which gives you Optional in result:

String hql="from DrawUnusedBalance where unusedBalanceDate= :today";
Query query=em.createQuery(hql);
query.setParameter("today",new LocalDate());

Optional<DrawUnusedBalance> drawUnusedBalance=query.uniqueResultOptional();

How could I create a list in c++?

If you are going to use std::list, you need to pass a type parameter:

list<int> intList;  
list<int>* intListPtr = new list<int>;

If you want to know how lists work, I recommending googling for some C/C++ tutorials to gain an understanding of that subject. Next step would then be learning enough C++ to create a list class, and finally a list template class.

If you have more questions, ask back here.

How do I remove leading whitespace in Python?

The function strip will remove whitespace from the beginning and end of a string.

my_str = "   text "
my_str = my_str.strip()

will set my_str to "text".

Only variable references should be returned by reference - Codeigniter

Edit filename: core/Common.php, line number: 257

Before

return $_config[0] =& $config; 

After

$_config[0] =& $config;
return $_config[0]; 

Update

Added by NikiC

In PHP assignment expressions always return the assigned value. So $_config[0] =& $config returns $config - but not the variable itself, but a copy of its value. And returning a reference to a temporary value wouldn't be particularly useful (changing it wouldn't do anything).

Update

This fix has been merged into CI 2.2.1 (https://github.com/bcit-ci/CodeIgniter/commit/69b02d0f0bc46e914bed1604cfbd9bf74286b2e3). It's better to upgrade rather than modifying core framework files.

Operand type clash: uniqueidentifier is incompatible with int

If you're accessing this via a View then try sp_recompile or refreshing views.

sp_recompile:

Causes stored procedures, triggers, and user-defined functions to be recompiled the next time that they are run. It does this by dropping the existing plan from the procedure cache forcing a new plan to be created the next time that the procedure or trigger is run. In a SQL Server Profiler collection, the event SP:CacheInsert is logged instead of the event SP:Recompile.

Arguments

[ @objname= ] 'object'

The qualified or unqualified name of a stored procedure, trigger, table, view, or user-defined function in the current database. object is nvarchar(776), with no default. If object is the name of a stored procedure, trigger, or user-defined function, the stored procedure, trigger, or function will be recompiled the next time that it is run. If object is the name of a table or view, all the stored procedures, triggers, or user-defined functions that reference the table or view will be recompiled the next time that they are run.

Return Code Values

0 (success) or a nonzero number (failure)

Remarks

sp_recompile looks for an object in the current database only.

The queries used by stored procedures, or triggers, and user-defined functions are optimized only when they are compiled. As indexes or other changes that affect statistics are made to the database, compiled stored procedures, triggers, and user-defined functions may lose efficiency. By recompiling stored procedures and triggers that act on a table, you can reoptimize the queries.

Deploying my application at the root in Tomcat

In tomcat 7 with these changes, i'm able to access myAPP at / and ROOT at /ROOT

<Context path="" docBase="myAPP">
     <!-- Default set of monitored resources -->
     <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
<Context path="ROOT" docBase="ROOT">
     <!-- Default set of monitored resources -->
     <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>

Add above to the <Host> section in server.xml

ImportError: No module named 'Queue'

It's because of the Python version. In Python 3 it's import Queue as queue; on the contrary in Python 2.x it's import queue. If you want it for both environments you may use something below as mentioned here

try:
   import queue
except ImportError:
   import Queue as queue

How to print a dictionary's key?

dict = {'name' : 'Fred', 'age' : 100, 'employed' : True }

# Choose key to print (could be a user input)
x = 'name'

if x in dict.keys():
    print(x)

Define constant variables in C++ header

You could simply define a series of const ints in a header file:

// Constants.h
#if !defined(MYLIB_CONSTANTS_H)
#define MYLIB_CONSTANTS_H 1

const int a = 100;
const int b = 0x7f;

#endif

This works because in C++ a name at namespace scope (including the global namespace) that is explicitly declared const and not explicitly declared extern has internal linkage, so these variables would not cause duplicate symbols when you link together translation units. Alternatively you could explicitly declare the constants as static.

static const int a = 100;
static const int b = 0x7f;

This is more compatible with C and more readable for people that may not be familiar with C++ linkage rules.

If all the constants are ints then another method you could use is to declare the identifiers as enums.

enum mylib_constants {
    a = 100;
    b = 0x7f;
};

All of these methods use only a header and allow the declared names to be used as compile time constants. Using extern const int and a separate implementation file prevents the names from being used as compile time constants.


Note that the rule that makes certain constants implicitly internal linkage does apply to pointers, exactly like constants of other types. The tricky thing though is that marking a pointer as const requires syntax a little different that most people use to make variables of other types const. You need to do:

int * const ptr;

to make a constant pointer, so that the rule will apply to it.

Also note that this is one reason I prefer to consistently put const after the type: int const instead of const int. I also put the * next to the variable: i.e. int *ptr; instead of int* ptr; (compare also this discussion).

I like to do these sorts of things because they reflect the general case of how C++ really works. The alternatives (const int, int* p) are just special cased to make some simple things more readable. The problem is that when you step out of those simple cases, the special cased alternatives become actively misleading.

So although the earlier examples show the common usage of const, I would actually recommend people write them like this:

int const a = 100;
int const b = 0x7f;

and

static int const a = 100;
static int const b = 0x7f;

Difference between h:button and h:commandButton

Here is what the JSF javadocs have to say about the commandButton action attribute:

MethodExpression representing the application action to invoke when this component is activated by the user. The expression must evaluate to a public method that takes no parameters, and returns an Object (the toString() of which is called to derive the logical outcome) which is passed to the NavigationHandler for this application.

It would be illuminating to me if anyone can explain what that has to do with any of the answers on this page. It seems pretty clear that action refers to some page's filename and not a method.

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

If you are in a country such as Argentina, you should call your bank and verify that your card is authorized for international purchases. Certain credit cards in that country (such as pre-paid credit cards) are ONLY authorized for domestic purchases and purchases in bordering countries. They DO work online, but the purchase must be from a bordering country. What this means is that you may get this message because your card is valid but denied. I know, because this has happened to me today. Hopefully this helps someone else understand what their system is telling them.

Email Address Validation for ASP.NET

Any script tags posted on an ASP.NET web form will cause your site to throw and unhandled exception.

You can use a asp regex validator to confirm input, just ensure you wrap your code behind method with a if(IsValid) clause in case your javascript is bypassed. If your client javascript is bypassed and script tags are posted to your asp.net form, asp.net will throw a unhandled exception.

You can use something like:

<asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>

Two values from one input in python?

You have to use the split() method which splits the input into two different inputs. Whatever you pass into the split is looked for and the input is split from there. In most cases its the white space.

For example, You give the input 23 24 25. You expect 3 different inputs like

num1 = 23
num2 = 24
num3 = 25

So in Python, You can do

num1,num2,num3 = input().split(" ")

Could not find any resources appropriate for the specified culture or the neutral culture

I resolved this by going to the project where my resources file was saved, scrolling down to its ItemGroup and adding a logical name that corresponded to the path the compiler expected.

My EmbeddedResource looked like this:

   <ItemGroup>
    <EmbeddedResource Update="Properties\TextResources.resx">
      <Generator>PublicResXFileCodeGenerator</Generator>
      <LastGenOutput>TextResources.Designer.cs</LastGenOutput>
    </EmbeddedResource>
  </ItemGroup>

Now it looks like this

  <ItemGroup>
    <EmbeddedResource Update="Properties\TextResources.resx">
      <Generator>PublicResXFileCodeGenerator</Generator>
      <LastGenOutput>TextResources.Designer.cs</LastGenOutput>
      <LogicalName>MyProject.Properties.Resources.resources</LogicalName>
    </EmbeddedResource>
  </ItemGroup>

How can I format a String number to have commas and round?

You might want to look at the DecimalFormat class; it supports different locales (eg: in some countries that would get formatted as 1.000.500.000,57 instead).

You also need to convert that string into a number, this can be done with:

double amount = Double.parseDouble(number);

Code sample:

String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");

System.out.println(formatter.format(amount));

Execute Python script via crontab

Just use crontab -e and follow the tutorial here.

Look at point 3 for a guide on how to specify the frequency.

Based on your requirement, it should effectively be:

*/10 * * * * /usr/bin/python script.py

Git error: src refspec master does not match any

You've created a new repository and added some files to the index, but you haven't created your first commit yet. After you've done:

 git add a_text_file.txt 

... do:

 git commit -m "Initial commit."

... and those errors should go away.

package android.support.v4.app does not exist ; in Android studio 0.8

tl;dr Remove all unused modules which have a dependency on the support library from your settings.gradle.

Long version:

In our case we had declared the support library as a dependency for all of our modules (one app module and multiple library modules) in a common.gradle file which is imported by every module. However there was one library module which wasn't declared as a dependency for any other module and therefore wasn't build. In every few syncs Android Studio would pick that exact module as the one where to look for the support library (that's why it appeared to happen randomly for us). As this module was never used it never got build which in turn caused the jar file not being in the intermediates folder of the module.

Removing this library module from settings.gradle and syncing again fixed the problem for us.

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

I am a little bit late, but I had this error too. I solved the problem by checking what where the values that where updating.

I found out that my query was wrong and that there where over 250+ edits pending. So I corrected my query, and now it works correct.

So in my situation: Check the query for errors, by debugging over the result that the query returns. After that correct the query.

Hope this helps resolving future problems.

Is it possible to set transparency in CSS3 box-shadow?

I suppose rgba() would work here. After all, browser support for both box-shadow and rgba() is roughly the same.

/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);

_x000D_
_x000D_
div {_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    line-height: 50px;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    background-color: red;_x000D_
    margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
  box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
_x000D_
_x000D_

How to find and turn on USB debugging mode on Nexus 4

In case you enabled debugging mode on your phone and adb devices is not listing your device, it seems there is a problem with phone driver. You might not install the usb-driver of your phone or driver might be installed with problems (in windows check in system --> device manager).

In my case, I had the same problem with My HTC android usb device which installing drivers again, fixed my problems.

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

Where does Console.WriteLine go in ASP.NET?

I've found this question by trying to change the Log output of the DataContext to the output window. So to anyone else trying to do the same, what I've done was create this:

class DebugTextWriter : System.IO.TextWriter {
   public override void Write(char[] buffer, int index, int count) {
       System.Diagnostics.Debug.Write(new String(buffer, index, count));
   }

   public override void Write(string value) {
       System.Diagnostics.Debug.Write(value);
   }

   public override Encoding Encoding {
       get { return System.Text.Encoding.Default; }
   }
}

Annd after that: dc.Log = new DebugTextWriter() and I can see all the queries in the output window (dc is the DataContext).

Have a look at this for more info: http://damieng.com/blog/2008/07/30/linq-to-sql-log-to-debug-window-file-memory-or-multiple-writers

How can I export Excel files using JavaScript?

Create an AJAX postback method which writes a CSV file to your webserver and returns the url.. Set a hidden IFrame in the browser to the location of the CSV file on the server.

Your user will then be presented with the CSV download link.

what is the difference between const_iterator and iterator?

Performance wise there is no difference. The only purpose of having const_iterator over iterator is to manage the accessesibility of the container on which the respective iterator runs. You can understand it more clearly with an example:

std::vector<int> integers{ 3, 4, 56, 6, 778 };

If we were to read & write the members of a container we will use iterator:

for( std::vector<int>::iterator it = integers.begin() ; it != integers.end() ; ++it )
       {*it = 4;  std::cout << *it << std::endl; }

If we were to only read the members of the container integers you might wanna use const_iterator which doesn't allow to write or modify members of container.

for( std::vector<int>::const_iterator it = integers.begin() ; it != integers.end() ; ++it )
       { cout << *it << endl; }

NOTE: if you try to modify the content using *it in second case you will get an error because its read-only.

"break;" out of "if" statement?

break interacts solely with the closest enclosing loop or switch, whether it be a for, while or do .. while type. It is frequently referred to as a goto in disguise, as all loops in C can in fact be transformed into a set of conditional gotos:

for (A; B; C) D;
// translates to
A;
goto test;
loop: D;
iter: C;
test: if (B) goto loop;
end:

while (B) D;          // Simply doesn't have A or C
do { D; } while (B);  // Omits initial goto test
continue;             // goto iter;
break;                // goto end;

The difference is, continue and break interact with virtual labels automatically placed by the compiler. This is similar to what return does as you know it will always jump ahead in the program flow. Switches are slightly more complicated, generating arrays of labels and computed gotos, but the way break works with them is similar.

The programming error the notice refers to is misunderstanding break as interacting with an enclosing block rather than an enclosing loop. Consider:

for (A; B; C) {
   D;
   if (E) {
       F;
       if (G) break;   // Incorrectly assumed to break if(E), breaks for()
       H;
   }
   I;
}
J;

Someone thought, given such a piece of code, that G would cause a jump to I, but it jumps to J. The intended function would use if (!G) H; instead.

How to Set a Custom Font in the ActionBar Title?

To add to @Sam_D's answer, I had to do this to make it work:

this.setTitle("my title!");
((TextView)v.findViewById(R.id.title)).setText(this.getTitle());
TextView title = ((TextView)v.findViewById(R.id.title));
title.setEllipsize(TextUtils.TruncateAt.MARQUEE);
title.setMarqueeRepeatLimit(1);
// in order to start strolling, it has to be focusable and focused
title.setFocusable(true);
title.setSingleLine(true);
title.setFocusableInTouchMode(true);
title.requestFocus();

It seems like overkill - referencing v.findViewById(R.id.title)) twice - but that's the only way it would let me do it.

How to limit the maximum value of a numeric field in a Django model?

There are two ways to do this. One is to use form validation to never let any number over 50 be entered by a user. Form validation docs.

If there is no user involved in the process, or you're not using a form to enter data, then you'll have to override the model's save method to throw an exception or limit the data going into the field.

How do you convert an entire directory with ffmpeg?

If you want a graphical interface to batch process with ffmpegX, try Quick Batcher. It's free and will take your last ffmpegX settings to convert files you drop into it.

Note that you can't drag-drop folders onto Quick Batcher. So select files and then put them through Quick Batcher.

SQL where datetime column equals today's date?

Can you try this?

SELECT [Title], [Firstname], [Surname], [Company_name], [Interest] 
FROM [dbo].[EXTRANET_users] 
WHERE CAST(Submission_date AS DATE) = CAST(GETDATE() AS DATE)

T-SQL doesn't really have the "implied" casting like C# does - you need to explicitly use CAST (or CONVERT).

Also, use GETDATE() or CURRENT_TIMESTAMP to get the "now" date and time.

Update: since you're working against SQL Server 2000 - none of those approaches so far work. Try this instead:

SELECT [Title], [Firstname], [Surname], [Company_name], [Interest] 
FROM [dbo].[EXTRANET_users] 
WHERE DATEADD(dd, 0, DATEDIFF(dd, 0, submission_date)) = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))

Remove all child nodes from a parent?

A other users suggested,

.empty()

is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.

If you wish to keep data, like event handlers for example, you should use

.detach()

as described on the JQuery's API detach documentation.

The method .remove() could be usefull for similar purposes.

How to stop a thread created by implementing runnable interface?

If you use ThreadPoolExecutor, and you use submit() method, it will give you a Future back. You can call cancel() on the returned Future to stop your Runnable task.

How to access a dictionary element in a Django template?

Similar to the answer by @russian_spy :

<ul>
{% for choice in choices.items %} 
  <li>{{choice.0}} - {{choice.1}}</li>
{% endfor %}
</ul>

This might be suitable for breaking down more complex dictionaries.

Writing a pandas DataFrame to CSV file

Example of export in file with full path on Windows and in case your file has headers:

df.to_csv (r'C:\Users\John\Desktop\export_dataframe.csv', index = None, header=True) 

For example, if you want to store the file in same directory where your script is, with utf-8 encoding and tab as separator:

df.to_csv(r'./export/dftocsv.csv', sep='\t', encoding='utf-8', header='true')

Determine the type of an object?

As an aside to the previous answers, it's worth mentioning the existence of collections.abc which contains several abstract base classes (ABCs) that complement duck-typing.

For example, instead of explicitly checking if something is a list with:

isinstance(my_obj, list)

you could, if you're only interested in seeing if the object you have allows getting items, use collections.abc.Sequence:

from collections.abc import Sequence
isinstance(my_obj, Sequence) 

if you're strictly interested in objects that allow getting, setting and deleting items (i.e mutable sequences), you'd opt for collections.abc.MutableSequence.

Many other ABCs are defined there, Mapping for objects that can be used as maps, Iterable, Callable, et cetera. A full list of all these can be seen in the documentation for collections.abc.

How to import js-modules into TypeScript file?

You can import the whole module as follows:

import * as FriendCard from './../pages/FriendCard';

For more details please refer the modules section of Typescript official docs.

Is calling destructor manually always a sign of bad design?

Found another example where you would have to call destructor(s) manually. Suppose you have implemented a variant-like class that holds one of several types of data:

struct Variant {
    union {
        std::string str;
        int num;
        bool b;
    };
    enum Type { Str, Int, Bool } type;
};

If the Variant instance was holding a std::string, and now you're assigning a different type to the union, you must destruct the std::string first. The compiler will not do that automatically.

Regex any ASCII character

Depending on what you mean with "ASCII character" you could simply try:

xxx.+xxx

convert ArrayList<MyCustomClass> to JSONArray

public void itemListToJsonConvert(ArrayList<HashMap<String, String>> list) {

        JSONObject jResult = new JSONObject();// main object
        JSONArray jArray = new JSONArray();// /ItemDetail jsonArray

        for (int i = 0; i < list.size(); i++) {
            JSONObject jGroup = new JSONObject();// /sub Object

            try {
                jGroup.put("ItemMasterID", list.get(i).get("ItemMasterID"));
                jGroup.put("ID", list.get(i).get("id"));
                jGroup.put("Name", list.get(i).get("name"));
                jGroup.put("Category", list.get(i).get("category"));

                jArray.put(jGroup);

                // /itemDetail Name is JsonArray Name
                jResult.put("itemDetail", jArray);
                return jResult;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

Drop Down Menu/Text Field in one

You can use the <datalist> tag instead of the <select> tag.

<input list="browsers" name="browser" id="browser">
<datalist id="browsers">
  <option value="Edge">
  <option value="Firefox">
  <option value="Chrome">
  <option value="Opera">
  <option value="Safari">
</datalist>

Is there a Sleep/Pause/Wait function in JavaScript?

setTimeout() function it's use to delay a process in JavaScript.

w3schools has an easy tutorial about this function.

Generating Request/Response XML from a WSDL

Try this online tool: https://www.wsdl-analyzer.com. It appears to be free and does a lot more than just generate XML for requests and response.

There is also this: https://www.oxygenxml.com/xml_editor/wsdl_soap_analyzer.html, which can be downloaded, but not free.

How can I create an MSI setup?

You can use Wix (which is free) to create an MSI installation package.

WiX Tutorial - Creating an Installer MSI with Wix

Inserting image into IPython notebook markdown

First make sure you are in markdown edit model in the ipython notebook cell

This is an alternative way to the method proposed by others <img src="myimage.png">:

![title](img/picture.png)

It also seems to work if the title is missing:

![](img/picture.png)

Note no quotations should be in the path. Not sure if this works for paths with white spaces though!

How to use andWhere and orWhere in Doctrine?

Why not just

$q->where("a = 1");
$q->andWhere("b = 1 OR b = 2");
$q->andWhere("c = 1 OR d = 2");

EDIT: You can also use the Expr class (Doctrine2).

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

Finding the max value of an attribute in an array of objects

Comparison of three ONELINERS which handle minus numbers case (input in a array):

var maxA = a.reduce((a,b)=>a.y>b.y?a:b).y; // 30 chars time complexity:  O(n)

var maxB = a.sort((a,b)=>b.y-a.y)[0].y;    // 27 chars time complexity:  O(nlogn)
           
var maxC = Math.max(...a.map(o=>o.y));     // 26 chars time complexity: >O(2n)

editable example here. Ideas from: maxA, maxB and maxC (side effect of maxB is that array a is changed because sort is in-place).

_x000D_
_x000D_
var a = [
  {"x":"8/11/2009","y":0.026572007},{"x":"8/12/2009","y":0.025057454},    
  {"x":"8/14/2009","y":0.031004457},{"x":"8/13/2009","y":0.024530916}
]

var maxA = a.reduce((a,b)=>a.y>b.y?a:b).y;
var maxC = Math.max(...a.map(o=>o.y));
var maxB = a.sort((a,b)=>b.y-a.y)[0].y;

document.body.innerHTML=`<pre>maxA: ${maxA}\nmaxB: ${maxB}\nmaxC: ${maxC}</pre>`;
_x000D_
_x000D_
_x000D_

For bigger arrays the Math.max... will throw exception: Maximum call stack size exceeded (Chrome 76.0.3809, Safari 12.1.2, date 2019-09-13)

_x000D_
_x000D_
let a = Array(400*400).fill({"x": "8/11/2009", "y": 0.026572007 }); 

// Exception: Maximum call stack size exceeded

try {
  let max1= Math.max.apply(Math, a.map(o => o.y));
} catch(e) { console.error('Math.max.apply:', e.message) }

try {
  let max2= Math.max(...a.map(o=>o.y));
} catch(e) { console.error('Math.max-map:', e.message) }
_x000D_
_x000D_
_x000D_

Benchmark for the 4 element array

Updating and committing only a file's permissions using git version control

@fooMonster article worked for me

# git ls-tree HEAD
100644 blob 55c0287d4ef21f15b97eb1f107451b88b479bffe    script.sh

As you can see the file has 644 permission (ignoring the 100). We would like to change it to 755:

# git update-index --chmod=+x script.sh

commit the changes

# git commit -m "Changing file permissions"
[master 77b171e] Changing file permissions
0 files changed, 0 insertions(+), 0 deletions(-)
mode change 100644 => 100755 script.sh

How can I roll back my last delete command in MySQL?

If you didn't commit the transaction yet, try rollback. If you have already committed the transaction (by commit or by exiting the command line client), you must restore the data from your last backup.

How SQL query result insert in temp table?

Look at SELECT INTO. This will create a new table for you, which can be temporary if you want by prefixing the table name with a pound sign (#).

For example, you can do:

SELECT * 
INTO #YourTempTable
FROM YourReportQuery

How to implement the factory method pattern in C++ correctly

First of all, there are cases when object construction is a task complex enough to justify its extraction to another class.

I believe this point is incorrect. The complexity doesn't really matter. The relevance is what does. If an object can be constructed in one step (not like in the builder pattern), the constructor is the right place to do it. If you really need another class to perform the job, then it should be a helper class that is used from the constructor anyway.

Vec2(float x, float y);
Vec2(float angle, float magnitude); // not a valid overload!

There is an easy workaround for this:

struct Cartesian {
  inline Cartesian(float x, float y): x(x), y(y) {}
  float x, y;
};
struct Polar {
  inline Polar(float angle, float magnitude): angle(angle), magnitude(magnitude) {}
  float angle, magnitude;
};
Vec2(const Cartesian &cartesian);
Vec2(const Polar &polar);

The only disadvantage is that it looks a bit verbose:

Vec2 v2(Vec2::Cartesian(3.0f, 4.0f));

But the good thing is that you can immediately see what coordinate type you're using, and at the same time you don't have to worry about copying. If you want copying, and it's expensive (as proven by profiling, of course), you may wish to use something like Qt's shared classes to avoid copying overhead.

As for the allocation type, the main reason to use the factory pattern is usually polymorphism. Constructors can't be virtual, and even if they could, it wouldn't make much sense. When using static or stack allocation, you can't create objects in a polymorphic way because the compiler needs to know the exact size. So it works only with pointers and references. And returning a reference from a factory doesn't work too, because while an object technically can be deleted by reference, it could be rather confusing and bug-prone, see Is the practice of returning a C++ reference variable, evil? for example. So pointers are the only thing that's left, and that includes smart pointers too. In other words, factories are most useful when used with dynamic allocation, so you can do things like this:

class Abstract {
  public:
    virtual void do() = 0;
};

class Factory {
  public:
    Abstract *create();
};

Factory f;
Abstract *a = f.create();
a->do();

In other cases, factories just help to solve minor problems like those with overloads you have mentioned. It would be nice if it was possible to use them in a uniform way, but it doesn't hurt much that it is probably impossible.

How do you count the elements of an array in java

If you assume that 0 is not a valid item in the array then the following code should work:

   public static void main( String[] args )
   {
      int[] theArray = new int[20];
      theArray[0] = 1;
      theArray[1] = 2;

      System.out.println(count(theArray));
   }

   private static int count(int[] array) 
   {
      int count = 0;
      for(int i : array)
      {
         if(i > 0)
         {
            count++;
         }
      }
      return count;
   }

jquery/javascript convert date string to date

var stringDate = "Sunday, February 28, 2010";

var months = ["January", "February", "March"]; // You add the rest  :-)

var m = /(\w+) (\d+), (\d+)/.exec(stringDate);

var date = new Date(+m[3], months.indexOf(m[1]), +m[2]);

The indexOf method on arrays is only supported on newer browsers (i.e. not IE). You'll need to do the searching yourself or use one of the many libraries that provide the same functionality.

Also the code is lacking any error checking which should be added. (String not matching the regular expression, non existent months, etc.)

Window.open as modal popup?

A pop-up is a child of the parent window, but it is not a child of the parent DOCUMENT. It is its own independent browser window and is not contained by the parent.

Use an absolutely-positioned DIV and a translucent overlay instead.

EDIT - example

You need jQuery for this:

<style>
html, body {
    height:100%
}


#overlay { 
    position:absolute;
    z-index:10;
    width:100%;
    height:100%;
    top:0;
    left:0;
    background-color:#f00;
    filter:alpha(opacity=10);
    -moz-opacity:0.1;
    opacity:0.1;
    cursor:pointer;

} 

.dialog {
    position:absolute;
    border:2px solid #3366CC;
    width:250px;
    height:120px;
    background-color:#ffffff;
    z-index:12;
}

</style>
<script type="text/javascript">
$(document).ready(function() { init() })

function init() {
    $('#overlay').click(function() { closeDialog(); })
}

function openDialog(element) {
    //this is the general dialog handler.
    //pass the element name and this will copy
    //the contents of the element to the dialog box

    $('#overlay').css('height', $(document.body).height() + 'px')
    $('#overlay').show()
    $('#dialog').html($(element).html())
    centerMe('#dialog')
    $('#dialog').show();
}

function closeDialog() {
    $('#overlay').hide();
    $('#dialog').hide().html('');
}

function centerMe(element) {
    //pass element name to be centered on screen
    var pWidth = $(window).width();
    var pTop = $(window).scrollTop()
    var eWidth = $(element).width()
    var height = $(element).height()
    $(element).css('top', '130px')
    //$(element).css('top',pTop+100+'px')
    $(element).css('left', parseInt((pWidth / 2) - (eWidth / 2)) + 'px')
}


</script>


<a href="javascript:;//close me" onclick="openDialog($('#content'))">show dialog A</a>

<a href="javascript:;//close me" onclick="openDialog($('#contentB'))">show dialog B</a>

<div id="dialog" class="dialog" style="display:none"></div>
<div id="overlay" style="display:none"></div>
<div id="content" style="display:none">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisl felis, placerat in sollicitudin quis, hendrerit vitae diam. Nunc ornare iaculis urna. 
</div>

<div id="contentB" style="display:none">
    Moooo mooo moo moo moo!!! 
</div>

How can I search for a commit message on GitHub?

Using Advanced Search on Github seemed the easiest with a combination of other answers. It's basically a search string builder. https://github.com/search/advanced

For example I wanted to find all commits in Autodesk/maya-usd containing "USD" enter image description here

Then in the search results can choose Commits from the list on the left: enter image description here

How to get duration, as int milli's and float seconds from <chrono>?

I don't know what "milliseconds and float seconds" means, but this should give you an idea:

#include <chrono>
#include <thread>
#include <iostream>

int main()
{
  auto then = std::chrono::system_clock::now();
  std::this_thread::sleep_for(std::chrono::seconds(1));
  auto now = std::chrono::system_clock::now();
  auto dur = now - then;
  typedef std::chrono::duration<float> float_seconds;
  auto secs = std::chrono::duration_cast<float_seconds>(dur);
  std::cout << secs.count() << '\n';
}

Find duplicate values in R

Here, I summarize a few ways which may return different results to your question, so be careful:

# First assign your "id"s to an R object.
# Here's a hypothetical example:
id <- c("a","b","b","c","c","c","d","d","d","d")

#To return ALL MINUS ONE duplicated values:
id[duplicated(id)]
## [1] "b" "c" "c" "d" "d" "d"

#To return ALL duplicated values by specifying fromLast argument:
id[duplicated(id) | duplicated(id, fromLast=TRUE)]
## [1] "b" "b" "c" "c" "c" "d" "d" "d" "d"

#Yet another way to return ALL duplicated values, using %in% operator:
id[ id %in% id[duplicated(id)] ]
## [1] "b" "b" "c" "c" "c" "d" "d" "d" "d"

Hope these help. Good luck.

Nginx 403 forbidden for all files

Old question, but I had the same issue. I tried every answer above, nothing worked. What fixed it for me though was removing the domain, and adding it again. I'm using Plesk, and I installed Nginx AFTER the domain was already there.

Did a local backup to /var/www/backups first though. So I could easily copy back the files.

Strange problem....

How to access private data members outside the class without making "friend"s?

It's possible to access the private data of class directly in main and other's function...

here is a small code...

class GIFT
{
    int i,j,k;

public:
    void Fun() 
    {
        cout<< i<<" "<< j<<" "<< k;
    }

};

int main()
{
     GIFT *obj=new GIFT(); // the value of i,j,k is 0
     int *ptr=(int *)obj;
     *ptr=10;
     cout<<*ptr;      // you also print value of I
     ptr++;
     *ptr=15;
     cout<<*ptr;      // you also print value of J
     ptr++;
     *ptr=20; 
     cout<<*ptr;      // you also print value of K
     obj->Fun();
}

./configure : /bin/sh^M : bad interpreter

You can also do this in Kate.

  1. Open the file
  2. Open the Tools menu
  3. Expand the End Of Line submenu
  4. Select UNIX
  5. Save the file.

Regex for numbers only

Regex regex = new Regex ("^[0-9]{1,4}=[0-9]{1,4]$")

Bower: ENOGIT Git is not installed or not in the PATH

Run the following command at your node.js command prompt where "<git path>" is the path to your git bin folder:

set PATH=%PATH%;<git path>;

So, like this:

set PATH=%PATH%;C:\Program Files\Git\bin;

Or this: (Notice the (x86) )

set PATH=%PATH%;C:\Program Files (x86)\Git\bin;

This will add git to your path variables. Be sure you type it correctly or you could possibly delete your path vars which would be bad.

How to ignore conflicts in rpm installs

From the context, the conflict was caused by the version of the package.
Let's take a look the manual about rpm:

--force
    Same as using --replacepkgs, --replacefiles, and --oldpackage.

--oldpackage
    Allow an upgrade to replace a newer package with an older one.

So, you can execute the command rpm -Uvh info-4.13a-2.rpm --force to solve your issue.

Call a Subroutine from a different Module in VBA

Prefix the call with Module2 (ex. Module2.IDLE). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.

How do I include inline JavaScript in Haml?

You can actually do what Chris Chalmers does in his answer, but you must make sure that HAML doesn't parse the JavaScript. This approach is actually useful when you need to use a different type than text/javascript, which is was I needed to do for MathJax.

You can use the plain filter to keep HAML from parsing the script and throwing an illegal nesting error:

%script{type: "text/x-mathjax-config"}
  :plain
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [["$","$"],["\\(","\\)"]]
      }
    });

Save and load MemoryStream to/from a file

The combined answer for writing to a file can be;

MemoryStream ms = new MemoryStream();    
FileStream file = new FileStream("file.bin", FileMode.Create, FileAccess.Write);
ms.WriteTo(file);
file.Close();
ms.Close();

Nodejs cannot find installed module on Windows

I stumbled on this question because I want to use node.js with visual studio 2015 on my new computer with windows 10. I used node.js on windows 7 and 8 and 8.1 Never a problem node.js finding a module. I use a legacy node.js 0.10.39 because I have to use this version because of the serial and RFXCOM module.

The answer for windows 10 is to set the NODE_PATH in the enviroment variables with C:\Users\User\node_modules.

Print the contents of a DIV

Although this has been said by @gabe, If you are using jQuery, you can use my printElement plugin.

There's a sample here, and more information about the plugin here.

The usage is rather straight forward, just grab an element with a jQuery selector and print it:

$("#myDiv").printElement();

I hope it helps!

C# equivalent of C++ vector, with contiguous memory?

First of all, stay away from Arraylist or Hashtable. Those classes are to be considered deprecated, in favor of generics. They are still in the language for legacy purposes.

Now, what you are looking for is the List<T> class. Note that if T is a value type you will have contiguos memory, but not if T is a reference type, for obvious reasons.

How can I display a messagebox in ASP.NET?

create a simple JavaScript function having one line of code-"alert("Hello this is an Alert")" and instead on OnClick() ,use OnClientClick() method.

`<html xmlns="http://www.w3.org/1999/xhtml">
 <head runat="server">
 <title></title>
 <script type="text/javascript" language="javascript">
    function showAlert() {
        alert("Hello this is an Alert")
    }
 </script>
 </head>
 <body>
 <form id="form1" runat="server">
 <div>
 <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="showAlert()" />
 </div>
 </form>
 </body>
 </html>`

Returning binary file from controller in ASP.NET Web API

For anyone having the problem of the API being called more than once while downloading a fairly large file using the method in the accepted answer, please set response buffering to true System.Web.HttpContext.Current.Response.Buffer = true;

This makes sure that the entire binary content is buffered on the server side before it is sent to the client. Otherwise you will see multiple request being sent to the controller and if you do not handle it properly, the file will become corrupt.

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

In my case, on commenting out the

<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/> 

in the web.config file was throwing "Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata".

Check list of words in another string

Here are a couple of alternative ways of doing it, that may be faster or more suitable than KennyTM's answer, depending on the context.

1) use a regular expression:

import re
words_re = re.compile("|".join(list_of_words))

if words_re.search('some one long two phrase three'):
   # do logic you want to perform

2) You could use sets if you want to match whole words, e.g. you do not want to find the word "the" in the phrase "them theorems are theoretical":

word_set = set(list_of_words)
phrase_set = set('some one long two phrase three'.split())
if word_set.intersection(phrase_set):
    # do stuff

Of course you can also do whole word matches with regex using the "\b" token.

The performance of these and Kenny's solution are going to depend on several factors, such as how long the word list and phrase string are, and how often they change. If performance is not an issue then go for the simplest, which is probably Kenny's.

The point of test %eax %eax

Some x86 instructions are designed to leave the content of the operands (registers) as they are and just set/unset specific internal CPU flags like the zero-flag (ZF). You can think at the ZF as a true/false boolean flag that resides inside the CPU.

in this particular case, TEST instruction performs a bitwise logical AND, discards the actual result and sets/unsets the ZF according to the result of the logical and: if the result is zero it sets ZF = 1, otherwise it sets ZF = 0.

Conditional jump instructions like JE are designed to look at the ZF for jumping/notjumping so using TEST and JE together is equivalent to perform a conditional jump based on the value of a specific register:

example:

TEST EAX,EAX
JE some_address



the CPU will jump to "some_address" if and only if ZF = 1, in other words if and only if AND(EAX,EAX) = 0 which in turn it can occur if and only if EAX == 0

the equivalent C code is:

if(eax == 0)
{
    goto some_address
}

Removing All Items From A ComboBox?

Best Way:

Combobox1.items.clear();

Why can't I check if a 'DateTime' is 'Nothing'?

You can also use below just simple to check:

If startDate <> Nothing Then
your logic
End If

It will check that the startDate variable of DateTime datatype is null or not.

Can someone explain __all__ in Python?

__all__ is used to document the public API of a Python module. Although it is optional, __all__ should be used.

Here is the relevant excerpt from the Python language reference:

The public names defined by a module are determined by checking the module’s namespace for a variable named __all__; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in __all__ are all considered public and are required to exist. If __all__ is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ('_'). __all__ should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).

PEP 8 uses similar wording, although it also makes it clear that imported names are not part of the public API when __all__ is absent:

To better support introspection, modules should explicitly declare the names in their public API using the __all__ attribute. Setting __all__ to an empty list indicates that the module has no public API.

[...]

Imported names should always be considered an implementation detail. Other modules must not rely on indirect access to such imported names unless they are an explicitly documented part of the containing module's API, such as os.path or a package's __init__ module that exposes functionality from submodules.

Furthermore, as pointed out in other answers, __all__ is used to enable wildcard importing for packages:

The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered.

Getting the HTTP Referrer in ASP.NET

Since Google takes you to this post when searching for C# Web API Referrer here's the deal: Web API uses a different type of Request from normal MVC Request called HttpRequestMessage which does not include UrlReferrer. Since a normal Web API request does not include this information, if you really need it, you must have your clients go out of their way to include it. Although you could make this be part of your API Object, a better way is to use Headers.

First, you can extend HttpRequestMessage to provide a UrlReferrer() method:

public static string UrlReferrer(this HttpRequestMessage request)
{
    return request.Headers.Referrer == null ? "unknown" : request.Headers.Referrer.AbsoluteUri;
}

Then your clients need to set the Referrer Header to their API Request:

// Microsoft.AspNet.WebApi.Client
client.DefaultRequestHeaders.Referrer = new Uri(url);

And now the Web API Request includes the referrer data which you can access like this from your Web API:

Request.UrlReferrer();

How to add a footer in ListView?

The activity in which you want to add listview footer and i have also generate an event on listview footer click.

  public class MainActivity extends Activity
{

        @Override
        protected void onCreate(Bundle savedInstanceState)
         {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            ListView  list_of_f = (ListView) findViewById(R.id.list_of_f);

            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View view = inflater.inflate(R.layout.web_view, null);  // i have open a webview on the listview footer

            RelativeLayout  layoutFooter = (RelativeLayout) view.findViewById(R.id.layoutFooter);

            list_of_f.addFooterView(view);

        }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg" >

    <ImageView
        android:id="@+id/dept_nav"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/dept_nav" />

    <ListView
        android:id="@+id/list_of_f"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/dept_nav"
        android:layout_margin="5dp"
        android:layout_marginTop="10dp"
        android:divider="@null"
        android:dividerHeight="0dp"
        android:listSelector="@android:color/transparent" >
    </ListView>

</RelativeLayout>

MySQL CONCAT returns NULL if any field contain NULL

you can use if statement like below

select CONCAT(if(affiliate_name is null ,'',affiliate_name),'- ',if(model is null ,'',affiliate_name)) as model from devices

Regular expression to extract URL from an HTML link

Yes, there are tons of them on regexlib. That only proves that RE's should not be used to do that. Use SGMLParser or BeautifulSoup or write a parser - but don't use RE's. The ones that seems to work are extremely compliated and still don't cover all cases.

How do I catch an Ajax query post error?

jQuery 1.5 added deferred objects that handle this nicely. Simply call $.post and attach any handlers you'd like after the call. Deferred objects even allow you to attach multiple success and error handlers.

Example:

$.post('status.ajax.php', {deviceId: id})
    .done( function(msg) { ... } )
    .fail( function(xhr, textStatus, errorThrown) {
        alert(xhr.responseText);
    });

Prior to jQuery 1.8, the function done was called success and fail was called error.

How do I find which process is leaking memory?

As suggeseted, the way to go is valgrind. It's a profiler that checks many aspects of the running performance of your application, including the usage of memory.

Running your application through Valgrind will allow you to verify if you forget to release memory allocated with malloc, if you free the same memory twice etc.

Using Mockito to stub and execute methods for testing

So, the idea of mocking the class under test is anathima to testing practice. You should NOT do this. Because you have done so, your test is entering Mockito's mocking classes not your class under test.

Spying will also not work because this only provides a wrapper / proxy around the spied class. Once execution is inside the class it will not go through the proxy and therefore not hit the spy. UPDATE: although I believe this to be true of Spring proxies it appears to not be true of Mockito spies. I set up a scenario where method m1() calls m2(). I spy the object and stub m2() to doNothing. When I invoke m1() in my test, m2() of the class is not reached. Mockito invokes the stub. So using a spy to accomplish what is being asked is possible. However, I would reiterate that I would consider it bad practice (IMHO).

You should mock all the classes on which the class under test depends. This will allow you to control the behavior of the methods invoked by the method under test in that you control the class that those methods invoke.

If your class creates instances of other classes, consider using factories.

How to enable SOAP on CentOS

The yum install php-soap command will install the Soap module for php 5.x

For installing the correct version for your environment I recommend to create a file info.php and put this code: <?php echo phpinfo(); ?>

In the header you'll see the version you're using:

enter image description here

Now that you know the correct version you can run this command: yum search php-soap

This command will return the avaliable versions:

php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php54-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php55-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php56-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php70-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php71-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php72-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php73-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php74-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php70-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php71-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php72-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol

Now you just need to choose the correct module to your php version.

For this example, you should run this command php72-php-soap.x86_64

How can I dynamically add items to a Java array?

In Java size of array is fixed , but you can add elements dynamically to a fixed sized array using its index and for loop. Please find example below.

package simplejava;

import java.util.Arrays;

/**
 *
 * @author sashant
 */
public class SimpleJava {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        try{
            String[] transactions;
            transactions = new String[10];

            for(int i = 0; i < transactions.length; i++){
                transactions[i] = "transaction - "+Integer.toString(i);            
            }

            System.out.println(Arrays.toString(transactions));

        }catch(Exception exc){
            System.out.println(exc.getMessage());
            System.out.println(Arrays.toString(exc.getStackTrace()));
        }
    }

}

How to write an async method with out parameter?

I had the same problem as I like using the Try-method-pattern which basically seems to be incompatible to the async-await-paradigm...

Important to me is that I can call the Try-method within a single if-clause and do not have to pre-define the out-variables before, but can do it in-line like in the following example:

if (TryReceive(out string msg))
{
    // use msg
}

So I came up with the following solution:

  1. Define a helper struct:

     public struct AsyncOut<T, OUT>
     {
         private readonly T returnValue;
         private readonly OUT result;
    
         public AsyncOut(T returnValue, OUT result)
         {
             this.returnValue = returnValue;
             this.result = result;
         }
    
         public T Out(out OUT result)
         {
             result = this.result;
             return returnValue;
         }
    
         public T ReturnValue => returnValue;
    
         public static implicit operator AsyncOut<T, OUT>((T returnValue ,OUT result) tuple) => 
             new AsyncOut<T, OUT>(tuple.returnValue, tuple.result);
     }
    
  2. Define async Try-method like this:

     public async Task<AsyncOut<bool, string>> TryReceiveAsync()
     {
         string message;
         bool success;
         // ...
         return (success, message);
     }
    
  3. Call the async Try-method like this:

     if ((await TryReceiveAsync()).Out(out string msg))
     {
         // use msg
     }
    

For multiple out parameters you can define additional structs (e.g. AsyncOut<T,OUT1, OUT2>) or you can return a tuple.

How can I set the PATH variable for javac so I can manually compile my .java works?

Trying this out on Windows 10, none of the command-line instructions worked.

Right clicking on "Computer" then open Properties etc. as the post by Galen Nare above already explains, leads you to a window where you need to click on "new" and then paste the path (as said: without deleting anything else). Afterwards you can check by typing java -version in the command-line window, which should display your current java version, if everything worked out right.

cannot be cast to java.lang.Comparable

I faced a similar kind of issue while using a custom object as a key in Treemap. Whenever you are using a custom object as a key in hashmap then you override two function equals and hashcode, However if you are using ContainsKey method of Treemap on this object then you need to override CompareTo method as well otherwise you will be getting this error Someone using a custom object as a key in hashmap in kotlin should do like following

 data class CustomObjectKey(var key1:String = "" , var 
 key2:String = ""):Comparable<CustomObjectKey?>
 {
override fun compareTo(other: CustomObjectKey?): Int {
    if(other == null)
        return -1
   // suppose you want to do comparison based on key 1 
    return this.key1.compareTo((other)key1)
}

override fun equals(other: Any?): Boolean {
    if(other == null)
        return false
    return this.key1 == (other as CustomObjectKey).key1
}

override fun hashCode(): Int {
    return this.key1.hashCode()
} 
}

How to randomize (shuffle) a JavaScript array?

You can do it easily with map and sort:

let unshuffled = ['hello', 'a', 't', 'q', 1, 2, 3, {cats: true}]

let shuffled = unshuffled
  .map((a) => ({sort: Math.random(), value: a}))
  .sort((a, b) => a.sort - b.sort)
  .map((a) => a.value)
  1. We put each element in the array in an object, and give it a random sort key
  2. We sort using the random key
  3. We unmap to get the original objects

You can shuffle polymorphic arrays, and the sort is as random as Math.random, which is good enough for most purposes.

Since the elements are sorted against consistent keys that are not regenerated each iteration, and each comparison pulls from the same distribution, any non-randomness in the distribution of Math.random is canceled out.

Speed

Time complexity is O(N log N), same as quick sort. Space complexity is O(N). This is not as efficient as a Fischer Yates shuffle but, in my opinion, the code is significantly shorter and more functional. If you have a large array you should certainly use Fischer Yates. If you have a small array with a few hundred items, you might do this.

Unsupported major.minor version 52.0 when rendering in Android Studio

This is bug in Android Studio. Usually you get error: Unsupported major.minor version 52.0

WORKAROUND: If you have installed Android N, change Android rendering version with older one and the problem will disappear.

SOLUTION: Install Android SDK Tools 25.1.3 (tools) or higher

enter image description here

Hide HTML element by id

you can use CSS selectors

a[href="/questions/ask"] { display:none; }

Run Android studio emulator on AMD processor

Windows 10 home version with latest android studio (Nov/2019):

  1. Enable virtualization from BIOS. If you have a laptop, google how to access the BIOS.

  2. Enable via Windows Features: "Windows Hypervisor Platform". Restart. No need for Hyper-V and Win10 Pro.

Done. Open Android Studio, the annoying warning is gone, emulator starts just fine.

Convert NSDate to String in iOS Swift

After allocating DateFormatter you need to give the formatted string then you can convert as string like this way

var date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
let updatedString = formatter.string(from: yourDate!)
print(updatedString)

OutPut

01-Mar-2017

How can I resize an image using Java?

I have developed a solution with the freely available classes ( AnimatedGifEncoder, GifDecoder, and LWZEncoder) available for handling GIF Animation.
You can download the jgifcode jar and run the GifImageUtil class. Link: http://www.jgifcode.com