Programs & Examples On #Django signals

Django signals allow listeners to be registered for events within the framework. This allows decoupled handling of, for example, model deletions.

Render HTML string as real HTML in a React component

You can also use parseReactHTMLComponent from Jumper Package. Just look at it, it's easy and you don't need to use JSX syntax.

https://codesandbox.io/s/jumper-module-react-simple-parser-3b8c9?file=/src/App.js .

More on Jumper:

https://github.com/Grano22/jumper/blob/master/components.js

NPM Package:

https://www.npmjs.com/package/jumper_react

C compiling - "undefined reference to"?

Make sure your declare the tolayer5 function as a prototype, or define the full function definition, earlier in the file where you use it.

What does enumerate() mean?

The enumerate function works as follows:

doc = """I like movie. But I don't like the cast. The story is very nice"""
doc1 = doc.split('.')
for i in enumerate(doc1):
     print(i)

The output is

(0, 'I like movie')
(1, " But I don't like the cast")
(2, ' The story is very nice')

Using ffmpeg to change framerate

You may consider using fps filter. It won't change the video playback speed:

ffmpeg -i <input> -filter:v fps=fps=30 <output>

Worked nice for reducing fps from 59.6 to 30.

How to get `DOM Element` in Angular 2?

Angular 2.0.0 Final:

I have found that using a ViewChild setter is most reliable way to set the initial form control focus:

@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
    if (_input !== undefined) {
        setTimeout(() => {
            this._renderer.invokeElementMethod(_input.nativeElement, "focus");
        }, 0);
    }
}

The setter is first called with an undefined value followed by a call with an initialized ElementRef.

Working example and full source here: http://plnkr.co/edit/u0sLLi?p=preview

Using TypeScript 2.0.3 Final/RTM, Angular 2.0.0 Final/RTM, and Chrome 53.0.2785.116 m (64-bit).

UPDATE for Angular 4+

Renderer has been deprecated in favor of Renderer2, but Renderer2 does not have the invokeElementMethod. You will need to access the DOM directly to set the focus as in input.nativeElement.focus().

I'm still finding that the ViewChild setter approach works best. When using AfterViewInit I sometimes get read property 'nativeElement' of undefined error.

@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
    if (_input !== undefined) {
        setTimeout(() => { //This setTimeout call may not be necessary anymore.
            _input.nativeElement.focus();
        }, 0);
    }
}

Calculate age based on date of birth

$getyear = explode("-", $value['users_dob']);
$dob = date('Y') - $getyear[0];

$value['users_dob'] is the database value with format yyyy-mm-dd

Homebrew: Could not symlink, /usr/local/bin is not writable

For those that are not familiar:

sudo chown -R YOUR_COMPUTER_USER_NAME PATH_OF_FILE

How to change the background-color of jumbrotron?

The easiest way to change the background color of the jumbotron

If you want to change the background color of your jumbotron, then for that you can apply a background color to it using one of your custom class.

HTML Code:

<div class="jumbotron myclass">   
    <h1>My Heading</h1>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
</div> 

CSS Code:

<style>
    .myclass{
        background-color: red;
    }
</style>

How do you subtract Dates in Java?

If you deal with dates it is a good idea to look at the joda time library for a more sane Date manipulation model.

http://joda-time.sourceforge.net/

How To Raise Property Changed events on a Dependency Property?

I think the OP is asking the wrong question. The code below will show that it not necessary to manually raise the PropertyChanged EVENT from a dependency property to achieve the desired result. The way to do it is handle the PropertyChanged CALLBACK on the dependency property and set values for other dependency properties there. The following is a working example. In the code below, MyControl has two dependency properties - ActiveTabInt and ActiveTabString. When the user clicks the button on the host (MainWindow), ActiveTabString is modified. The PropertyChanged CALLBACK on the dependency property sets the value of ActiveTabInt. The PropertyChanged EVENT is not manually raised by MyControl.

MainWindow.xaml.cs

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        ActiveTabString = "zero";
    }

    private string _ActiveTabString;
    public string ActiveTabString
    {
        get { return _ActiveTabString; }
        set
        {
            if (_ActiveTabString != value)
            {
                _ActiveTabString = value;
                RaisePropertyChanged("ActiveTabString");
            }
        }
    }

    private int _ActiveTabInt;
    public int ActiveTabInt
    {
        get { return _ActiveTabInt; }
        set
        {
            if (_ActiveTabInt != value)
            {
                _ActiveTabInt = value;
                RaisePropertyChanged("ActiveTabInt");
            }
        }
    }

    #region INotifyPropertyChanged implementation
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        ActiveTabString = (ActiveTabString == "zero") ? "one" : "zero";
    }

}

public class MyControl : Control
{
    public static List<string> Indexmap = new List<string>(new string[] { "zero", "one" });


    public string ActiveTabString
    {
        get { return (string)GetValue(ActiveTabStringProperty); }
        set { SetValue(ActiveTabStringProperty, value); }
    }

    public static readonly DependencyProperty ActiveTabStringProperty = DependencyProperty.Register(
        "ActiveTabString",
        typeof(string),
        typeof(MyControl), new FrameworkPropertyMetadata(
            null,
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            ActiveTabStringChanged));


    public int ActiveTabInt
    {
        get { return (int)GetValue(ActiveTabIntProperty); }
        set { SetValue(ActiveTabIntProperty, value); }
    }
    public static readonly DependencyProperty ActiveTabIntProperty = DependencyProperty.Register(
        "ActiveTabInt",
        typeof(Int32),
        typeof(MyControl), new FrameworkPropertyMetadata(
            new Int32(),
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));


    static MyControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));

    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
    }


    private static void ActiveTabStringChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        MyControl thiscontrol = sender as MyControl;

        if (Indexmap[thiscontrol.ActiveTabInt] != thiscontrol.ActiveTabString)
            thiscontrol.ActiveTabInt = Indexmap.IndexOf(e.NewValue.ToString());

    }
}

MainWindow.xaml

    <StackPanel Orientation="Vertical">
    <Button Content="Change Tab Index" Click="Button_Click" Width="110" Height="30"></Button>
    <local:MyControl x:Name="myControl" ActiveTabInt="{Binding ActiveTabInt, Mode=TwoWay}" ActiveTabString="{Binding ActiveTabString}"></local:MyControl>
</StackPanel>

App.xaml

<Style TargetType="local:MyControl">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:MyControl">
                    <TabControl SelectedIndex="{Binding ActiveTabInt, Mode=TwoWay}">
                        <TabItem Header="Tab Zero">
                            <TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
                        </TabItem>
                        <TabItem Header="Tab One">
                            <TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
                        </TabItem>
                    </TabControl>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Is it possible to set an object to null?

You can set any pointer to NULL, though NULL is simply defined as 0 in C++:

myObject *foo = NULL;

Also note that NULL is defined if you include standard headers, but is not built into the language itself. If NULL is undefined, you can use 0 instead, or include this:

#ifndef NULL
#define NULL 0
#endif

As an aside, if you really want to set an object, not a pointer, to NULL, you can read about the Null Object Pattern.

Cannot add or update a child row: a foreign key constraint fails

If you use mysql index or relation between tables, firstly you delete the colums(for example:city_id) and create new colums with same name(for example:city_id).Then try again...

return, return None, and no return at all?

As other have answered, the result is exactly the same, None is returned in all cases.

The difference is stylistic, but please note that PEP8 requires the use to be consistent:

Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable).

Yes:

def foo(x):
    if x >= 0:
        return math.sqrt(x)
    else:
        return None

def bar(x):
    if x < 0:
        return None
    return math.sqrt(x)

No:

def foo(x):
    if x >= 0:
        return math.sqrt(x)

def bar(x):
    if x < 0:
        return
    return math.sqrt(x)

https://www.python.org/dev/peps/pep-0008/#programming-recommendations


Basically, if you ever return non-None value in a function, it means the return value has meaning and is meant to be caught by callers. So when you return None, it must also be explicit, to convey None in this case has meaning, it is one of the possible return values.

If you don't need return at all, you function basically works as a procedure instead of a function, so just don't include the return statement.

If you are writing a procedure-like function and there is an opportunity to return earlier (i.e. you are already done at that point and don't need to execute the remaining of the function) you may use empty an returns to signal for the reader it is just an early finish of execution and the None value returned implicitly doesn't have any meaning and is not meant to be caught (the procedure-like function always returns None anyway).

ERROR 2003 (HY000): Can't connect to MySQL server (111)

errno 111 is ECONNREFUSED, I suppose something is wrong with the router's DNAT.

It is also possible that your ISP is filtering that port.

Change the URL in the browser without loading the new page using JavaScript

If you want it to work in browsers that don't support history.pushState and history.popState yet, the "old" way is to set the fragment identifier, which won't cause a page reload.

The basic idea is to set the window.location.hash property to a value that contains whatever state information you need, then either use the window.onhashchange event, or for older browsers that don't support onhashchange (IE < 8, Firefox < 3.6), periodically check to see if the hash has changed (using setInterval for example) and update the page. You will also need to check the hash value on page load to set up the initial content.

If you're using jQuery there's a hashchange plugin that will use whichever method the browser supports. I'm sure there are plugins for other libraries as well.

One thing to be careful of is colliding with ids on the page, because the browser will scroll to any element with a matching id.

What is an "index out of range" exception, and how do I fix it?

Why does this error occur?

Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.

The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

var firstElement = array[0];
var lastElement = array[5];

So when you write:

var element = array[5];

you are retrieving the sixth element in the array, not the fifth one.

Typically, you would loop over an array like this:

for (int index = 0; index < array.Length; index++)
{
    Console.WriteLine(array[index]);
}

This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.

This, however, will throw an exception:

for (int index = 0; index <= array.Length; index++)
{
    Console.WriteLine(array[index]);
}

Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.

How other collections work

Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.

for (int index = 0; i < list.Count; index++)
{
    Console.WriteLine(list[index]);
} 

However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:

foreach (var element in list)
{
    Console.WriteLine(element.ToString());
}

You cannot index an element that hasn't been added to a collection yet.

var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]);  // Throws exception.

Copy map values to vector in STL

#include <algorithm> // std::transform
#include <iterator>  // std::back_inserter
std::transform( 
    your_map.begin(), 
    your_map.end(),
    std::back_inserter(your_values_vector),
    [](auto &kv){ return kv.second;} 
);

Sorry that I didn't add any explanation - I thought that code is so simple that is doesn't require any explanation. So:

transform( beginInputRange, endInputRange, outputIterator, unaryOperation)

this function calls unaryOperation on every item from inputIterator range (beginInputRange-endInputRange). The value of operation is stored into outputIterator.

If we want to operate through whole map - we use map.begin() and map.end() as our input range. We want to store our map values into vector - so we have to use back_inserter on our vector: back_inserter(your_values_vector). The back_inserter is special outputIterator that pushes new elements at the end of given (as paremeter) collection. The last parameter is unaryOperation - it takes only one parameter - inputIterator's value. So we can use lambda: [](auto &kv) { [...] }, where &kv is just a reference to map item's pair. So if we want to return only values of map's items we can simply return kv.second:

[](auto &kv) { return kv.second; }

I think this explains any doubts.

JQuery .each() backwards

You can do

jQuery.fn.reverse = function() {
    return this.pushStack(this.get().reverse(), arguments);
}; 

followed by

$(selector).reverse().each(...) 

How to read PDF files using Java?

PDFBox is the best library I've found for this purpose, it's comprehensive and really quite easy to use if you're just doing basic text extraction. Examples can be found here.

It explains it on the page, but one thing to watch out for is that the start and end indexes when using setStartPage() and setEndPage() are both inclusive. I skipped over that explanation first time round and then it took me a while to realise why I was getting more than one page back with each call!

Itext is another alternative that also works with C#, though I've personally never used it. It's more low level than PDFBox, so less suited to the job if all you need is basic text extraction.

Regular expression to detect semi-colon terminated C++ for & while loops

This is the kind of thing you really shouldn't do with a regular expression. Just parse the string one character at a time, keeping track of opening/closing parentheses.

If this is all you're looking for, you definitely don't need a full-blown C++ grammar lexer/parser. If you want practice, you can write a little recursive-decent parser, but even that's a bit much for just matching parentheses.

jQuery - selecting elements from inside a element

....but $('span', $('#foo')); doesn't work?

This method is called as providing selector context.

In this you provide a second argument to the jQuery selector. It can be any css object string just like you would pass for direct selecting or a jQuery element.

eg.

$("span",".cont1").css("background", '#F00');

The above line will select all spans within the container having the class named cont1.

DEMO

Correct use for angular-translate in controllers

What is happening is that Angular-translate is watching the expression with an event-based system, and just as in any other case of binding or two-way binding, an event is fired when the data is retrieved, and the value changed, which obviously doesn't work for translation. Translation data, unlike other dynamic data on the page, must, of course, show up immediately to the user. It can't pop in after the page loads.

Even if you can successfully debug this issue, the bigger problem is that the development work involved is huge. A developer has to manually extract every string on the site, put it in a .json file, manually reference it by string code (ie 'pageTitle' in this case). Most commercial sites have thousands of strings for which this needs to happen. And that is just the beginning. You now need a system of keeping the translations in synch when the underlying text changes in some of them, a system for sending the translation files out to the various translators, of reintegrating them into the build, of redeploying the site so the translators can see their changes in context, and on and on.

Also, as this is a 'binding', event-based system, an event is being fired for every single string on the page, which not only is a slower way to transform the page but can slow down all the actions on the page, if you start adding large numbers of events to it.

Anyway, using a post-processing translation platform makes more sense to me. Using GlobalizeIt for example, a translator can just go to a page on the site and start editing the text directly on the page for their language, and that's it: https://www.globalizeit.com/HowItWorks. No programming needed (though it can be programmatically extensible), it integrates easily with Angular: https://www.globalizeit.com/Translate/Angular, the transformation of the page happens in one go, and it always displays the translated text with the initial render of the page.

Full disclosure: I'm a co-founder :)

How to get Javascript Select box's selected text

this.options[this.selectedIndex].innerHTML

should provide you with the "displayed" text of the selected item. this.value, like you said, merely provides the value of the value attribute.

Wait some seconds without blocking UI execution

i really disadvise you against using Thread.Sleep(2000), because of a several reasons (a few are described here), but most of all because its not useful when it comes to debugging/testing.

I recommend to use a C# Timer instead of Thread.Sleep(). Timers let you perform methods frequently (if necessary) AND are much easiert to use in testing! There's a very nice example of how to use a timer right behind the hyperlink - just put your logic "what happens after 2 seconds" right into the Timer.Elapsed += new ElapsedEventHandler(OnTimedEvent); method.

Creating a button in Android Toolbar

ToolBar with Button Tutorial

1 - Add library compatibility inside build.gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
}

2 - Create a file name color.xml to define the Toolbar colors

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="ColorPrimary">#FF5722</color>
    <color name="ColorPrimaryDark">#E64A19</color>
</resources>

3 - Modify your style.xml file

<resources>     
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

        <item name="colorPrimary">@color/ColorPrimary</item>
        <item name="colorPrimaryDark">@color/ColorPrimaryDark</item>
        <!-- Customize your theme here. -->
    </style>     
</resources>

4 - Create a xml file like tool_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
 xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"
    android:elevation="4dp" />

5 - Include the Toolbar into your main_activity.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"
    tools:context=".MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar" />

    <TextView
        android:layout_below="@+id/tool_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/TextDimTop"
        android:text="@string/hello_world" />

</RelativeLayout>

6 - Then, put it inside your MainActivity class

package com.example.hp1.materialtoolbar;

import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

/* When using AppCompat support library                                                             
 * (you need to extend Main Activity to                                                            
 * ActionBarActivity)
 * ActionBarActivity has deprecated, use AppCompatActivity
 */
public class MainActivity extends ActionBarActivity { 
    // Declaring the Toolbar Object
    private Toolbar toolbar;

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

        // Attaching the layout to the toolbar object
        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        // Setting toolbar as the ActionBar with setSupportActionBar() call
        setSupportActionBar(toolbar);
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

7 - And finally, add your "Button Items" to the menu_main.xml inside of /res/menu/ directory

<?xml version="1.0" encoding="utf-8"?>
   <menu
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        tools:context=".MainActivity">
        <item
            android:id="@+id/action_settings"
            android:orderInCategory="100"
            android:title="@string/action_settings"
            app:showAsAction="never" />
        <item
            android:id="@+id/action_search"
            android:orderInCategory="200"
            android:title="Search"
            android:icon="@drawable/ic_search"
            app:showAsAction="ifRoom"/>                
        <item
            android:id="@+id/action_user"
            android:orderInCategory="300"
            android:title="User"
            android:icon="@drawable/ic_user"
            app:showAsAction="ifRoom" />        
    </menu>

When to use Hadoop, HBase, Hive and Pig?

Hadoop is a a framework that allows for the distributed processing of large data sets across clusters of computers using simple programming models.

There are four main modules in Hadoop.

  1. Hadoop Common: The common utilities that support the other Hadoop modules.

  2. Hadoop Distributed File System (HDFS™): A distributed file system that provides high-throughput access to application data.

  3. Hadoop YARN: A framework for job scheduling and cluster resource management.

  4. Hadoop MapReduce: A YARN-based system for parallel processing of large data sets.

Before going further, Let's note that we have three different types of data.

  • Structured: Structured data has strong schema and schema will be checked during write & read operation. e.g. Data in RDBMS systems like Oracle, MySQL Server etc.

  • Unstructured: Data does not have any structure and it can be any form - Web server logs, E-Mail, Images etc.

  • Semi-structured: Data is not strictly structured but have some structure. e.g. XML files.

Depending on type of data to be processed, we have to choose right technology.

Some more projects, which are part of Hadoop:

  • HBase™: A scalable, distributed database that supports structured data storage for large tables.

  • Hive™: A data warehouse infrastructure that provides data summarization and ad-hoc querying.

  • Pig™: A high-level data-flow language and execution framework for parallel computation.

Hive Vs PIG comparison can be found at this article and my other post at this SE question.

HBASE won't replace Map Reduce. HBase is scalable distributed database & Map Reduce is programming model for distributed processing of data. Map Reduce may act on data in HBASE in processing.

You can use HIVE/HBASE for structured/semi-structured data and process it with Hadoop Map Reduce

You can use SQOOP to import structured data from traditional RDBMS database Oracle, SQL Server etc and process it with Hadoop Map Reduce

You can use FLUME for processing Un-structured data and process with Hadoop Map Reduce

Have a look at: Hadoop Use Cases.

Hive should be used for analytical querying of data collected over a period of time. e.g Calculate trends, summarize website logs but it can't be used for real time queries.

HBase fits for real-time querying of Big Data. Facebook use it for messaging and real-time analytics.

PIG can be used to construct dataflows, run a scheduled jobs, crunch big volumes of data, aggregate/summarize it and store into relation database systems. Good for ad-hoc analysis.

Hive can be used for ad-hoc data analysis but it can't support all un-structured data formats unlike PIG.

how to get the last character of a string?

You can achieve this using different ways but with different performance,

1. Using bracket notation:

var str = "Test"; var lastLetter = str[str.length - 1];

But it's not recommended to use brackets. Check the reasons here

2. charAt[index]:

var lastLetter = str.charAt(str.length - 1)

This is readable and fastest among others. It is most recommended way.

3. substring:

str.substring(str.length - 1);

4. slice:

str.slice(-1);

It's slightly faster than substring.

You can check the performance here

With ES6:

You can use str.endsWith("t");

But it is not supported in IE. Check more details about endsWith here

How to transition to a new view controller with code only using Swift

This worked perfectly for me:

func switchScreen() {
    let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
    if let viewController = mainStoryboard.instantiateViewController(withIdentifier: "yourVcName") as? UIViewController {
        self.present(viewController, animated: true, completion: nil)
    }
}

How do I use $scope.$watch and $scope.$apply in AngularJS?

There are $watchGroup and $watchCollection as well. Specifically, $watchGroup is really helpful if you want to call a function to update an object which has multiple properties in a view that is not dom object, for e.g. another view in canvas, WebGL or server request.

Here, the documentation link.

Choosing a jQuery datagrid plugin?

A good plugin that I have used before is DataTables.

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

You can use the following methods to specify C:\Program Files without a space in it for programs that can't handle spaces in file paths:

'Path to Continuum Reports Subdirectory - Note use DOS equivalent (no spaces)
RepPath = "c:\progra~1\continuum_reports\" or
RepPath = C:\Program Files\Continuum_Reports  'si es para 64 bits.

' Path to Continuum Reports Subdirectory - Note use DOS equivalent (no spaces)
RepPath = "c:\progra~2\continuum_reports\" 'or
RepPath = C:\Program Files (x86)\Continuum_Reports  'si es para 32 bits.

Add numpy array as column to Pandas data frame

import numpy as np
import pandas as pd
import scipy.sparse as sparse

df = pd.DataFrame(np.arange(1,10).reshape(3,3))
arr = sparse.coo_matrix(([1,1,1], ([0,1,2], [1,2,0])), shape=(3,3))
df['newcol'] = arr.toarray().tolist()
print(df)

yields

   0  1  2     newcol
0  1  2  3  [0, 1, 0]
1  4  5  6  [0, 0, 1]
2  7  8  9  [1, 0, 0]

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

If you want to understand AutoResetEvent and ManualResetEvent you need to understand not threading but interrupts!

.NET wants to conjure up low-level programming the most distant possible.

An interrupts is something used in low-level programming which equals to a signal that from low became high (or viceversa). When this happens the program interrupt its normal execution and move the execution pointer to the function that handles this event.

The first thing to do when an interrupt happend is to reset its state, becosa the hardware works in this way:

  1. a pin is connected to a signal and the hardware listen for it to change (the signal could have only two states).
  2. if the signal changes means that something happened and the hardware put a memory variable to the state happened (and it remain like this even if the signal change again).
  3. the program notice that variable change states and move the execution to a handling function.
  4. here the first thing to do, to be able to listen again this interrupt, is to reset this memory variable to the state not-happened.

This is the difference between ManualResetEvent and AutoResetEvent.
If a ManualResetEvent happen and I do not reset it, the next time it happens I will not be able to listen it.

Is it possible to get the current spark context settings in PySpark?

I would suggest you try the method below in order to get the current spark context settings.

SparkConf.getAll()

as accessed by

SparkContext.sc._conf

Get the default configurations specifically for Spark 2.1+

spark.sparkContext.getConf().getAll() 

Stop the current Spark Session

spark.sparkContext.stop()

Create a Spark Session

spark = SparkSession.builder.config(conf=conf).getOrCreate()

angularjs: ng-src equivalent for background-image:url(...)

Similar to hooblei's answer, just with interpolation:

<li ng-style="{'background-image': 'url({{ image.source }})'}">...</li>

document.getElementById vs jQuery $()

Just like most people have said, the main difference is the fact that it is wrapped in a jQuery object with the jQuery call vs the raw DOM object using straight JavaScript. The jQuery object will be able to do other jQuery functions with it of course but, if you just need to do simple DOM manipulation like basic styling or basic event handling, the straight JavaScript method is always a tad bit faster than jQuery since you don't have to load in an external library of code built on JavaScript. It saves an extra step.

Python module for converting PDF to text

PDFminer gave me perhaps one line [page 1 of 7...] on every page of a pdf file I tried with it.

The best answer I have so far is pdftoipe, or the c++ code it's based on Xpdf.

see my question for what the output of pdftoipe looks like.

How to log a method's execution time exactly in milliseconds?

I use this:

clock_t start, end;
double elapsed;
start = clock();

//Start code to time

//End code to time

end = clock();
elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;
NSLog(@"Time: %f",elapsed);

But I'm not sure about CLOCKS_PER_SEC on the iPhone. You might want to leave it off.

How to set JVM parameters for Junit Unit Tests?

I agree with the others who said that there is no simple way to distribute these settings.

For Eclipse: ask your colleagues to set the following:

  • Windows Preferences / Java / Installed JREs:
  • Select the proper JRE/JDK (or do it for all of them)
  • Edit
  • Default VM arguments: -Xmx1024m
  • Finish, OK.

After that all test will run with -Xmx1024m but unfortunately you have set it in every Eclipse installation. Maybe you could create a custom Eclipse package which contains this setting and give it to you co-workers.

The following working process also could help: If the IDE cannot run a test the developer should check that Maven could run this test or not.

  • If Maven could run it the cause of the failure usually is the settings of the developer's IDE. The developer should check these settings.
  • If Maven also could not run the test the developer knows that the cause of the failure is not the IDE, so he/she could use the IDE to debug the test.

HTML for the Pause symbol in audio and video control

The ISO 7000 / IEC 60417 Symbol for Pause; Interruption is #5111B. See Media_Controls

Java Program to test if a character is uppercase/lowercase/number/vowel

Some comments on your code

  • why would you want to have 2 for loops like for(i='A';i<='Z';i++), if you can check this with a simple if statement ... you loop over a whole range while you can simply check whether it is contained in that range
  • even when you found your answer (for example when input is A you will have your result the first time you enter the first loop) you still loop over all the rest
  • your System.out.println("Lowercase"); statement (and the uppercase statement) are placed in the wrong loop
  • If you are allowed to use it, I suggest to look at the Character class which has for example nice isUpperCase and isLowerCase methods

I leave the rest up to you since it is homework

When should I use double or single quotes in JavaScript?

I think it's important not to forget that while Internet Explorer might have zero extensions/toolbars installed, Firefox might have some extensions installed (I'm just thinking of Firebug for instance). Those extensions will have an influence on the benchmark result.

Not that it really matters since browser X is faster in getting elementstyles, while browser Y might be faster in rendering a canvas element (hence why a browser "manufacturer" always has the fastest JavaScript engine).

How to get the changes on a branch in Git

With Git 2.30 (Q1 2021), "git diff A...B(man)" learned "git diff --merge-base A B(man), which is a longer short-hand to say the same thing.

Thus you can do this using git diff --merge-base <branch> HEAD. This should be equivalent to git diff <branch>...HEAD but without the confusion of having to use range-notation in a diff.

CKEditor instance already exists

I chose to rename all instances instead of destroy/replace - since sometimes the AJAX loaded instance doesn't really replace the one on the core of the page... keeps more in RAM, but less conflict this way.

    if (CKEDITOR && CKEDITOR.instances) {
        for (var oldName in CKEDITOR.instances) {
            var newName = "ajax"+oldName;
            CKEDITOR.instances[newName] = CKEDITOR.instances[oldName];
            CKEDITOR.instances[newName].name = newName;
            delete CKEDITOR.instances[oldName];
        }
    }

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

It can be due to a number of reasons happening when configuring the listener. Best way is to log and see the actual error. You can do this by adding a logging.properties file to the root of your classpath with the following contents:

org.apache.catalina.core.ContainerBase.[Catalina].level = INFO org.apache.catalina.core.ContainerBase.[Catalina].handlers = java.util.logging.ConsoleHandler

How to clear the canvas for redrawing

the shortest way:

canvas.width += 0

Align an element to bottom with flexbox

When setting your display to flex, you could simply use the flex property to mark which content can grow and which content cannot.

Flex property

_x000D_
_x000D_
div.content {_x000D_
 height: 300px;_x000D_
 display: flex;_x000D_
 flex-direction: column;_x000D_
}_x000D_
_x000D_
div.up {_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
div.down {_x000D_
  flex: none;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="up">_x000D_
    <h1>heading 1</h1>_x000D_
    <h2>heading 2</h2>_x000D_
    <p>Some more or less text</p>_x000D_
  </div>_x000D_
_x000D_
  <div class="down">_x000D_
    <a href="/" class="button">Click me</a>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Get the last element of a std::string

*(myString.end() - 1) maybe? That's not exactly elegant either.

A python-esque myString.at(-1) would be asking too much of an already-bloated class.

How should I unit test multithreaded code?

I spent most of last week at a university library studying debugging of concurrent code. The central problem is concurrent code is non-deterministic. Typically, academic debugging has fallen into one of three camps here:

  1. Event-trace/replay. This requires an event monitor and then reviewing the events that were sent. In a UT framework, this would involve manually sending the events as part of a test, and then doing post-mortem reviews.
  2. Scriptable. This is where you interact with the running code with a set of triggers. "On x > foo, baz()". This could be interpreted into a UT framework where you have a run-time system triggering a given test on a certain condition.
  3. Interactive. This obviously won't work in an automatic testing situation. ;)

Now, as above commentators have noticed, you can design your concurrent system into a more deterministic state. However, if you don't do that properly, you're just back to designing a sequential system again.

My suggestion would be to focus on having a very strict design protocol about what gets threaded and what doesn't get threaded. If you constrain your interface so that there is minimal dependancies between elements, it is much easier.

Good luck, and keep working on the problem.

Tool for sending multipart/form-data request

UPDATE: I have created a video on sending multipart/form-data requests to explain this better.


Actually, Postman can do this. Here is a screenshot

Newer version : Screenshot captured from postman chrome extension enter image description here

Another version

enter image description here

Older version

enter image description here

Make sure you check the comment from @maxkoryukov

Be careful with explicit Content-Type header. Better - do not set it's value, the Postman is smart enough to fill this header for you. BUT, if you want to set the Content-Type: multipart/form-data - do not forget about boundary field.

Spring Boot, Spring Data JPA with multiple DataSources

There is another way to have multiple dataSources by using @EnableAutoConfiguration and application.properties.

Basically put multiple dataSource configuration info on application.properties and generate default setup (dataSource and entityManagerFactory) automatically for first dataSource by @EnableAutoConfiguration. But for next dataSource, create dataSource, entityManagerFactory and transactionManager all manually by the info from property file.

Below is my example to setup two dataSources. First dataSource is setup by @EnableAutoConfiguration which can be assigned only for one configuration, not multiple. And that will generate 'transactionManager' by DataSourceTransactionManager, that looks default transactionManager generated by the annotation. However I have seen the transaction not beginning issue on the thread from scheduled thread pool only for the default DataSourceTransactionManager and also when there are multiple transaction managers. So I create transactionManager manually by JpaTransactionManager also for the first dataSource with assigning 'transactionManager' bean name and default entityManagerFactory. That JpaTransactionManager for first dataSource surely resolves the weird transaction issue on the thread from ScheduledThreadPool.

Update for Spring Boot 1.3.0.RELEASE

I found my previous configuration with @EnableAutoConfiguration for default dataSource has issue on finding entityManagerFactory with Spring Boot 1.3 version. Maybe default entityManagerFactory is not generated by @EnableAutoConfiguration, once after I introduce my own transactionManager. So now I create entityManagerFactory by myself. So I don't need to use @EntityScan. So it looks I'm getting more and more out of the setup by @EnableAutoConfiguration.

Second dataSource is setup without @EnableAutoConfiguration and create 'anotherTransactionManager' by manual way.

Since there are multiple transactionManager extends from PlatformTransactionManager, we should specify which transactionManager to use on each @Transactional annotation

Default Repository Config

@Configuration
@EnableTransactionManagement
@EnableAutoConfiguration
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactory",
        transactionManagerRef = "transactionManager",
        basePackages = {"com.mysource.repository"})
public class RepositoryConfig {
    @Autowired
    JpaVendorAdapter jpaVendorAdapter;

    @Autowired
    DataSource dataSource;

    @Bean(name = "entityManager")
    public EntityManager entityManager() {
        return entityManagerFactory().createEntityManager();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public EntityManagerFactory entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(dataSource);
        emf.setJpaVendorAdapter(jpaVendorAdapter);
        emf.setPackagesToScan("com.mysource.model");
        emf.setPersistenceUnitName("default");   // <- giving 'default' as name
        emf.afterPropertiesSet();
        return emf.getObject();
    }

    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(entityManagerFactory());
        return tm;
    }
}

Another Repository Config

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "anotherEntityManagerFactory",
        transactionManagerRef = "anotherTransactionManager",
        basePackages = {"com.mysource.anothersource.repository"})
public class AnotherRepositoryConfig {
    @Autowired
    JpaVendorAdapter jpaVendorAdapter;

    @Value("${another.datasource.url}")
    private String databaseUrl;

    @Value("${another.datasource.username}")
    private String username;

    @Value("${another.datasource.password}")
    private String password;

    @Value("${another.dataource.driverClassName}")
    private String driverClassName;

    @Value("${another.datasource.hibernate.dialect}")
    private String dialect;

    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource(databaseUrl, username, password);
        dataSource.setDriverClassName(driverClassName);
        return dataSource;
    }

    @Bean(name = "anotherEntityManager")
    public EntityManager entityManager() {
        return entityManagerFactory().createEntityManager();
    }

    @Bean(name = "anotherEntityManagerFactory")
    public EntityManagerFactory entityManagerFactory() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", dialect);

        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(dataSource());
        emf.setJpaVendorAdapter(jpaVendorAdapter);
        emf.setPackagesToScan("com.mysource.anothersource.model");   // <- package for entities
        emf.setPersistenceUnitName("anotherPersistenceUnit");
        emf.setJpaProperties(properties);
        emf.afterPropertiesSet();
        return emf.getObject();
    }

    @Bean(name = "anotherTransactionManager")
    public PlatformTransactionManager transactionManager() {
        return new JpaTransactionManager(entityManagerFactory());
    }
}

application.properties

# database configuration
spring.datasource.url=jdbc:h2:file:~/main-source;AUTO_SERVER=TRUE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.continueOnError=true
spring.datasource.initialize=false

# another database configuration
another.datasource.url=jdbc:sqlserver://localhost:1433;DatabaseName=another;
another.datasource.username=username
another.datasource.password=
another.datasource.hibernate.dialect=org.hibernate.dialect.SQLServer2008Dialect 
another.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver

Choose proper transactionManager for @Transactional annotation

Service for first datasource

@Service("mainService")
@Transactional("transactionManager")
public class DefaultDataSourceServiceImpl implements DefaultDataSourceService       
{

   //

}

Service for another datasource

@Service("anotherService")
@Transactional("anotherTransactionManager")
public class AnotherDataSourceServiceImpl implements AnotherDataSourceService 
{

   //

}

Sort array of objects by string property value

So here is one sorting algorithm which can sort in any order , throughout array of any kind of objects , without the restriction of datatype comparison ( i.e. Number , String )

function smoothSort(items,prop,reverse) {  
    var length = items.length;
    for (var i = (length - 1); i >= 0; i--) {
        //Number of passes
        for (var j = (length - i); j > 0; j--) {
            //Compare the adjacent positions
            if(reverse){
              if (items[j][prop] > items[j - 1][prop]) {
                //Swap the numbers
                var tmp = items[j];
                items[j] = items[j - 1];
                items[j - 1] = tmp;
            }
            }

            if(!reverse){
              if (items[j][prop] < items[j - 1][prop]) {
                  //Swap the numbers
                  var tmp = items[j];
                  items[j] = items[j - 1];
                  items[j - 1] = tmp;
              }
            }
        }
    }

    return items;
}
  • the first argument items is the array of objects ,

  • prop is the key of the object on which you want to sort ,

  • reverse is a boolean parameter which on being true results in Ascending order and in false it returns descending order.

Redirecting a page using Javascript, like PHP's Header->Location

You cannot mix JS and PHP that way, PHP is rendered before the page is sent to the browser (i.e. before the JS is run)

You can use window.location to change your current page.

$('.entry a:first').click(function() {
    window.location = "http://google.ca";
});

How to create and handle composite primary key in JPA

You can make an Embedded class, which contains your two keys, and then have a reference to that class as EmbeddedId in your Entity.

You would need the @EmbeddedId and @Embeddable annotations.

@Entity
public class YourEntity {
    @EmbeddedId
    private MyKey myKey;

    @Column(name = "ColumnA")
    private String columnA;

    /** Your getters and setters **/
}
@Embeddable
public class MyKey implements Serializable {

    @Column(name = "Id", nullable = false)
    private int id;

    @Column(name = "Version", nullable = false)
    private int version;

    /** getters and setters **/
}

Another way to achieve this task is to use @IdClass annotation, and place both your id in that IdClass. Now you can use normal @Id annotation on both the attributes

@Entity
@IdClass(MyKey.class)
public class YourEntity {
   @Id
   private int id;
   @Id
   private int version;

}

public class MyKey implements Serializable {
   private int id;
   private int version;
}

How do I set the value property in AngularJS' ng-options?

Here is how I solve this problem in a legacy application:

In HTML:

ng-options="kitType.name for kitType in vm.kitTypes track by kitType.id" ng-model="vm.itemTypeId"

In JavaScript:

vm.kitTypes = [
    {"id": "1", "name": "Virtual"},
    {"id": "2", "name": "Physical"},
    {"id": "3", "name": "Hybrid"}
];

...

vm.itemTypeId = vm.kitTypes.filter(function(value, index, array){
    return value.id === (vm.itemTypeId || 1);
})[0];

My HTML displays the option value properly.

Why can't I define a default constructor for a struct in .NET?

You can make a static property that initializes and returns a default "rational" number:

public static Rational One => new Rational(0, 1); 

And use it like:

var rat = Rational.One;

INNER JOIN same table

Lets try to answer this question, with a good and simple scenario, with 3 MySQL tables i.e. datetable, colortable and jointable.

first see values of table datetable with primary key assigned to column dateid:

mysql> select * from datetable;
+--------+------------+
| dateid | datevalue  |
+--------+------------+
|    101 | 2015-01-01 |
|    102 | 2015-05-01 |
|    103 | 2016-01-01 |
+--------+------------+
3 rows in set (0.00 sec)

now move to our second table values colortable with primary key assigned to column colorid:

mysql> select * from colortable;
+---------+------------+
| colorid | colorvalue |
+---------+------------+
|      11 | blue       |
|      12 | yellow     |
+---------+------------+
2 rows in set (0.00 sec)

and our final third table jointable have no primary keys and values are:

mysql> select * from jointable;
+--------+---------+
| dateid | colorid |
+--------+---------+
|    101 |      11 |
|    102 |      12 |
|    101 |      12 |
+--------+---------+
3 rows in set (0.00 sec)

Now our condition is to find the dateid's, which have both color values blue and yellow.

So, our query is:

mysql> SELECT t1.dateid FROM jointable AS t1 INNER JOIN jointable t2
    -> ON t1.dateid = t2.dateid
    -> WHERE
    -> (t1.colorid IN (SELECT colorid FROM colortable WHERE colorvalue = 'blue'))
    -> AND
    -> (t2.colorid IN (SELECT colorid FROM colortable WHERE colorvalue = 'yellow'));
+--------+
| dateid |
+--------+
|    101 |
+--------+
1 row in set (0.00 sec)

Hope, this would help many one.

Improve SQL Server query performance on large tables

Even if you have indexes on some columns that are used in some queries, the fact that your 'ad-hoc' query causes a table scan shows that you don't have sufficient indexes to allow this query to complete efficiently.

For date ranges in particular it is difficult to add good indexes.

Just looking at your query, the db has to sort all the records by the selected column to be able to return the first n records.

Does the db also do a full table scan without the order by clause? Does the table have a primary key - without a PK, the db will have to work harder to perform the sort?

Trigger change event of dropdown

alternatively you can put onchange attribute on the dropdownlist itself, that onchange will call certain jquery function like this.

<input type="dropdownlist" onchange="jqueryFunc()">

<script type="text/javascript">
$(function(){
    jqueryFunc(){
        //something goes here
    }
});
</script>

hope this one helps you, and please note that this code is just a rough draft, not tested on any ide. thanks

ObjectiveC Parse Integer from String

You can just convert the string like that [str intValue] or [str integerValue]

integerValue Returns the NSInteger value of the receiver’s text.

  • (NSInteger)integerValue Return Value The NSInteger value of the receiver’s text, assuming a decimal representation and skipping whitespace at the beginning of the string. Returns 0 if the receiver doesn’t begin with a valid decimal text representation of a number.

for more information refer here

How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?

It's possible to inject instance of ApplicationContext class by using SpringClassRule and SpringMethodRule rules. It might be very handy if you would like to use another non-Spring runners. Here's an example:

@ContextConfiguration(classes = BeanConfiguration.class)
public static class SpringRuleUsage {

    @ClassRule
    public static final SpringClassRule springClassRule = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

    @Autowired
    private ApplicationContext context;

    @Test
    public void shouldInjectContext() {
    }
}

Java Date - Insert into database

The Answer by OscarRyz is correct, and should have been the accepted Answer. But now that Answer is out-dated.

java.time

In Java 8 and later, we have the new java.time package (inspired by Joda-Time, defined by JSR 310, with tutorial, extended by ThreeTen-Extra project).

Avoid Old Date-Time Classes

The old java.util.Date/.Calendar, SimpleDateFormat, and java.sql.Date classes are a confusing mess. For one thing, j.u.Date has date and time-of-day while j.s.Date is date-only without time-of-day. Oh, except that j.s.Date only pretends to not have a time-of-day. As a subclass of j.u.Date, j.s.Date inherits the time-of-day but automatically adjusts that time-of-day to midnight (00:00:00.000). Confusing? Yes. A bad hack, frankly.

For this and many more reasons, those old classes should be avoided, used only a last resort. Use java.time where possible, with Joda-Time as a fallback.

LocalDate

In java.time, the LocalDate class cleanly represents a date-only value without any time-of-day or time zone. That is what we need for this Question’s solution.

To get that LocalDate object, we parse the input string. But rather than use the old SimpleDateFormat class, java.time provides a new DateTimeFormatter class in the java.time.format package.

String input = "01/01/2009" ;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MM/dd/yyyy" ) ;
LocalDate localDate = LocalDate.parse( input, formatter ) ;

JDBC drivers compliant with JDBC 4.2 or later can use java.time types directly via the PreparedStatement::setObject and ResultSet::getObject methods.

PreparedStatement pstmt = connection.prepareStatement(
    "INSERT INTO USERS ( USER_ID, FIRST_NAME, LAST_NAME, SEX, DATE ) " +
    " VALUES (?, ?, ?, ?, ? )");

pstmt.setString( 1, userId );
pstmt.setString( 3, myUser.getLastName() ); 
pstmt.setString( 2, myUser.getFirstName() ); // please use "getFir…" instead of "GetFir…", per Java conventions.
pstmt.setString( 4, myUser.getSex() );
pstmt.setObject( 5, localDate ) ;  // Pass java.time object directly, without any need for java.sql.*. 

But until you have such an updated JDBC driver, fallback on using the java.sql.Date class. Fortunately, that old java.sql.Date class has been gifted by Java 8 with a new convenient conversion static method, valueOf( LocalDate ).

In the sample code of the sibling Answer by OscarRyz, replace its "sqlDate =" line with this one:

java.sql.Date sqlDate = java.sql.Date.valueOf( localDate ) ;

Get Windows version in a batch file

This will return 5.1 for xp or 6/1 for windows 7

for /f "tokens=4-7 delims=[.] " %%i in ('ver') do (
if %%i == Version set OSVersion=%%j.%%k
if %%i neq Version set OSVersion=%%i.%%j
)

How to outline text in HTML / CSS

There are some webkit css properties that should work on Chrome/Safari at least:

-webkit-text-stroke-width: 2px;
-webkit-text-stroke-color: black;

That's a 2px wide black text outline.

Passing multiple values for a single parameter in Reporting Services

If you want to pass multiple values to RS via a query string all you need to do is repeat the report parameter for each value.

For example; I have a RS column called COLS and this column expects one or more values.

&rp:COLS=1&rp:COLS=1&rp:COLS=5 etc..

Call to undefined function mysql_connect

Be sure you edited php.ini in /php folder, I lost all day to detect error and finally I found I edited php.ini in wrong location.

Fastest way to Remove Duplicate Value from a list<> by lambda

There is Distinct() method. it should works.

List<long> longs = new List<long> { 1, 2, 3, 4, 3, 2, 5 };
var distinctList = longs.Distinct().ToList();

Find element in List<> that contains a value

Enumerable.First returns the element instead of an index. In both cases you will get an exception if no matching element appears in the list (your original code will throw an IndexOutOfBoundsException when you try to get the item at index -1, but First will throw an InvalidOperationException).

MyList.First(item => string.Equals("foo", item.name)).value

Moment js get first and last day of current month

There would be another way to do this:

var begin = moment().format("YYYY-MM-01");
var end = moment().format("YYYY-MM-") + moment().daysInMonth();

Show / hide div on click with CSS

You're going to have to either use JS or write a function/method in whatever non-markup language you're using to do this. For instance you could write something that will save the status to a cookie or session variable then check for it on page load. If you want to do it without reloading the page then JS is going to be your only option.

Encode String to UTF-8

Use byte[] ptext = String.getBytes("UTF-8"); instead of getBytes(). getBytes() uses so-called "default encoding", which may not be UTF-8.

Mailx send html message

I had successfully used the following on Arch Linux (where the -a flag is used for attachments) for several years:

mailx -s "The Subject $( echo -e "\nContent-Type: text/html" [email protected] < email.html

This appended the Content-Type header to the subject header, which worked great until a recent update. Now the new line is filtered out of the -s subject. Presumably, this was done to improve security.

Instead of relying on hacking the subject line, I now use a bash subshell:

(
    echo -e "Content-Type: text/html\n"
    cat mail.html
 ) | mail -s "The Subject" -t [email protected]

And since we are really only using mailx's subject flag, it seems there is no reason not to switch to sendmail as suggested by @dogbane:

(
    echo "To: [email protected]"
    echo "Subject: The Subject"
    echo "Content-Type: text/html"
    echo
    cat mail.html
) | sendmail -t

The use of bash subshells avoids having to create a temporary file.

Angular 2 filter/search list

You can also create a search pipe to filter results:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name : 'searchPipe',
})
export class SearchPipe implements PipeTransform {
  public transform(value, key: string, term: string) {
    return value.filter((item) => {
      if (item.hasOwnProperty(key)) {
        if (term) {
          let regExp = new RegExp('\\b' + term, 'gi');
          return regExp.test(item[key]);
        } else {
          return true;
        }
      } else {
        return false;
      }
    });
  }
}

Use pipe in HTML :

<md-input placeholder="Item name..." [(ngModel)]="search" ></md-input>
<div *ngFor="let item of items | searchPipe:'name':search ">
  {{item.name}}
</div>

Laravel Redirect Back with() Message

In Laravel 5.4 the following worked for me:

return back()->withErrors(['field_name' => ['Your custom message here.']]);

Add table row in jQuery

<table id=myTable>
    <tr><td></td></tr>
    <style="height=0px;" tfoot></tfoot>
</table>

You can cache the footer variable and reduce access to DOM (Note: may be it will be better to use a fake row instead of footer).

var footer = $("#mytable tfoot")
footer.before("<tr><td></td></tr>")

How to fetch the row count for all tables in a SQL SERVER database

If you want to by pass the time and resources it takes to count(*) your 3million row tables. Try this per SQL SERVER Central by Kendal Van Dyke.


Row Counts Using sysindexes If you're using SQL 2000 you'll need to use sysindexes like so:

-- Shows all user tables and row counts for the current database 
-- Remove OBJECTPROPERTY function call to include system objects 
SELECT o.NAME,
  i.rowcnt 
FROM sysindexes AS i
  INNER JOIN sysobjects AS o ON i.id = o.id 
WHERE i.indid < 2  AND OBJECTPROPERTY(o.id, 'IsMSShipped') = 0
ORDER BY o.NAME

If you're using SQL 2005 or 2008 querying sysindexes will still work but Microsoft advises that sysindexes may be removed in a future version of SQL Server so as a good practice you should use the DMVs instead, like so:

-- Shows all user tables and row counts for the current database 
-- Remove is_ms_shipped = 0 check to include system objects 
-- i.index_id < 2 indicates clustered index (1) or hash table (0) 
SELECT o.name,
  ddps.row_count 
FROM sys.indexes AS i
  INNER JOIN sys.objects AS o ON i.OBJECT_ID = o.OBJECT_ID
  INNER JOIN sys.dm_db_partition_stats AS ddps ON i.OBJECT_ID = ddps.OBJECT_ID
  AND i.index_id = ddps.index_id 
WHERE i.index_id < 2  AND o.is_ms_shipped = 0 ORDER BY o.NAME 

SQL: Alias Column Name for Use in CASE Statement

  • If you write only equal condition just: Select Case columns1 When 0 then 'Value1' when 1 then 'Value2' else 'Unknown' End

  • If you want to write greater , Less then or equal you must do like this: Select Case When [ColumnsName] >0 then 'value1' When [ColumnsName]=0 Or [ColumnsName]<0 then 'value2' Else 'Unkownvalue' End

From tablename

Thanks Mr.Buntha Khin

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

A simple and intuitive way would be to use shuf.

Example:

Assume words.txt as:

the
an
linux
ubuntu
life
good
breeze

To shuffle the lines, do:

$ shuf words.txt

which would throws the shuffled lines to standard output; So, you've to pipe it to an output file like:

$ shuf words.txt > shuffled_words.txt

One such shuffle run could yield:

breeze
the
linux
an
ubuntu
good
life

How do I download a file with Angular2 or greater

As mentioned by Alejandro Corredor it is a simple scope error. The subscribe is run asynchronously and the open must be placed in that context, so that the data finished loading when we trigger the download.

That said, there are two ways of doing it. As the docs recommend the service takes care of getting and mapping the data:

//On the service:
downloadfile(runname: string, type: string){
  var headers = new Headers();
  headers.append('responseType', 'arraybuffer');
  return this.authHttp.get( this.files_api + this.title +"/"+ runname + "/?file="+ type)
            .map(res => new Blob([res],{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
            .catch(this.logAndPassOn);
}

Then, on the component we just subscribe and deal with the mapped data. There are two possibilities. The first, as suggested in the original post, but needs a small correction as noted by Alejandro:

//On the component
downloadfile(type: string){
  this.pservice.downloadfile(this.rundata.name, type)
      .subscribe(data => window.open(window.URL.createObjectURL(data)),
                  error => console.log("Error downloading the file."),
                  () => console.log('Completed file download.'));
  }

The second way would be to use FileReader. The logic is the same but we can explicitly wait for FileReader to load the data, avoiding the nesting, and solving the async problem.

//On the component using FileReader
downloadfile(type: string){
    var reader = new FileReader();
    this.pservice.downloadfile(this.rundata.name, type)
        .subscribe(res => reader.readAsDataURL(res), 
                    error => console.log("Error downloading the file."),
                    () => console.log('Completed file download.'));

    reader.onloadend = function (e) {
        window.open(reader.result, 'Excel', 'width=20,height=10,toolbar=0,menubar=0,scrollbars=no');
  }
}

Note: I am trying to download an Excel file, and even though the download is triggered (so this answers the question), the file is corrupt. See the answer to this post for avoiding the corrupt file.

How can I check if char* variable points to empty string?

Give it a chance:

Try getting string via function gets(string) then check condition as if(string[0] == '\0')

Root element is missing

I had the same problem when i have trying to read xml that was extracted from archive to memory stream.

 MemoryStream SubSetupStream = new MemoryStream();
        using (ZipFile archive = ZipFile.Read(zipPath))
        {
            archive.Password = "SomePass";
            foreach  (ZipEntry file in archive)
            {
                file.Extract(SubSetupStream);
            }
        }

Problem was in these lines:

XmlDocument doc = new XmlDocument();
    doc.Load(SubSetupStream);

And solution is (Thanks to @Phil):

        if (SubSetupStream.Position>0)
        {
            SubSetupStream.Position = 0;
        }

what happens when you type in a URL in browser

Look up the specification of HTTP. Or to get started, try http://www.jmarshall.com/easy/http/

Django: Display Choice Value

It looks like you were on the right track - get_FOO_display() is most certainly what you want:

In templates, you don't include () in the name of a method. Do the following:

{{ person.get_gender_display }}

How to set Highcharts chart maximum yAxis value

Alternatively one can use the setExtremes method also,

yAxis.setExtremes(0, 100);

Or if only one value is needed to be set, just leave other as null

yAxis.setExtremes(null, 100);

Using group by on two fields and count in SQL

I think you're looking for: SELECT a, b, COUNT(a) FROM tbl GROUP BY a, b

How do I make the first letter of a string uppercase in JavaScript?

Okay, so I am new to JavaScript. I wasn't able to get the above to work for me. So I started putting it together myself. Here's my idea (about the same, different and working syntax):

String name = request.getParameter("name");
name = name.toUpperCase().charAt(0) + name.substring(1);
out.println(name);

Here I get the variable from a form (it also works manually):

String name = "i am a Smartypants...";
name = name.toUpperCase().charAt(0) + name.substring(1);
out.println(name);

Output: "I am a Smartypants...";

How to send a html email with the bash command "sendmail"?

Found solution in http://senthilkl.blogspot.lu/2012/11/how-to-send-html-emails-using-sendemail.html

sendEmail -f "oracle@server" -t "[email protected]" -u "Alert: Backup complete" -o message-content-type=html -o message-file=$LOG_FILE  -a $LOG_FILE_ATTACH 

IF EXISTS condition not working with PLSQL

Unfortunately PL/SQL doesn't have IF EXISTS operator like SQL Server. But you can do something like this:

begin
  for x in ( select count(*) cnt
               from dual 
              where exists (
                select 1 from courseoffering co
                  join co_enrolment ce on ce.co_id = co.co_id
                 where ce.s_regno = 403 
                   and ce.coe_completionstatus = 'C' 
                   and co.c_id = 803 ) )
  loop
        if ( x.cnt = 1 ) 
        then
           dbms_output.put_line('exists');
        else 
           dbms_output.put_line('does not exist');
        end if;
  end loop;
end;
/

Why can't I use background image and color together?

To tint an image, you can use CSS3 background to stack images and a linear-gradient. In the example below, I use a linear-gradient with no actual gradient. The browser treats gradients as images (I think it actually generates a bitmap and overlays it) and thus, is actually stacking multiple images.

background: linear-gradient(0deg, rgba(2,173,231,0.5), rgba(2,173,231,0.5)), url(images/mba-grid-5px-bg.png) repeat;

Will yield a graph-paper with light blue tint, if you had the png. Note that the stacking order might work in reverse to your mental model, with the first item being on top.

Excellent documentation by Mozilla, here:

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_multiple_backgrounds

Tool for building the gradients:

http://www.colorzilla.com/gradient-editor/

Note - doesn't work in IE11! I'll post an update when I find out why, since its supposed to.

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

SQLite - getting number of rows in a database

I got same problem if i understand your question correctly, I want to know the last inserted id after every insert performance in SQLite operation. i tried the following statement:

select * from table_name order by id desc limit 1

The id is the first column and primary key of the table_name, the mentioned statement show me the record with the largest id.

But the premise is u never deleted any row so the numbers of id equal to the numbers of rows.

javascript: get a function's variable's value within another function

Your nameContent variable is inside the function scope and not visible outside that function so if you want to use the nameContent outside of the function then declare it global inside the <script> tag and use inside functions without the var keyword as follows

<script language="javascript" type="text/javascript">
    var nameContent; // In the global scope
    function first(){
        nameContent=document.getElementById('full_name').value;
    }

    function second() {
        first();
        y=nameContent; 
        alert(y);
    }
    second();
</script>

Get root view from current activity

For those of you who are using the Data Binding Library, to get the root of the current activity, simply use:

View rootView = dataBinding.getRoot();

And for Kotlin users, it's even simpler:

val rootView = dataBinding.root

MySQL select 10 random rows from 600K rows fast

I Use this query:

select floor(RAND() * (SELECT MAX(key) FROM table)) from table limit 10

query time:0.016s

How do I configure Maven for offline development?

Sadly dependency:go-offline hasn't worked for me as it didn't cached everything, ie. POMs files and other implicitly mention dependencies.

The workaround has been to specify a local repository location, either within settings.xml file with <localRepository>...</localRepository> or by running mvn with -Dmaven.repo.local=... parameter. After initial project build, all necessary artifacts should be cached, and then you can reference repository location the same ways, while running Maven build in offline mode (mvn -o ...).

When a 'blur' event occurs, how can I find out which element focus went *to*?

I am also trying to make Autocompleter ignore blurring if a specific element clicked and have a working solution, but for only Firefox due to explicitOriginalTarget

Autocompleter.Base.prototype.onBlur = Autocompleter.Base.prototype.onBlur.wrap( 
        function(origfunc, ev) {
            if ($(this.options.ignoreBlurEventElement)) {
                var newTargetElement = (ev.explicitOriginalTarget.nodeType == 3 ? ev.explicitOriginalTarget.parentNode : ev.explicitOriginalTarget);
                if (!newTargetElement.descendantOf($(this.options.ignoreBlurEventElement))) {
                    return origfunc(ev);
                }
            }
        }
    );

This code wraps default onBlur method of Autocompleter and checks if ignoreBlurEventElement parameters is set. if it is set, it checks everytime to see if clicked element is ignoreBlurEventElement or not. If it is, Autocompleter does not cal onBlur, else it calls onBlur. The only problem with this is that it only works in Firefox because explicitOriginalTarget property is Mozilla specific . Now I am trying to find a different way than using explicitOriginalTarget. The solution you have mentioned requires you to add onclick behaviour manually to the element. If I can't manage to solve explicitOriginalTarget issue, I guess I will follow your solution.

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

If you are working with the configuratior you can set the @grid-gutter-width from 30px to 0

In an array of objects, fastest way to find the index of an object whose attributes match a search

I like this method because it's easy to compare to any value in the object no matter how deep it's nested.

 while(i<myArray.length && myArray[i].data.value!==value){
  i++; 
}
// i now hows the index value for the match. 
 console.log("Index ->",i );

Find the maximum value in a list of tuples in Python

You could loop through the list and keep the tuple in a variable and then you can see both values from the same variable...

num=(0, 0)
for item in tuplelist:
  if item[1]>num[1]:
    num=item #num has the whole tuple with the highest y value and its x value

Why doesn't JavaScript support multithreading?

I don't know the rationale for this decision, but I know that you can simulate some of the benefits of multi-threaded programming using setTimeout. You can give the illusion of multiple processes doing things at the same time, though in reality, everything happens in one thread.

Just have your function do a little bit of work, and then call something like:

setTimeout(function () {
    ... do the rest of the work...
}, 0);

And any other things that need doing (like UI updates, animated images, etc) will happen when they get a chance.

Split large string in n-size chunks in JavaScript

const getChunksFromString = (str, chunkSize) => {
    var regexChunk = new RegExp(`.{1,${chunkSize}}`, 'g')   // '.' represents any character
    return str.match(regexChunk)
}

Call it as needed

console.log(getChunksFromString("Hello world", 3))   // ["Hel", "lo ", "wor", "ld"]

Difference between .on('click') vs .click()

I think, the difference is in usage patterns.

I would prefer .on over .click because the former can use less memory and work for dynamically added elements.

Consider the following html:

<html>
    <button id="add">Add new</button>
    <div id="container">
        <button class="alert">alert!</button>
    </div>
</html>

where we add new buttons via

$("button#add").click(function() {
    var html = "<button class='alert'>Alert!</button>";
    $("button.alert:last").parent().append(html);
});

and want "Alert!" to show an alert. We can use either "click" or "on" for that.


When we use click

$("button.alert").click(function() {
    alert(1);
});

with the above, a separate handler gets created for every single element that matches the selector. That means

  1. many matching elements would create many identical handlers and thus increase memory footprint
  2. dynamically added items won't have the handler - ie, in the above html the newly added "Alert!" buttons won't work unless you rebind the handler.

When we use .on

$("div#container").on('click', 'button.alert', function() {
    alert(1);
});

with the above, a single handler for all elements that match your selector, including the ones created dynamically.


...another reason to use .on

As Adrien commented below, another reason to use .on is namespaced events.

If you add a handler with .on("click", handler) you normally remove it with .off("click", handler) which will remove that very handler. Obviously this works only if you have a reference to the function, so what if you don't ? You use namespaces:

$("#element").on("click.someNamespace", function() { console.log("anonymous!"); });

with unbinding via

$("#element").off("click.someNamespace");

Write a file on iOS

Try making

NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile"];

as

NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile.txt"];

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

try with

<form formGroup="userForm">

instead of

<form [formGroup]="userForm">

function is not defined error in Python

if working with IDLE installed version of Python

>>>def any(a,b):
...    print(a+b)
...
>>>any(1,2)
3

TypeScript: correct way to do string equality?

If you know x and y are both strings, using === is not strictly necessary, but is still good practice.

Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string rather than an actual string, which may complicate things.

Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===. Just go with that.

Can I change the color of Font Awesome's icon color?

just give and text style whatever you want like :D HTML:

<a href="javascript:;" class="fa fa-trash" style="color:#d9534f;">
   <span style="color:black;">Text Name</span>
</a>

System.IO.IOException: file used by another process

Sounds like an external process (AV?) is locking it, but can't you avoid the problem in the first place?

private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod)
{
    try
    {
        string contents = File.ReadAllText(file.FullName);
        Console.WriteLine("input : {0}", contents);
        contents = contents.Replace(extractedMethod, modifiedMethod);
        Console.WriteLine("replaced String {0}", contents);
        File.WriteAllText(file.FullName, contents);
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
        return false;
    }
}

How to filter a data frame

Another method utilizing the dplyr package:

library(dplyr)
df <- mtcars %>%
        filter(mpg > 25)

Without the chain (%>%) operator:

library(dplyr)
df <- filter(mtcars, mpg > 25)

Cordova - Error code 1 for command | Command failed for

I had the same error code but different issue

Error: /Users/danieloram/desktop/CordovaProject/platforms/android/gradlew: Command failed with exit code 1 Error output: Exception in thread "main" java.lang.UnsupportedClassVersionError: com/android/dx/command/Main : Unsupported major.minor version 52.0

To resolve this issue I opened the Android SDK Manager, uninstalled the latest Android SDK build-tools that I had (24.0.3) and installed version 23.0.3 of the build-tools.

My cordova app then proceeded to build successfully for android.

Jquery/Ajax call with timer

If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:

setTimeout ( expression, timeout );
setInterval ( expression, interval );

Where expression is a function and timeout and interval are integers in milliseconds. setTimeout runs the timer once and runs the expression once whereas setInterval will run the expression every time the interval passes.

So in your case it would work something like this:

setInterval(function() {
    //call $.ajax here
}, 5000); //5 seconds

As far as the Ajax goes, see jQuery's ajax() method. If you run an interval, there is nothing stopping you from calling the same ajax() from other places in your code.


If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:

setInterval() returns an integer which is the ID of the interval.

var id = setInterval(function() {
    //call $.ajax here
}, 30000); // 30 seconds

If you store that ID in a variable, you can then call clearInterval(id) which will stop the progression.

Then you can reinstantiate the setInterval() call after you've completed your ajax form submission.

How do I list all loaded assemblies?

Here's what I ended up with. It's a listing of all properties and methods, and I listed all parameters for each method. I didn't succeed on getting all of the values.

foreach(System.Reflection.AssemblyName an in System.Reflection.Assembly.GetExecutingAssembly().GetReferencedAssemblies()){                      
            System.Reflection.Assembly asm = System.Reflection.Assembly.Load(an.ToString());
            foreach(Type type in asm.GetTypes()){   
                //PROPERTIES
                foreach (System.Reflection.PropertyInfo property in type.GetProperties()){
                    if (property.CanRead){
                        Response.Write("<br>" + an.ToString() + "." + type.ToString() + "." + property.Name);       
                    }
                }
                //METHODS
                var methods = type.GetMethods();
                foreach (System.Reflection.MethodInfo method in methods){               
                    Response.Write("<br><b>" + an.ToString() + "."  + type.ToString() + "." + method.Name  + "</b>");   
                    foreach (System.Reflection.ParameterInfo param in method.GetParameters())
                    {
                        Response.Write("<br><i>Param=" + param.Name.ToString());
                        Response.Write("<br>  Type=" + param.ParameterType.ToString());
                        Response.Write("<br>  Position=" + param.Position.ToString());
                        Response.Write("<br>  Optional=" + param.IsOptional.ToString() + "</i>");
                    }
                }
            }
        }

RESTful call in Java

Update: It’s been almost 5 years since I wrote the answer below; today I have a different perspective.

99% of the time when people use the term REST, they really mean HTTP; they could care less about “resources”, “representations”, “state transfers”, “uniform interfaces”, “hypermedia”, or any other constraints or aspects of the REST architecture style identified by Fielding. The abstractions provided by various REST frameworks are therefore confusing and unhelpful.

So: you want to send HTTP requests using Java in 2015. You want an API that is clear, expressive, intuitive, idiomatic, simple. What to use? I no longer use Java, but for the past few years the Java HTTP client library that has seemed the most promising and interesting is OkHttp. Check it out.


You can definitely interact with RESTful web services by using URLConnection or HTTPClient to code HTTP requests.

However, it's generally more desirable to use a library or framework which provides a simpler and more semantic API specifically designed for this purpose. This makes the code easier to write, read, and debug, and reduces duplication of effort. These frameworks generally implement some great features which aren't necessarily present or easy to use in lower-level libraries, such as content negotiation, caching, and authentication.

Some of the most mature options are Jersey, RESTEasy, and Restlet.

I'm most familiar with Restlet, and Jersey, let's look at how we'd make a POST request with both APIs.

Jersey Example

Form form = new Form();
form.add("x", "foo");
form.add("y", "bar");

Client client = ClientBuilder.newClient();

WebTarget resource = client.target("http://localhost:8080/someresource");

Builder request = resource.request();
request.accept(MediaType.APPLICATION_JSON);

Response response = request.get();

if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
    System.out.println("Success! " + response.getStatus());
    System.out.println(response.getEntity());
} else {
    System.out.println("ERROR! " + response.getStatus());    
    System.out.println(response.getEntity());
}

Restlet Example

Form form = new Form();
form.add("x", "foo");
form.add("y", "bar");

ClientResource resource = new ClientResource("http://localhost:8080/someresource");

Response response = resource.post(form.getWebRepresentation());

if (response.getStatus().isSuccess()) {
    System.out.println("Success! " + response.getStatus());
    System.out.println(response.getEntity().getText());
} else {
    System.out.println("ERROR! " + response.getStatus());
    System.out.println(response.getEntity().getText());
}

Of course, GET requests are even simpler, and you can also specify things like entity tags and Accept headers, but hopefully these examples are usefully non-trivial but not too complex.

As you can see, Restlet and Jersey have similar client APIs. I believe they were developed around the same time, and therefore influenced each other.

I find the Restlet API to be a little more semantic, and therefore a little clearer, but YMMV.

As I said, I'm most familiar with Restlet, I've used it in many apps for years, and I'm very happy with it. It's a very mature, robust, simple, effective, active, and well-supported framework. I can't speak to Jersey or RESTEasy, but my impression is that they're both also solid choices.

Split string based on a regular expression

The str.split method will automatically remove all white space between items:

>>> str1 = "a    b     c      d"
>>> str1.split()
['a', 'b', 'c', 'd']

Docs are here: http://docs.python.org/library/stdtypes.html#str.split

How to read a PEM RSA private key from .NET

For people who don't want to use Bouncy, and are trying some of the code included in other answers, I've found that the code works MOST of the time, but trips up on some RSA private strings, such as the one I've included below. By looking at the bouncy code, I tweaked the code provided by wprl to

    RSAparams.D = ConvertRSAParametersField(D, MODULUS.Length);
    RSAparams.DP = ConvertRSAParametersField(DP, P.Length);
    RSAparams.DQ = ConvertRSAParametersField(DQ, Q.Length);
    RSAparams.InverseQ = ConvertRSAParametersField(IQ, Q.Length);

    private static byte[] ConvertRSAParametersField(byte[] bs, int size)
    {
        if (bs.Length == size)
            return bs;

        if (bs.Length > size)
            throw new ArgumentException("Specified size too small", "size");

        byte[] padded = new byte[size];
        Array.Copy(bs, 0, padded, size - bs.Length, bs.Length);
        return padded;
    }

-----BEGIN RSA PRIVATE KEY-----
MIIEoQIBAAKCAQEAxCgWAYJtfKBVa6Px1Blrj+3Wq7LVXDzx+MiQFrLCHnou2Fvb
fxuDeRmd6ERhDWnsY6dxxm981vTlXukvYKpIZQYpiSzL5pyUutoi3yh0+/dVlsHZ
UHheVGZjSMgUagUCLX1p/augXltAjgblUsj8GFBoKJBr3TMKuR5TwF7lBNYZlaiR
k9MDZTROk6MBGiHEgD5RaPKA/ot02j3CnSGbGNNubN2tyXXAgk8/wBmZ4avT0U4y
5oiO9iwCF/Hj9gK/S/8Q2lRsSppgUSsCioSg1CpdleYzIlCB0li1T0flB51zRIpg
JhWRfmK1uTLklU33xfzR8zO2kkfaXoPTHSdOGQIDAQABAoIBAAkhfzoSwttKRgT8
sgUYKdRJU0oqyO5s59aXf3LkX0+L4HexzvCGbK2hGPihi42poJdYSV4zUlxZ31N2
XKjjRFDE41S/Vmklthv8i3hX1G+Q09XGBZekAsAVrrQfRtP957FhD83/GeKf3MwV
Bhe/GKezwSV3k43NvRy2N1p9EFa+i7eq1e5i7MyDxgKmja5YgADHb8izGLx8Smdd
+v8EhWkFOcaPnQRj/LhSi30v/CjYh9MkxHMdi0pHMMCXleiUK0Du6tnsB8ewoHR3
oBzL4F5WKyNHPvesYplgTlpMiT0uUuN8+9Pq6qsdUiXs0wdFYbs693mUMekLQ4a+
1FOWvQECgYEA7R+uI1r4oP82sTCOCPqPi+fXMTIOGkN0x/1vyMXUVvTH5zbwPp9E
0lG6XmJ95alMRhjvFGMiCONQiSNOQ9Pec5TZfVn3M/w7QTMZ6QcWd6mjghc+dGGE
URmCx8xaJb847vACir7M08AhPEt+s2C7ZokafPCoGe0qw/OD1fLt3NMCgYEA08WK
S+G7dbCvFMrBP8SlmrnK4f5CRE3pV4VGneWp/EqJgNnWwaBCvUTIegDlqS955yVp
q7nVpolAJCmlUVmwDt4gHJsWXSQLMXy3pwQ25vdnoPe97y3xXsi0KQqEuRjD1vmw
K7SXoQqQeSf4z74pFal4CP38U3pivvoE4MQmJeMCfyJFceWqQEUEneL+IYkqrZSK
7Y8urNse5MIC3yUlcose1cWVKyPh4RCEv2rk0U1gKqX29Jb9vO2L7RflAmrLNFuA
J+72EcRxsB68RAJqA9VHr1oeAejQL0+JYF2AK4dJG/FsvvFOokv4eNU+FBHY6Tzo
k+t63NDidkvb5jIF6lsCgYEAlnQ08f5Y8Z9qdCosq8JpKYkwM+kxaVe1HUIJzqpZ
X24RTOL3aa8TW2afy9YRVGbvg6IX9jJcMSo30Llpw2cl5xo21Dv24ot2DF2gGN+s
peFF1Z3Naj1Iy99p5/KaIusOUBAq8pImW/qmc/1LD0T56XLyXekcuK4ts6Lrjkit
FaMCgYAusOLTsRgKdgdDNI8nMQB9iSliwHAG1TqzB56S11pl+fdv9Mkbo8vrx6g0
NM4DluCGNEqLZb3IkasXXdok9e8kmX1en1lb5GjyPbc/zFda6eZrwIqMX9Y68eNR
IWDUM3ckwpw3rcuFXjFfa+w44JZVIsgdoGHiXAdrhtlG/i98Rw==
-----END RSA PRIVATE KEY-----

SQL Server 2008- Get table constraints

I tried to edit the answer provided by marc_s however it wasn't accepted for some reason. It formats the sql for easier reading, includes the schema and also names the Default name so that this can easily be pasted into other code.

  SELECT SchemaName = s.Name,
         TableName = t.Name,
         ColumnName = c.Name,
         DefaultName = dc.Name,
         DefaultDefinition = dc.Definition
    FROM sys.schemas                s
    JOIN sys.tables                 t   on  t.schema_id          = s.schema_id
    JOIN sys.default_constraints    dc  on  dc.parent_object_id  = t.object_id 
    JOIN sys.columns                c   on  c.object_id          = dc.parent_object_id
                                        and c.column_id          = dc.parent_column_id
ORDER BY s.Name, t.Name, c.name

How to insert new cell into UITableView in Swift

For Swift 5

Remove Cell

    let indexPath = [NSIndexPath(row: yourArray-1, section: 0)]
    yourArray.remove(at: buttonTag)
    self.tableView.beginUpdates()

    self.tableView.deleteRows(at: indexPath as [IndexPath] , with: .fade)
    self.tableView.endUpdates()
    self.tableView.reloadData()// Not mendatory, But In my case its requires

Add new cell

    yourArray.append(4)

    tableView.beginUpdates()
    tableView.insertRows(at: [
        (NSIndexPath(row: yourArray.count-1, section: 0) as IndexPath)], with: .automatic)
    tableView.endUpdates()

How can I generate a list of files with their absolute path in Linux?

Here's an example that prints out a list without an extra period and that also demonstrates how to search for a file match. Hope this helps:

find . -type f -name "extr*" -exec echo `pwd`/{} \; | sed "s|\./||"

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

For anyone coming here in 2018:

  • go to iTerm -> Preferences -> Profiles -> Advanced -> Semantic History
  • from the dropdown, choose Open with Editor and from the right dropdown choose your editor of choice

How do I sort arrays using vbscript?

If you are going to output the lines anyway, you could run the output through the sort command. Not elegant, but it does not require much work:

cscript.exe //nologo YOUR-SCRIPT | Sort

Note //nologo omits the logo lines (Microsoft (R) Windows Script Host Version... blah blah blah) from appearing in the middle of your sorted output. (I guess MS does not know what stderr is for.)

See http://ss64.com/nt/sort.html for details on sort.

/+n is the most useful option if your sort key does not start in the first column.

Compares are always case-insensitive, which is lame.

Iterate over object keys in node.js

What you want is lazy iteration over an object or array. This is not possible in ES5 (thus not possible in node.js). We will get this eventually.

The only solution is finding a node module that extends V8 to implement iterators (and probably generators). I couldn't find any implementation. You can look at the spidermonkey source code and try writing it in C++ as a V8 extension.

You could try the following, however it will also load all the keys into memory

Object.keys(o).forEach(function(key) {
  var val = o[key];
  logic();
});

However since Object.keys is a native method it may allow for better optimisation.

Benchmark

As you can see Object.keys is significantly faster. Whether the actual memory storage is more optimum is a different matter.

var async = {};
async.forEach = function(o, cb) {
  var counter = 0,
    keys = Object.keys(o),
    len = keys.length;
  var next = function() {
    if (counter < len) cb(o[keys[counter++]], next);
  };
  next();
};

async.forEach(obj, function(val, next) {
  // do things
  setTimeout(next, 100);
});

MySQL - Select the last inserted row easiest way

Just after running mysql query from php

get it by

$lastid=mysql_insert_id();

this give you the alst auto increment id value

Is there any quick way to get the last two characters in a string?

The existing answers will fail if the string is empty or only has one character. Options:

String substring = str.length() > 2 ? str.substring(str.length() - 2) : str;

or

String substring = str.substring(Math.max(str.length() - 2, 0));

That's assuming that str is non-null, and that if there are fewer than 2 characters, you just want the original string.

SQL Server Group By Month

Another approach, that doesn't involve adding columns to the result, is to simply zero-out the day component of the date, so 2016-07-13 and 2016-07-16 would both be 2016-07-01 - thus making them equal by month.

If you have a date (not a datetime) value, then you can zero it directly:

SELECT
    DATEADD( day, 1 - DATEPART( day, [Date] ), [Date] ),
    COUNT(*)
FROM
    [Table]
GROUP BY
    DATEADD( day, 1 - DATEPART( day, [Date] ), [Date] )

If you have datetime values, you'll need to use CONVERT to remove the time-of-day portion:

SELECT
    DATEADD( day, 1 - DATEPART( day, [Date] ),  CONVERT( date, [Date] ) ),
    COUNT(*)
FROM
    [Table]
GROUP BY
    DATEADD( day, 1 - DATEPART( day, [Date] ),  CONVERT( date, [Date] ) )

Adding three months to a date in PHP

Change it to this will give you the expected format:

$effectiveDate = date('Y-m-d', strtotime("+3 months", strtotime($effectiveDate)));

How can I increase a scrollbar's width using CSS?

Yes.

If the scrollbar is not the browser scrollbar, then it will be built of regular HTML elements (probably divs and spans) and can thus be styled (or will be Flash, Java, etc and can be customized as per those environments).

The specifics depend on the DOM structure used.

Different ways of clearing lists

There are two cases in which you might want to clear a list:

  1. You want to use the name old_list further in your code;
  2. You want the old list to be garbage collected as soon as possible to free some memory;

In case 1 you just go on with the assigment:

    old_list = []    # or whatever you want it to be equal to

In case 2 the del statement would reduce the reference count to the list object the name old list points at. If the list object is only pointed by the name old_list at, the reference count would be 0, and the object would be freed for garbage collection.

    del old_list

How to pass a parameter to Vue @click event handler

Just use a normal Javascript expression, no {} or anything necessary:

@click="addToCount(item.contactID)"

if you also need the event object:

@click="addToCount(item.contactID, $event)"

Hive: Filtering Data between Specified Dates when Date is a String

You have to convert string formate to required date format as following and then you can get your required result.

hive> select * from salesdata01 where from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') >= from_unixtime(unix_timestamp('2010-09-01', 'yyyy-MM-dd'),'yyyy-MM-dd') and from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') <= from_unixtime(unix_timestamp('2011-09-01', 'yyyy-MM-dd'),'yyyy-MM-dd') limit 10;
OK
1   3   13-10-2010  Low 6.0 261.54  0.04    Regular Air -213.25 38.94
80  483 10-07-2011  High    30.0    4965.7593   0.08    Regular Air 1198.97 195.99
97  613 17-06-2011  High    12.0    93.54   0.03    Regular Air -54.04  7.3
98  613 17-06-2011  High    22.0    905.08  0.09    Regular Air 127.7   42.76
103 643 24-03-2011  High    21.0    2781.82 0.07    Express Air -695.26 138.14
127 807 23-11-2010  Medium  45.0    196.85  0.01    Regular Air -166.85 4.28
128 807 23-11-2010  Medium  32.0    124.56  0.04    Regular Air -14.33  3.95
160 995 30-05-2011  Medium  46.0    1815.49 0.03    Regular Air 782.91  39.89
229 1539    09-03-2011  Low 33.0    511.83  0.1 Regular Air -172.88 15.99
230 1539    09-03-2011  Low 38.0    184.99  0.05    Regular Air -144.55 4.89
Time taken: 0.166 seconds, Fetched: 10 row(s)
hive> select * from salesdata01 where from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') >= from_unixtime(unix_timestamp('2010-09-01', 'yyyy-MM-dd'),'yyyy-MM-dd') and from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') <= from_unixtime(unix_timestamp('2010-12-01', 'yyyy-MM-dd'),'yyyy-MM-dd') limit 10;
OK
1   3   13-10-2010  Low 6.0 261.54  0.04    Regular Air -213.25 38.94
127 807 23-11-2010  Medium  45.0    196.85  0.01    Regular Air -166.85 4.28
128 807 23-11-2010  Medium  32.0    124.56  0.04    Regular Air -14.33  3.95
256 1792    08-11-2010  Low 28.0    370.48  0.04    Regular Air -5.45   13.48
381 2631    23-09-2010  Low 27.0    1078.49 0.08    Regular Air 252.66  40.96
656 4612    19-09-2010  Medium  9.0 89.55   0.06    Regular Air -375.64 4.48
769 5506    07-11-2010  Critical    22.0    129.62  0.05    Regular Air 4.41    5.88
1457    10499   16-11-2010  Not Specified   29.0    6250.936    0.01    Delivery Truck  31.21   262.11
1654    11911   10-11-2010  Critical    25.0    397.84  0.0 Regular Air -14.75  15.22
2323    16741   30-09-2010  Medium  6.0 157.97  0.01    Regular Air -42.38  22.84
Time taken: 0.17 seconds, Fetched: 10 row(s)

How to check if Location Services are enabled?

Migrate to Android X and use

implementation 'androidx.appcompat:appcompat:1.1.0'

and use LocationManagerCompat

In java

private boolean isLocationEnabled(Context context) {
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    return LocationManagerCompat.isLocationEnabled(locationManager);
}

In Kotlin

private fun isLocationEnabled(context: Context): Boolean {
    val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    return LocationManagerCompat.isLocationEnabled(locationManager)
}

Update:

implementation 'androidx.appcompat:appcompat:1.2.0'

get dictionary key by value

I was in a situation where Linq binding was not available and had to expand lambda explicitly. It resulted in a simple function:

public static T KeyByValue<T, W>(this Dictionary<T, W> dict, W val)
{
    T key = default;
    foreach (KeyValuePair<T, W> pair in dict)
    {
        if (EqualityComparer<W>.Default.Equals(pair.Value, val))
        {
            key = pair.Key;
            break;
        }
    }
    return key;
}

Call it like follows:

public static void Main()
{
    Dictionary<string, string> dict = new Dictionary<string, string>()
    {
        {"1", "one"},
        {"2", "two"},
        {"3", "three"}
    };

    string key = KeyByValue(dict, "two");       
    Console.WriteLine("Key: " + key);
}

Works on .NET 2.0 and in other limited environments.

Laravel: Using try...catch with DB::transaction()

If you use PHP7, use Throwable in catch for catching user exceptions and fatal errors.

For example:

DB::beginTransaction();

try {
    DB::insert(...);    
    DB::commit();
} catch (\Throwable $e) {
    DB::rollback();
    throw $e;
}

If your code must be compartable with PHP5, use Exception and Throwable:

DB::beginTransaction();

try {
    DB::insert(...);    
    DB::commit();
} catch (\Exception $e) {
    DB::rollback();
    throw $e;
} catch (\Throwable $e) {
    DB::rollback();
    throw $e;
}

How can I generate Javadoc comments in Eclipse?

Shift-Alt-J is a useful keyboard shortcut in Eclipse for creating Javadoc comment templates.

Invoking the shortcut on a class, method or field declaration will create a Javadoc template:

public int doAction(int i) {
    return i;
}

Pressing Shift-Alt-J on the method declaration gives:

/**
 * @param i
 * @return
 */
public int doAction(int i) {
    return i;
}

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:

NuGet

Up next is the create script. Creating a database file:

SQLiteConnection.CreateFile("MyDatabase.sqlite");

SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

m_dbConnection.Close();

After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
 {
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
     tran.Complete();
 }

Find a line in a file and remove it

package com.ncs.cache;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;

public class FileUtil {

    public void removeLineFromFile(String file, String lineToRemove) {

        try {

            File inFile = new File(file);

            if (!inFile.isFile()) {
                System.out.println("Parameter is not an existing file");
                return;
            }

            // Construct the new file that will later be renamed to the original
            // filename.
            File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

            BufferedReader br = new BufferedReader(new FileReader(file));
            PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

            String line = null;

            // Read from the original file and write to the new
            // unless content matches data to be removed.
            while ((line = br.readLine()) != null) {

                if (!line.trim().equals(lineToRemove)) {

                    pw.println(line);
                    pw.flush();
                }
            }
            pw.close();
            br.close();

            // Delete the original file
            if (!inFile.delete()) {
                System.out.println("Could not delete file");
                return;
            }

            // Rename the new file to the filename the original file had.
            if (!tempFile.renameTo(inFile))
                System.out.println("Could not rename file");

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        FileUtil util = new FileUtil();
        util.removeLineFromFile("test.txt", "bbbbb");
    }
}

src : http://www.javadb.com/remove-a-line-from-a-text-file/

How to delete a specific line in a file?

If you use Linux, you can try the following approach.
Suppose you have a text file named animal.txt:

$ cat animal.txt  
dog
pig
cat 
monkey         
elephant  

Delete the first line:

>>> import subprocess
>>> subprocess.call(['sed','-i','/.*dog.*/d','animal.txt']) 

then

$ cat animal.txt
pig
cat
monkey
elephant

How to prompt for user input and read command-line arguments

Use 'raw_input' for input from a console/terminal.

if you just want a command line argument like a file name or something e.g.

$ python my_prog.py file_name.txt

then you can use sys.argv...

import sys
print sys.argv

sys.argv is a list where 0 is the program name, so in the above example sys.argv[1] would be "file_name.txt"

If you want to have full on command line options use the optparse module.

Pev

How to trigger jQuery change event in code

Use the trigger() method

$(selector).trigger("change");

Anaconda export Environment file

I find exporting the packages in string format only is more portable than exporting the whole conda environment. As the previous answer already suggested:

$ conda list -e > requirements.txt

However, this requirements.txt contains build numbers which are not portable between operating systems, e.g. between Mac and Ubuntu. In conda env export we have the option --no-builds but not with conda list -e, so we can remove the build number by issuing the following command:

$ sed -i -E "s/^(.*\=.*)(\=.*)/\1/" requirements.txt 

And recreate the environment on another computer:

conda create -n recreated_env --file requirements.txt 

Python - converting a string of numbers into a list of int

I guess the dirtiest solution is this:

list(eval('0, 0, 0, 11, 0, 0, 0, 11'))

How to get root directory in yii2

Use "getAlias" in Yii2

   \Yii::getAlias('@webroot')

How to deploy a war file in JBoss AS 7?

Actually, for the latest JBOSS 7 AS, we need a .dodeploy marker even for archives. So add a marker to trigger the deployment.

In my case, I added a Hello.war.deployed file in the same directory and then everything worked fine.

Hope this helps someone!

How to get Spinner value?

Yes, you can register a listener via setOnItemSelectedListener(), as is demonstrated here.

Update query using Subquery in Sql Server

The title of this thread asks how a subquery can be used in an update. Here's an example of that:

update [dbName].[dbo].[MyTable] 
set MyColumn = 1 
where 
    (
        select count(*) 
        from [dbName].[dbo].[MyTable] mt2 
        where
            mt2.ID > [dbName].[dbo].[MyTable].ID
            and mt2.Category = [dbName].[dbo].[MyTable].Category
    ) > 0

jquery $('.class').each() how many items?

Use the .length property. It is not a function.

alert($('.class').length); // alerts a nonnegative number 

Changing iframe src with Javascript

You can solve it by making the iframe in javascript

_x000D_
_x000D_
  document.write(" <iframe  id='frame' name='frame' src='" + srcstring + "' width='600'  height='315'   allowfullscreen></iframe>");
_x000D_
_x000D_
_x000D_

How to list the files inside a JAR file?

Here is an example of using Reflections library to recursively scan classpath by regex name pattern augmented with a couple of Guava perks to to fetch resources contents:

Reflections reflections = new Reflections("com.example.package", new ResourcesScanner());
Set<String> paths = reflections.getResources(Pattern.compile(".*\\.template$"));

Map<String, String> templates = new LinkedHashMap<>();
for (String path : paths) {
    log.info("Found " + path);
    String templateName = Files.getNameWithoutExtension(path);
    URL resource = getClass().getClassLoader().getResource(path);
    String text = Resources.toString(resource, StandardCharsets.UTF_8);
    templates.put(templateName, text);
}

This works with both jars and exploded classes.

How to convert from java.sql.Timestamp to java.util.Date?

The problem is probably coming from the fact that Date is deprecated.

Consider using

java.util.Calendar

or

Joda-Time

Edit 2015:

Java 8 and later has built-in the new java.time package, which is similar to Joda-Time.

How to discard local changes and pull latest from GitHub repository

In addition to the above answers, there is always the scorched earth method.

rm -R <folder>

in Windows shell the command is:

rd /s <folder>

Then you can just checkout the project again:

git clone -v <repository URL> 

This will definitely remove any local changes and pull the latest from the remote repository. Be careful with rm -R as it will delete your good data if you put the wrong path. For instance, definitely do not do:

rm -R /

edit: To fix spelling and add emphasis.

How to call a PHP file from HTML or Javascript

As you have already stated in your question you have more than one option. A very basic approach would be using the tag referencing your PHP file in the method attribute. However as esoteric as it may sound AJAX is a more complete approach. Considering that an AJAX call (in combination with jQuery) can be as simple as:

$.post("yourfile.php", {data : "This can be as long as you want"});

And you get a more flexible solution, for example triggering a function after the server request is completed. Hope this helps.

NSAttributedString add text alignment

 NSMutableParagraphStyle *paragraphStyle = NSMutableParagraphStyle.new;
 paragraphStyle.alignment                = NSTextAlignmentCenter;

 NSAttributedString *attributedString   = 
[NSAttributedString.alloc initWithString:@"someText" 
                              attributes:
         @{NSParagraphStyleAttributeName:paragraphStyle}];

Swift 4.2

let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = NSTextAlignment.center

    let attributedString = NSAttributedString(string: "someText", attributes: [NSAttributedString.Key.paragraphStyle : paragraphStyle])

Is there any option to limit mongodb memory usage?

If you're using Docker, reading the Docker image documentation (in the Setting WiredTiger cache size limits section) I found out that they set the default to consume all available memory regardless of memory limits you may have imposed on the container, so you would have to limit the RAM usage directly from the DB configuration.

  1. Create you mongod.conf file:
# Limits cache storage
storage:
   wiredTiger:
      engineConfig:
         cacheSizeGB: 1 # Set the size you want
  1. Now you can assign that config file to the container: docker run --name mongo-container -v /path/to/mongod.conf:/etc/mongo/mongod.conf -d mongo --config /etc/mongo/mongod.conf
  2. Alternatively you could use a docker-compose.yml file:
version: '3'

services:
    mongo:
        image: mongo:4.2
        # Sets the config file
        command: --config /etc/mongo/mongod.conf
        volumes:
            - ./config/mongo/mongod.conf:/etc/mongo/mongod.conf
        # Others settings...

What's the CMake syntax to set and use variables?

$ENV{FOO} for usage, where FOO is being picked up from the environment variable. otherwise use as ${FOO}, where FOO is some other variable. For setting, SET(FOO "foo") would be used in CMake.

PDO Prepared Inserts multiple rows in single query

Here is another (slim) solution for this issue:

At first you need to count the data of the source array (here: $aData) with count(). Then you use array_fill() and generate a new array wich as many entries as the source array has, each with the value "(?,?)" (the number of placeholders depends on the fields you use; here: 2). Then the generated array needs to be imploded and as glue a comma is used. Within the foreach loop, you need to generate another index regarding on the number of placeholders you use (number of placeholders * current array index + 1). You need to add 1 to the generated index after each binded value.

$do = $db->prepare("INSERT INTO table (id, name) VALUES ".implode(',', array_fill(0, count($aData), '(?,?)')));

foreach($aData as $iIndex => $aValues){
 $iRealIndex = 2 * $iIndex + 1;
 $do->bindValue($iRealIndex, $aValues['id'], PDO::PARAM_INT);
 $iRealIndex = $iRealIndex + 1;
 $do->bindValue($iRealIndex, $aValues['name'], PDO::PARAM_STR);
}

$do->execute();

Get user input from textarea

Tested with Angular2 RC2

I tried a code-snippet similar to yours and it works for me ;) see [(ngModel)] = "str" in my template If you push the button, the console logs the current content of the textarea-field. Hope it helps

textarea-component.ts

import {Component} from '@angular/core';

@Component({
  selector: 'textarea-comp',
  template: `
      <textarea cols="30" rows="4" [(ngModel)] = "str"></textarea>
      <p><button (click)="pushMe()">pushMeToLog</button></p>
  `
})

  export class TextAreaComponent {
    str: string;

  pushMe() {
      console.log( "TextAreaComponent::str: " + this.str);
  }
}

How to pass an event object to a function in Javascript?

  1. Modify the definition of the function check_me as::

     function check_me(ev) {
    
  2. Now you can access the methods and parameters of the event, in your case:

     ev.preventDefault();
    
  3. Then, you have to pass the parameter on the onclick in the inline call::

     <button type="button" onclick="check_me(event);">Click Me!</button>
    

A useful link to understand this.


Full example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script type="text/javascript">
      function check_me(ev) {
        ev.preventDefault();
        alert("Hello World!")
      }
    </script>
  </head>
  <body>
    <button type="button" onclick="check_me(event);">Click Me!</button>
  </body>
</html>









Alternatives (best practices):

Although the above is the direct answer to the question (passing an event object to an inline event), there are other ways of handling events that keep the logic separated from the presentation

A. Using addEventListener:

<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
    <button id='my_button' type="button">Click Me!</button>

    <!-- put the javascript at the end to guarantee that the DOM is ready to use-->
    <script type="text/javascript">
      function check_me(ev) {
        ev.preventDefault();
        alert("Hello World!")
      }
      
      <!-- add the event to the button identified #my_button -->
      document.getElementById("my_button").addEventListener("click", check_me);
    </script>
  </body>
</html>

B. Isolating Javascript:

Both of the above solutions are fine for a small project, or a hackish quick and dirty solution, but for bigger projects, it is better to keep the HTML separated from the Javascript.

Just put this two files in the same folder:

  • example.html:
<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
    <button id='my_button' type="button">Click Me!</button>

    <!-- put the javascript at the end to guarantee that the DOM is ready to use-->
    <script type="text/javascript" src="example.js"></script>
  </body>
</html>
  • example.js:
function check_me(ev) {
    ev.preventDefault();
    alert("Hello World!")
}
document.getElementById("my_button").addEventListener("click", check_me);

msvcr110.dll is missing from computer error while installing PHP

I had installed PHP in IIS7 on Windows Server 2008 R2 using the Web Platform Installer. It did not work out of the box. I had to install the Visual C++ Redistributable for VS 2012 Update 4 (32bit) as found here http://www.microsoft.com/en-us/download/details.aspx?id=30679 .

Difference between Select Unique and Select Distinct

  1. Unique was the old syntax while Distinct is the new syntax,which is now the Standard sql.
  2. Unique creates a constraint that all values to be inserted must be different from the others. An error can be witnessed if one tries to enter a duplicate value. Distinct results in the removal of the duplicate rows while retrieving data.
  3. Example: SELECT DISTINCT names FROM student ;

    CREATE TABLE Persons ( Id varchar NOT NULL UNIQUE, Name varchar(20) );

how to upload a file to my server using html

On top of what the others have already stated, some sort of server-side scripting is necessary in order for the server to read and save the file.

Using PHP might be a good choice, but you're free to use any server-side scripting language. http://www.w3schools.com/php/php_file_upload.asp may be of use on that end.

Adjust UILabel height depending on the text

Swift 2:

    yourLabel.text = "your very long text"
    yourLabel.numberOfLines = 0
    yourLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
    yourLabel.frame.size.width = 200
    yourLabel.frame.size.height = CGFloat(MAXFLOAT)
    yourLabel.sizeToFit()

The interesting lines are sizeToFit() in conjunction with setting a frame.size.height to the max float, this will give room for long text, but sizeToFit() will force it to only use the necessary, but ALWAYS call it after setting the .frame.size.height .

I recommend setting a .backgroundColor for debug purposes, this way you can see the frame being rendered for each case.

Group a list of objects by an attribute

Java 8 groupingBy Collector

Probably it's late but I like to share an improved idea to this problem. This is basically the same of @Vitalii Fedorenko's answer but more handly to play around.

You can just use the Collectors.groupingBy() by passing the grouping logic as function parameter and you will get the splitted list with the key parameter mapping. Note that using Optional is used to avoid the unwanted NPE when the provided list is null

public static <E, K> Map<K, List<E>> groupBy(List<E> list, Function<E, K> keyFunction) {
    return Optional.ofNullable(list)
            .orElseGet(ArrayList::new)
            .stream()
            .collect(Collectors.groupingBy(keyFunction));
}

Now you can groupBy anything with this. For the use case here in the question

Map<String, List<Student>> map = groupBy(studlist, Student::getLocation);

Maybe you would like to look into this also Guide to Java 8 groupingBy Collector

window.close and self.close do not close the window in Chrome

I found a new way that works for me perfetly

var win = window.open("about:blank", "_self");
win.close();

Jquery - How to make $.post() use contentType=application/json?

we can change Content-type like this in $.post

$.post(url,data, function (data, status, xhr) { xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");});

How to squash all git commits into one?

I read something about using grafts but never investigated it much.

Anyway, you can squash those last 2 commits manually with something like this:

git reset HEAD~1
git add -A
git commit --amend

R Apply() function on specific dataframe columns

lapply is probably a better choice than apply here, as apply first coerces your data.frame to an array which means all the columns must have the same type. Depending on your context, this could have unintended consequences.

The pattern is:

df[cols] <- lapply(df[cols], FUN)

The 'cols' vector can be variable names or indices. I prefer to use names whenever possible (it's robust to column reordering). So in your case this might be:

wifi[4:9] <- lapply(wifi[4:9], A)

An example of using column names:

wifi <- data.frame(A=1:4, B=runif(4), C=5:8)
wifi[c("B", "C")] <- lapply(wifi[c("B", "C")], function(x) -1 * x)

How do I include a path to libraries in g++

To specify a directory to search for (binary) libraries, you just use -L:

-L/data[...]/lib

To specify the actual library name, you use -l:

-lfoo  # (links libfoo.a or libfoo.so)

To specify a directory to search for include files (different from libraries!) you use -I:

-I/data[...]/lib

So I think what you want is something like

g++ -g -Wall -I/data[...]/lib testing.cpp fileparameters.cpp main.cpp -o test

These compiler flags (amongst others) can also be found at the GNU GCC Command Options manual:

How can I call a method in Objective-C?

I think what you're trying to do is:

-(void) score2 {
    [self score];
}

The [object message] syntax is the normal way to call a method in objective-c. I think the @selector syntax is used when the method to be called needs to be determined at run-time, but I don't know well enough to give you more information on that.

slideToggle JQuery right to left

include Jquery and Jquery UI plugins and try this

 $("#LeftSidePane").toggle('slide','left',400);

How to configure Chrome's Java plugin so it uses an existing JDK in the machine

I'm on Windows 7 64 bit and couldn't understand if I can manually enable JRE8 64 bit for Chrome. Turned out that my problem was that Java plugin DLL is 64 bit which wouldn't work in 32 bit Chrome. Therefore you need to install x86 version of JRE. Below are Windows registry settings you need to create

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2]
"Description"="Oracle® Next Generation Java™ Plug-In"
"GeckoVersion"="1.9"
"Path"="C:\\Program Files (x86)\\Java\\jre8\\bin\\plugin2\\npjp2.dll"
"ProductName"="Oracle® Java™ Plug-In"
"Vendor"="Oracle Corp."
"Version"="1.8.0"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes]

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;jpi-version=1.8.0]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.1]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.1.1]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.1.2]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.1.3]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.2]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.2.1]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.3]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.3.1]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.4]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.4.1]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.4.2]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.5]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.6]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.7]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.8]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-vm]
"Description"="Java™ Virtual Machine"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-vm-npruntime]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin]
"Description"="Oracle® Next Generation Java™ Plug-In"
"GeckoVersion"="1.9"
"ProductName"="Oracle® Java™ Plug-In"
"Vendor"="Oracle Corp."
"Version"="160_29"
"Path"="C:\\Program Files\\Java\\jre8\\bin\\plugin2\\npjp2.dll"

What's the difference between ngOnInit and ngAfterViewInit of Angular2?

Content is what is passed as children. View is the template of the current component.

The view is initialized before the content and ngAfterViewInit() is therefore called before ngAfterContentInit().

** ngAfterViewInit() is called when the bindings of the children directives (or components) have been checked for the first time. Hence its perfect for accessing and manipulating DOM with Angular 2 components. As @Günter Zöchbauer mentioned before is correct @ViewChild() hence runs fine inside it.

Example:

@Component({
    selector: 'widget-three',
    template: `<input #input1 type="text">`
})
export class WidgetThree{
    @ViewChild('input1') input1;

    constructor(private renderer:Renderer){}

    ngAfterViewInit(){
        this.renderer.invokeElementMethod(
            this.input1.nativeElement,
            'focus',
            []
        )
    }
}

Can I convert long to int?

Sometimes you're not actually interested in the actual value, but in its usage as checksum/hashcode. In this case, the built-in method GetHashCode() is a good choice:

int checkSumAsInt32 = checkSumAsIn64.GetHashCode();

Count the occurrences of DISTINCT values

SELECT name,COUNT(*) as count 
FROM tablename 
GROUP BY name 
ORDER BY count DESC;

HTML text input allow only numeric input

If you are trying on angular this might help

To get the input as number (with a decimal point) then

<input [(ngModel)]="data" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">

Now this will not update the value in model correctly to explicitly change the value of model too add this

<input [(ngModel)]="data" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" (change)="data = $event.target.value">

The change event will fire after the value in the model has been updated so it can be used with reactive forms as well.

Regex matching beginning AND end strings

If you're searching for hits within a larger text, you don't want to use ^ and $ as some other responders have said; those match the beginning and end of the text. Try this instead:

\bdbo\.\w+_fn\b

\b is a word boundary: it matches a position that is either preceded by a word character and not followed by one, or followed by a word character and not preceded by one. This regex will find what you're looking for in any of these strings:

dbo.functionName_fn
foo dbo.functionName_fn bar
(dbo.functionName_fn)

...but not in this one:

foodbo.functionName_fnbar

\w+ matches one or more "word characters" (letters, digits, or _). If you need something more inclusive, you can try \S+ (one or more non-whitespace characters) or .+? (one or more of any characters except linefeeds, non-greedily). The non-greedy +? prevents it from accidentally matching something like dbo.func1_fn dbo.func2_fn as if it were just one hit.

React-Redux: Actions must be plain objects. Use custom middleware for async actions

You have to dispatch after the async request ends.

This would work:

export function bindComments(postId) {
    return function(dispatch) {
        return API.fetchComments(postId).then(comments => {
            // dispatch
            dispatch({
                type: BIND_COMMENTS,
                comments,
                postId
            });
        });
    };
}

How to parse XML to R data frame

Data in XML format are rarely organized in a way that would allow the xmlToDataFrame function to work. You're better off extracting everything in lists and then binding the lists together in a data frame:

require(XML)
data <- xmlParse("http://forecast.weather.gov/MapClick.php?lat=29.803&lon=-82.411&FcstType=digitalDWML")

xml_data <- xmlToList(data)

In the case of your example data, getting location and start time is fairly straightforward:

location <- as.list(xml_data[["data"]][["location"]][["point"]])

start_time <- unlist(xml_data[["data"]][["time-layout"]][
    names(xml_data[["data"]][["time-layout"]]) == "start-valid-time"])

Temperature data is a bit more complicated. First you need to get to the node that contains the temperature lists. Then you need extract both the lists, look within each one, and pick the one that has "hourly" as one of its values. Then you need to select only that list but only keep the values that have the "value" label:

temps <- xml_data[["data"]][["parameters"]]
temps <- temps[names(temps) == "temperature"]
temps <- temps[sapply(temps, function(x) any(unlist(x) == "hourly"))]
temps <- unlist(temps[[1]][sapply(temps, names) == "value"])

out <- data.frame(
  as.list(location),
  "start_valid_time" = start_time,
  "hourly_temperature" = temps)

head(out)
  latitude longitude          start_valid_time hourly_temperature
1    29.81    -82.42 2013-06-19T16:00:00-04:00                 91
2    29.81    -82.42 2013-06-19T17:00:00-04:00                 90
3    29.81    -82.42 2013-06-19T18:00:00-04:00                 89
4    29.81    -82.42 2013-06-19T19:00:00-04:00                 85
5    29.81    -82.42 2013-06-19T20:00:00-04:00                 83
6    29.81    -82.42 2013-06-19T21:00:00-04:00                 80

Plot 3D data in R

I use the lattice package for almost everything I plot in R and it has a corresponing plot to persp called wireframe. Let data be the way Sven defined it.

wireframe(z ~ x * y, data=data)

wireframe plot

Or how about this (modification of fig 6.3 in Deepanyan Sarkar's book):

p <- wireframe(z ~ x * y, data=data)
npanel <- c(4, 2)
rotx <- c(-50, -80)
rotz <- seq(30, 300, length = npanel[1]+1)
update(p[rep(1, prod(npanel))], layout = npanel,
    panel = function(..., screen) {
        panel.wireframe(..., screen = list(z = rotz[current.column()],
                                           x = rotx[current.row()]))
    })

Multiple wireframe plots using panel and update

Update: Plotting surfaces with OpenGL

Since this post continues to draw attention I want to add the OpenGL way to make 3-d plots too (as suggested by @tucson below). First we need to reformat the dataset from xyz-tripplets to axis vectors x and y and a matrix z.

x <- 1:5/10
y <- 1:5
z <- x %o% y
z <- z + .2*z*runif(25) - .1*z

library(rgl)
persp3d(x, y, z, col="skyblue")

rgl::persp3d

This image can be freely rotated and scaled using the mouse, or modified with additional commands, and when you are happy with it you save it using rgl.snapshot.

rgl.snapshot("myplot.png")

How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?

HTML:

<style>
#foo, #bar{
    width: 50px; /* use any width or height */
    height: 50px;
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
}
</style>

<div id="foo" style="background-image: url('path/to/image1.png');">
<div id="bar" style="background-image: url('path/to/image2.png');">

JSFiddle

...And if you want to set or change the image (using #foo as an example):

jQuery:

$("#foo").css("background-image", "url('path/to/image.png')");

JavaScript:

document.getElementById("foo").style.backgroundImage = "url('path/to/image.png')";

Anaconda-Navigator - Ubuntu16.04

it works :

export PATH=/home/yourUserName/anaconda3/bin:$PATH

after that run anaconda-navigator command. remember anaconda can't in Sudo mode, so don't use sudo at all.

Anaconda Running screenshot

Connection Java-MySql : Public Key Retrieval is not allowed

I was also facing such an issue while dockerizing our existing application. The solution si to add allowPublicKeyRetrieval connection option of MySQL with a value of true to the JDBC connection string. If that is not working , try adding useSSL option to false as well .

The resultant string would look like this :

jdbc:mysql://<database server ip>:3306/databaseName?allowPublicKeyRetrieval=true&useSSL=false

Bind class toggle to window scroll event

Why do you all suggest heavy scope operations? I don't see why this is not an "angular" solution:

.directive('changeClassOnScroll', function ($window) {
  return {
    restrict: 'A',
    scope: {
        offset: "@",
        scrollClass: "@"
    },
    link: function(scope, element) {
        angular.element($window).bind("scroll", function() {
            if (this.pageYOffset >= parseInt(scope.offset)) {
                element.addClass(scope.scrollClass);
            } else {
                element.removeClass(scope.scrollClass);
            }
        });
    }
  };
})

So you can use it like this:

<navbar change-class-on-scroll offset="500" scroll-class="you-have-scrolled-down"></navbar>

or

<div change-class-on-scroll offset="500" scroll-class="you-have-scrolled-down"></div>

Java URL encoding of query string parameters

URLEncoder is the way to go. You only need to keep in mind to encode only the individual query string parameter name and/or value, not the entire URL, for sure not the query string parameter separator character & nor the parameter name-value separator character =.

String q = "random word £500 bank $";
String url = "https://example.com?q=" + URLEncoder.encode(q, StandardCharsets.UTF_8);

When you're still not on Java 10 or newer, then use StandardCharsets.UTF_8.toString() as charset argument, or when you're still not on Java 7 or newer, then use "UTF-8".


Note that spaces in query parameters are represented by +, not %20, which is legitimately valid. The %20 is usually to be used to represent spaces in URI itself (the part before the URI-query string separator character ?), not in query string (the part after ?).

Also note that there are three encode() methods. One without Charset as second argument and another with String as second argument which throws a checked exception. The one without Charset argument is deprecated. Never use it and always specify the Charset argument. The javadoc even explicitly recommends to use the UTF-8 encoding, as mandated by RFC3986 and W3C.

All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the byte. The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used.

See also:

How do I write a "tab" in Python?

The Python reference manual includes several string literals that can be used in a string. These special sequences of characters are replaced by the intended meaning of the escape sequence.

Here is a table of some of the more useful escape sequences and a description of the output from them.

Escape Sequence       Meaning
\t                    Tab
\\                    Inserts a back slash (\)
\'                    Inserts a single quote (')
\"                    Inserts a double quote (")
\n                    Inserts a ASCII Linefeed (a new line)

Basic Example

If i wanted to print some data points separated by a tab space I could print this string.

DataString = "0\t12\t24"
print (DataString)

Returns

0    12    24

Example for Lists

Here is another example where we are printing the items of list and we want to sperate the items by a TAB.

DataPoints = [0,12,24]
print (str(DataPoints[0]) + "\t" + str(DataPoints[1]) + "\t" + str(DataPoints[2]))

Returns

0    12    24

Raw Strings

Note that raw strings (a string which include a prefix "r"), string literals will be ignored. This allows these special sequences of characters to be included in strings without being changed.

DataString = r"0\t12\t24"
print (DataString)

Returns

0\t12\t24

Which maybe an undesired output

String Lengths

It should also be noted that string literals are only one character in length.

DataString = "0\t12\t24"
print (len(DataString))

Returns

7

The raw string has a length of 9.

What is the difference between $routeProvider and $stateProvider?

Angular's own ng-Router takes URLs into consideration while routing, UI-Router takes states in addition to URLs.

States are bound to named, nested and parallel views, allowing you to powerfully manage your application's interface.

While in ng-router, you have to be very careful about URLs when providing links via <a href=""> tag, in UI-Router you have to only keep state in mind. You provide links like <a ui-sref="">. Note that even if you use <a href=""> in UI-Router, just like you would do in ng-router, it will still work.

So, even if you decide to change your URL some day, your state will remain same and you need to change URL only at .config.

While ngRouter can be used to make simple apps, UI-Router makes development much easier for complex apps. Here its wiki.

For loop in Objective-C

You mean fast enumeration? You question is very unclear.

A normal for loop would look a bit like this:

unsigned int i, cnt = [someArray count];
for(i = 0; i < cnt; i++)
{ 
   // do loop stuff
   id someObject = [someArray objectAtIndex:i];
}

And a loop with fast enumeration, which is optimized by the compiler, would look like this:

for(id someObject in someArray)
{
   // do stuff with object
}

Keep in mind that you cannot change the array you are using in fast enumeration, thus no deleting nor adding when using fast enumeration

MySQL Check if username and password matches in Database

1.) Storage of database passwords Use some kind of hash with a salt and then alter the hash, obfuscate it, for example add a distinct value for each byte. That way your passwords a super secured against dictionary attacks and rainbow tables.

2.) To check if the password matches, create your hash for the password the user put in. Then perform a query against the database for the username and just check if the two password hashes are identical. If they are, give the user an authentication token.

The query should then look like this:

select hashedPassword from users where username=?

Then compare the password to the input.

Further questions?

setImmediate vs. nextTick

Some great answers here detailing how they both work.

Just adding one that answers the specific question asked:

When should I use nextTick and when should I use setImmediate?


Always use setImmediate.


The Node.js Event Loop, Timers, and process.nextTick() doc includes the following:

We recommend developers use setImmediate() in all cases because it's easier to reason about (and it leads to code that's compatible with a wider variety of environments, like browser JS.)


Earlier in the doc it warns that process.nextTick can lead to...

some bad situations because it allows you to "starve" your I/O by making recursive process.nextTick() calls, which prevents the event loop from reaching the poll phase.

As it turns out, process.nextTick can even starve Promises:

Promise.resolve().then(() => { console.log('this happens LAST'); });

process.nextTick(() => {
  console.log('all of these...');
  process.nextTick(() => {
    console.log('...happen before...');
    process.nextTick(() => {
      console.log('...the Promise ever...');
      process.nextTick(() => {
        console.log('...has a chance to resolve');
      })
    })
  })
})

On the other hand, setImmediate is "easier to reason about" and avoids these types of issues:

Promise.resolve().then(() => { console.log('this happens FIRST'); });

setImmediate(() => {
  console.log('this happens LAST');
})

So unless there is a specific need for the unique behavior of process.nextTick, the recommended approach is to "use setImmediate() in all cases".

Recursively find files with a specific extension

find -name "*Robert*" \( -name "*.pdf" -o -name "*.jpg" \)

The -o repreents an OR condition and you can add as many as you wish within the braces. So this says to find all files containing the word "Robert" anywhere in their names and whose names end in either "pdf" or "jpg".

how do I use an enum value on a switch statement in C++

You're on the right track. You may read the user input into an integer and switch on that:

enum Choice
{
  EASY = 1, 
  MEDIUM = 2, 
  HARD = 3
};

int i = -1;

// ...<present the user with a menu>...

cin >> i;

switch(i)
{
  case EASY:
    cout << "Easy\n";
    break;
  case MEDIUM:
    cout << "Medium\n";
    break;
  case HARD:
    cout << "Hard\n";
    break;
  default:
    cout << "Invalid Selection\n";
    break;
}

Call PHP function from Twig template

I know this is an old thread. But with symfony 3.3 I did this:

{{ render(controller(
    'AppBundle\\Controller\\yourController::yourAction'
)) }}

Symfony docs

How can I check if a value is a json object?

Solution 3 (fastest way)

/**
 * @param Object
 * @returns boolean
 */
function isJSON (something) {
    if (typeof something != 'string')
        something = JSON.stringify(something);

    try {
        JSON.parse(something);
        return true;
    } catch (e) {
        return false;
    }
}

You can use it:

var myJson = [{"user":"chofoteddy"}, {"user":"bart"}];
isJSON(myJson); // true

The best way to validate that an object is of type JSON or array is as follows:

var a = [],
    o = {};

Solution 1

toString.call(o) === '[object Object]'; // true
toString.call(a) === '[object Array]'; // true

Solution 2

a.constructor.name === 'Array'; // true
o.constructor.name === 'Object'; // true

But, strictly speaking, an array is part of a JSON syntax. Therefore, the following two examples are part of a JSON response:

console.log(response); // {"message": "success"}
console.log(response); // {"user": "bart", "id":3}

And:

console.log(response); // [{"user":"chofoteddy"}, {"user":"bart"}]
console.log(response); // ["chofoteddy", "bart"]

AJAX / JQuery (recommended)

If you use JQuery to bring information via AJAX. I recommend you put in the "dataType" attribute the "json" value, that way if you get a JSON or not, JQuery validate it for you and make it known through their functions "success" and "error". Example:

$.ajax({
    url: 'http://www.something.com',
    data: $('#formId').serialize(),
    method: 'POST',
    dataType: 'json',
    // "sucess" will be executed only if the response status is 200 and get a JSON
    success: function (json) {},
    // "error" will run but receive state 200, but if you miss the JSON syntax
    error: function (xhr) {}
});

How to remove gem from Ruby on Rails application?

How about something like:

gem dependency devise --pipe | cut -d \  -f 1 | xargs gem uninstall -a

(this assumes that you're not using bundler - but I guess you're not since removing from your bundle gemspec would solve the problem)

How do I view an older version of an SVN file?

It is also interesting to compare the file of the current working revision with the same file of another revision.

You can do as follows:

$ svn diff -r34 file

How to display a "busy" indicator with jQuery?

yes, it's really just a matter of showing/hiding an animated gif.

Subclipse svn:ignore

It seems Subclipse only allows you to add a top-level folder to ignore list and not any sub folders under it. Not sure why it works this way. However, I found out by trial and error that if you directly add a sub-folder to version control, then it will allow you to add another folder at the same level to the ignore list.

alt text

For example, refer fig above, when I wanted to ignore the webapp folder without adding src, subclipse was not allowing me to do so. But when I added the java folder to version control, the "add to svn:ignore..." was enabled for webapp.

Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?

You'll need to decide how you'd like to handle exceptions thrown by the encrypt method.

Currently, encrypt is declared with throws Exception - however, in the body of the method, exceptions are caught in a try/catch block. I recommend you either:

  • remove the throws Exception clause from encrypt and handle exceptions internally (consider writing a log message at the very least); or,
  • remove the try/catch block from the body of encrypt, and surround the call to encrypt with a try/catch instead (i.e. in actionPerformed).

Regarding the compilation error you refer to: if an exception was thrown in the try block of encrypt, nothing gets returned after the catch block finishes. You could address this by initially declaring the return value as null:

public static byte[] encrypt(String toEncrypt) throws Exception{
  byte[] encrypted = null;
  try {
    // ...
    encrypted = ...
  }
  catch(Exception e){
    // ...
  }
  return encrypted;
}

However, if you can correct the bigger issue (the exception-handling strategy), this problem will take care of itself - particularly if you choose the second option I've suggested.

How to ssh connect through python Paramiko with ppk public key

@VonC's answer to a duplicate question:

If, as commented, Paraminko does not support PPK key, the official solution, as seen here, would be to use PuTTYgen.

But you can also use the Python library CkSshKey to make that same conversion directly in your program.

See "Convert PuTTY Private Key (ppk) to OpenSSH (pem)"

import sys
import chilkat

key = chilkat.CkSshKey()

#  Load an unencrypted or encrypted PuTTY private key.

#  If  your PuTTY private key is encrypted, set the Password
#  property before calling FromPuttyPrivateKey.
#  If your PuTTY private key is not encrypted, it makes no diffference
#  if Password is set or not set.
key.put_Password("secret")

#  First load the .ppk file into a string:

keyStr = key.loadText("putty_private_key.ppk")

#  Import into the SSH key object:
success = key.FromPuttyPrivateKey(keyStr)
if (success != True):
    print(key.lastErrorText())
    sys.exit()

#  Convert to an encrypted or unencrypted OpenSSH key.

#  First demonstrate converting to an unencrypted OpenSSH key

bEncrypt = False
unencryptedKeyStr = key.toOpenSshPrivateKey(bEncrypt)
success = key.SaveText(unencryptedKeyStr,"unencrypted_openssh.pem")
if (success != True):
    print(key.lastErrorText())
    sys.exit()