Programs & Examples On #Collectionbase

Operation is not valid due to the current state of the object, when I select a dropdown list

This can happen if you call

 .SingleOrDefault() 

on an IEnumerable with 2 or more elements.

Creating a blocking Queue<T> in .NET?

That looks very unsafe (very little synchronization); how about something like:

class SizeQueue<T>
{
    private readonly Queue<T> queue = new Queue<T>();
    private readonly int maxSize;
    public SizeQueue(int maxSize) { this.maxSize = maxSize; }

    public void Enqueue(T item)
    {
        lock (queue)
        {
            while (queue.Count >= maxSize)
            {
                Monitor.Wait(queue);
            }
            queue.Enqueue(item);
            if (queue.Count == 1)
            {
                // wake up any blocked dequeue
                Monitor.PulseAll(queue);
            }
        }
    }
    public T Dequeue()
    {
        lock (queue)
        {
            while (queue.Count == 0)
            {
                Monitor.Wait(queue);
            }
            T item = queue.Dequeue();
            if (queue.Count == maxSize - 1)
            {
                // wake up any blocked enqueue
                Monitor.PulseAll(queue);
            }
            return item;
        }
    }
}

(edit)

In reality, you'd want a way to close the queue so that readers start exiting cleanly - perhaps something like a bool flag - if set, an empty queue just returns (rather than blocking):

bool closing;
public void Close()
{
    lock(queue)
    {
        closing = true;
        Monitor.PulseAll(queue);
    }
}
public bool TryDequeue(out T value)
{
    lock (queue)
    {
        while (queue.Count == 0)
        {
            if (closing)
            {
                value = default(T);
                return false;
            }
            Monitor.Wait(queue);
        }
        value = queue.Dequeue();
        if (queue.Count == maxSize - 1)
        {
            // wake up any blocked enqueue
            Monitor.PulseAll(queue);
        }
        return true;
    }
}

org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

Go to the task manager, kill the java processes and turn the server back on. should work fine.

C++ for each, pulling from vector elements

C++ does not have the for_each loop feature in its syntax. You have to use c++11 or use the template function std::for_each.

struct Function {
    int input;
    Function(int input): input(input) {}
    void operator()(Attack& attack) {
        if(attack->m_num == input) attack->makeDamage();
    }
};
Function f(input);
std::for_each(m_attack.begin(), m_attack.end(), f);

Html code as IFRAME source rather than a URL

You can do this with a data URL. This includes the entire document in a single string of HTML. For example, the following HTML:

<html><body>foo</body></html>

can be encoded as this:

data:text/html;charset=utf-8,%3Chtml%3E%3Cbody%3Efoo%3C/body%3E%3C/html%3E

and then set as the src attribute of the iframe. Example.


Edit: The other alternative is to do this with Javascript. This is almost certainly the technique I'd choose. You can't guarantee how long a data URL the browser will accept. The Javascript technique would look something like this:

var iframe = document.getElementById('foo'),
    iframedoc = iframe.contentDocument || iframe.contentWindow.document;

iframedoc.body.innerHTML = 'Hello world';

Example


Edit 2 (December 2017): use the Html5's srcdoc attribute, just like in Saurabh Chandra Patel's answer, who now should be the accepted answer! If you can detect IE/Edge efficiently, a tip is to use srcdoc-polyfill library only for them and the "pure" srcdoc attribute in all non-IE/Edge browsers (check caniuse.com to be sure).

<iframe srcdoc="<html><body>Hello, <b>world</b>.</body></html>"></iframe>

How to get a URL parameter in Express?

This will work if your route looks like this: localhost:8888/p?tagid=1234

var tagId = req.query.tagid;
console.log(tagId); // outputs: 1234
console.log(req.query.tagid); // outputs: 1234

Otherwise use the following code if your route looks like this: localhost:8888/p/1234

var tagId = req.params.tagid;
console.log(tagId); // outputs: 1234
console.log(req.params.tagid); // outputs: 1234

The result of a query cannot be enumerated more than once

Try replacing this

var query = context.Search(id, searchText);

with

var query = context.Search(id, searchText).tolist();

and everything will work well.

std::string formatting like sprintf

Update of some answer around, difference is - function will properly accept std::string for %s

namespace format_helper
{

    template <class Src>
    inline Src cast(Src v)
    {
        return v;
    }

    inline const char *cast(const std::string& v)
    {
        return v.c_str();
    }
};

template <typename... Ts>
inline std::string stringfmt (const std::string &fmt, Ts&&... vs)
{
    using namespace format_helper;
    char b;
    size_t required = std::snprintf(&b, 0, fmt.c_str(), cast(std::forward<Ts>(vs))...);//not counting the terminating null character.
    std::string result;
    //because we use string as container, it adds extra 0 automatically
    result.resize(required , 0);
    //and snprintf will use n-1 bytes supplied
    std::snprintf(const_cast<char*>(result.data()), required + 1, fmt.c_str(), cast(std::forward<Ts>(vs))...);

    return result;
}

Live: http://cpp.sh/5ajsv

How to get the top position of an element?

var top = event.target.offsetTop + 'px';

Parent element top position like we are adding elemnt inside div

var rect = event.target.offsetParent;
         rect.offsetTop;

How to format numbers as currency string?

+1 to Jonathan M for providing the original method. Since this is explicitly a currency formatter, I went ahead and added the currency symbol (defaults to '$') to the output, and added a default comma as the thousands separator. If you don't actually want a currency symbol (or thousands separator), just use "" (empty string) as your argument for it.

Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator, currencySymbol) {
    // check the args and supply defaults:
    decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces;
    decSeparator = decSeparator == undefined ? "." : decSeparator;
    thouSeparator = thouSeparator == undefined ? "," : thouSeparator;
    currencySymbol = currencySymbol == undefined ? "$" : currencySymbol;

    var n = this,
        sign = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;

    return sign + currencySymbol + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
};

How to initialize a variable of date type in java?

To parse a Date from a String you can choose which format you would like it to have. For example:

public Date StringToDate(String s){

    Date result = null;
    try{
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        result  = dateFormat.parse(s);
    }

    catch(ParseException e){
        e.printStackTrace();

    }
    return result ;
}

If you would like to use this method now, you will have to use something like this

Date date = StringToDate("2015-12-06 17:03:00");

For more explanation you should check out http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Returning anonymous type in C#

Three options:

Option1:

public class TheRepresentativeType {
    public ... SomeVariable {get;set;}
    public ... AnotherVariable {get;set;}
}

public IEnumerable<TheRepresentativeType> TheMethod(SomeParameter)
{
   using (MyDC TheDC = new MyDC())
   {
     var TheQueryFromDB = (....
                           select new TheRepresentativeType{ SomeVariable = ....,
                                        AnotherVariable = ....}
                           ).ToList();

     return TheQueryFromDB;
   } 
}

Option 2:

public IEnumerable TheMethod(SomeParameter)
{
   using (MyDC TheDC = new MyDC())
   {
     var TheQueryFromDB = (....
                           select new TheRepresentativeType{ SomeVariable = ....,
                                        AnotherVariable = ....}
                           ).ToList();
     return TheQueryFromDB;
   } 
}

you can iterate it as object

Option 3:

public IEnumerable<dynamic> TheMethod(SomeParameter)
{
   using (MyDC TheDC = new MyDC())
   {
     var TheQueryFromDB = (....
                           select new TheRepresentativeType{ SomeVariable = ....,
                                        AnotherVariable = ....}
                           ).ToList();

     return TheQueryFromDB; //You may need to call .Cast<dynamic>(), but I'm not sure
   } 
}

and you will be able to iterate it as a dynamic object and access their properties directly

How to save SELECT sql query results in an array in C# Asp.net

Instead of any Array you can load your data in DataTable like:

using System.Data;

DataTable dt = new DataTable();
using (var con = new SqlConnection("Data Source=local;Initial Catalog=Test;Integrated Security=True"))
{
    using (var command = new SqlCommand("SELECT col1,col2" +
    {
        con.Open();
        using (SqlDataReader dr = command.ExecuteReader())
        {
            dt.Load(dr);
        }
    }
}

You can also use SqlDataAdapater to fill your DataTable like

SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(dt);

Later you can iterate each row and compare like:

foreach (DataRow dr in dt.Rows)
{
    if (dr.Field<string>("col1") == "yourvalue") //your condition
    {
    }
}

Looping over arrays, printing both index and value

You would find the array keys with "${!foo[@]}" (reference), so:

for i in "${!foo[@]}"; do 
  printf "%s\t%s\n" "$i" "${foo[$i]}"
done

Which means that indices will be in $i while the elements themselves have to be accessed via ${foo[$i]}

MVVM Passing EventArgs As Command Parameter

For people just finding this post, you should know that in newer versions (not sure on the exact version since official docs are slim on this topic) the default behavior of the InvokeCommandAction, if no CommandParameter is specified, is to pass the args of the event it's attached to as the CommandParameter. So the originals poster's XAML could be simply written as:

<i:Interaction.Triggers>
  <i:EventTrigger EventName="Navigated">
    <i:InvokeCommandAction Command="{Binding NavigatedEvent}"/>
  </i:EventTrigger>
</i:Interaction.Triggers>

Then in your command, you can accept a parameter of type NavigationEventArgs (or whatever event args type is appropriate) and it will automatically be provided.

What does random.sample() method in python do?

random.sample() also works on text

example:

> text = open("textfile.txt").read() 

> random.sample(text, 5)

> ['f', 's', 'y', 'v', '\n']

\n is also seen as a character so that can also be returned

you could use random.sample() to return random words from a text file if you first use the split method

example:

> words = text.split()

> random.sample(words, 5)

> ['the', 'and', 'a', 'her', 'of']

How to iterate over arguments in a Bash script

Note that Robert's answer is correct, and it works in sh as well. You can (portably) simplify it even further:

for i in "$@"

is equivalent to:

for i

I.e., you don't need anything!

Testing ($ is command prompt):

$ set a b "spaces here" d
$ for i; do echo "$i"; done
a
b
spaces here
d
$ for i in "$@"; do echo "$i"; done
a
b
spaces here
d

I first read about this in Unix Programming Environment by Kernighan and Pike.

In bash, help for documents this:

for NAME [in WORDS ... ;] do COMMANDS; done

If 'in WORDS ...;' is not present, then 'in "$@"' is assumed.

ssl.SSLError: tlsv1 alert protocol version

I encountered this exact issue when I attempted gem install bundler, and I was confused by all the Python responses (since I was using Ruby). Here was my exact error:

ERROR:  Could not find a valid gem 'bundler' (>= 0), here is why:
          Unable to download data from https://rubygems.org/ - SSL_connect returned=1 errno=0 state=SSLv2/v3 read server hello A: tlsv1 alert protocol version (https://rubygems.org/latest_specs.4.8.gz)

My solution: I updated Ruby to the most recent version (2.6.5). Problem solved.

Specifying maxlength for multiline textbox

Here's how we did it (keeps all code in one place):

<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine"/>
<% TextBox1.Attributes["maxlength"] = "1000"; %>

Just in case someone still using webforms in 2018..

How to count the number of occurrences of a character in an Oracle varchar value?

I justed faced very similar problem... BUT RegExp_Count couldn't resolved it. How many times string '16,124,3,3,1,0,' contains ',3,'? As we see 2 times, but RegExp_Count returns just 1. Same thing is with ''bbaaaacc' and when looking in it 'aa' - should be 3 times and RegExp_Count returns just 2.

select REGEXP_COUNT('336,14,3,3,11,0,' , ',3,') from dual;
select REGEXP_COUNT('bbaaaacc' , 'aa') from dual;

I lost some time to research solution on web. Couldn't' find... so i wrote my own function that returns TRUE number of occurance. Hope it will be usefull.

CREATE OR REPLACE FUNCTION EXPRESSION_COUNT( pEXPRESSION VARCHAR2, pPHRASE VARCHAR2 ) RETURN NUMBER AS
  vRET NUMBER := 0;
  vPHRASE_LENGTH NUMBER := 0;
  vCOUNTER NUMBER := 0;
  vEXPRESSION VARCHAR2(4000);
  vTEMP VARCHAR2(4000);
BEGIN
  vEXPRESSION := pEXPRESSION;
  vPHRASE_LENGTH := LENGTH( pPHRASE );
  LOOP
    vCOUNTER := vCOUNTER + 1;
    vTEMP := SUBSTR( vEXPRESSION, 1, vPHRASE_LENGTH);
    IF (vTEMP = pPHRASE) THEN        
        vRET := vRET + 1;
    END IF;
    vEXPRESSION := SUBSTR( vEXPRESSION, 2, LENGTH( vEXPRESSION ) - 1);
  EXIT WHEN ( LENGTH( vEXPRESSION ) = 0 ) OR (vEXPRESSION IS NULL);
  END LOOP;
  RETURN vRET;
END;

Example using Hyperlink in WPF

If you want your application to open the link in a web browser you need to add a HyperLink with the RequestNavigate event set to a function that programmatically opens a web-browser with the address as a parameter.

<TextBlock>           
    <Hyperlink NavigateUri="http://www.google.com" RequestNavigate="Hyperlink_RequestNavigate">
        Click here
    </Hyperlink>
</TextBlock>

In the code-behind you would need to add something similar to this to handle the RequestNavigate event:

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
    // for .NET Core you need to add UseShellExecute = true
    // see https://docs.microsoft.com/dotnet/api/system.diagnostics.processstartinfo.useshellexecute#property-value
    Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
    e.Handled = true;
}

In addition you will also need the following imports:

using System.Diagnostics;
using System.Windows.Navigation;

It will look like this in your application:

oO

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

I'm a PHP developer and to be able to work on my development environment with a certificate, I was able to do the same by finding the real SSL HTTPS/HTTP Certificate and deleting it.

The steps are :

  1. In the address bar, type "chrome://net-internals/#hsts".
  2. Type the domain name in the text field below "Delete domain".
  3. Click the "Delete" button.
  4. Type the domain name in the text field below "Query domain".
  5. Click the "Query" button.
  6. Your response should be "Not found".

You can find more information at : http://classically.me/blogs/how-clear-hsts-settings-major-browsers

Although this solution is not the best, Chrome currently does not have any good solution for the moment. I have escalated this situation with their support team to help improve user experience.

Edit : you have to repeat the steps every time you will go on the production site.

Private class declaration

You can't have private class but you can have second class:

public class App14692708 {
    public static void main(String[] args) {
        PC pc = new PC();
        System.out.println(pc);
    }
}

class PC {
    @Override
    public String toString() {
        return "I am PC instance " + super.toString();
    }
}

Also remember that static inner class is indistinguishable of separate class except it's name is OuterClass.InnerClass. So if you don't want to use "closures", use static inner class.

How to select all instances of selected region in Sublime Text

Note: You should not edit the default settings, because they get reset on updates/upgrades. For customization, you should override any setting by using the user bindings.

On Mac:

  • Sublime Text 2 > Preferences > Key Bindings-Default
  • Sublime Text 3 > Preferences > Key Bindings

This opens a document that you can edit the keybindings for Sublime.

If you search "ctrl+super+g" you find this:

{ "keys": ["ctrl+super+g"], "command": "find_all_under" },

Wpf control size to content?

I had a problem like this whereby I had specified the width of my Window, but had the height set to Auto. The child DockPanel had it's VerticalAlignment set to Top and the Window had it's VerticalContentAlignment set to Top, yet the Window would still be much taller than the contents.

Using Snoop, I discovered that the ContentPresenter within the Window (part of the Window, not something I had put there) has it's VerticalAlignment set to Stretch and can't be changed without retemplating the entire Window!

After a lot of frustration, I discovered the SizeToContent property - you can use this to specify whether you want the Window to size vertically, horizontally or both, according to the size of the contents - everything is sizing nicely now, I just can't believe it took me so long to find that property!

Could not load the Tomcat server configuration

I've just been encountering a very similar issue in Ubuntu while trying to get Eclipse Mars and Tomcat7 integrated because Eclipse was expecting the tomcat configuration files etc to be all in the same location, and with the necessary permissions to be able to change those files.

The following instructions from this blog article helped me in the end:

cd /usr/share/tomcat7
sudo ln -s /var/lib/tomcat7/conf conf
sudo ln -s /var/log/tomcat7 log
sudo ln -s /etc/tomcat7/policy.d/03catalina.policy conf/catalina.policy
sudo chmod -R a+rwx /usr/share/tomcat7/conf

Sublime text 3. How to edit multiple lines?

Select multiple lines by clicking first line then holding shift and clicking last line. Then press:

CTRL+SHIFT+L

or on MAC: CMD+SHIFT+L (as per comments)

Alternatively you can select lines and go to SELECTION MENU >> SPLIT INTO LINES.

Now you can edit multiple lines, move cursors etc. for all selected lines.

Transfer files to/from session I'm logged in with PuTTY

Same everyday problem.

I just created a simple vc project to solve this problem.

It copies the file as Base64 encoded data directly to the clipboard, and then this can be pasted into the PuTTY console and decoded on the remote side.

This solution is for relatively small files (relative to the connection speed to your remote console).

Installation:

Download clip_b64.exe and place it in the SendTo folder (or a .lnk shortcut to it). To open this folder, in the address bar of the explorer, enter shell:sendto or %appdata%\Microsoft\Windows\SendTo.

You may need to install VC 2017 redist to run it, or use the statically linked clip_b64s.exe execution.

Usage:

On the local machine:

In the File Explorer, right-click the file you are transferring to open the context menu, then go to the "Send To" section and select Clip_B64 from the list.

On the remote console (over putty-ssh link):

Run the shell command base64 -d > file-name-you-want and right-click in the console (or press Shift + Insert) to place the clipboard content in it, and then press Ctrl + D to finish.

voila

How to subtract X day from a Date object in Java?

Java 8 and later

With Java 8's date time API change, Use LocalDate

LocalDate date = LocalDate.now().minusDays(300);

Similarly you can have

LocalDate date = someLocalDateInstance.minusDays(300);

Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <--> java.time.LocalDateTime

Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());

Java 7 and earlier

Use Calendar's add() method

Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();

How to add icons to React Native app

I would use a service to scale the icon correctly. http://makeappicon.com/ seems good. Use a image on the larger size as scaling up a smaller image can lead to the larger icons being pixelated. That site will give you sizes for both iOS and Android.

From there its just a matter of setting the icon like you would a regular native app.

https://help.apple.com/xcode/mac/8.0/#/dev10510b1f7

Set icon for Android application

Simple (I think) Horizontal Line in WPF?

I had the same issue and eventually chose to use a Rectangle element:

<Rectangle HorizontalAlignment="Stretch" Fill="Blue" Height="4"/>

In my opinion it's somewhat easier to modify/shape than a separator. Of course the Separator is a very easy and neat solution for simple separations :)

sys.argv[1], IndexError: list index out of range

sys.argv is the list of command line arguments passed to a Python script, where sys.argv[0] is the script name itself.

It is erroring out because you are not passing any commandline argument, and thus sys.argv has length 1 and so sys.argv[1] is out of bounds.

To "fix", just make sure to pass a commandline argument when you run the script, e.g.

python ConcatenateFiles.py /the/path/to/the/directory

However, you likely wanted to use some default directory so it will still work when you don't pass in a directory:

cur_dir = sys.argv[1] if len(sys.argv) > 1 else '.'

with open(cur_dir + '/Concatenated.csv', 'w+') as outfile:

    try:
        with open(cur_dir + '/MatrixHeader.csv') as headerfile:
            for line in headerfile:
                outfile.write(line + '\n')
    except:
        print 'No Header File'

Could not establish trust relationship for SSL/TLS secure channel -- SOAP

Luke wrote a pretty good article about this .. pretty straight forward .. give this a try

Luke's Solution

Reason (quote from his article (minus cursing)) ".. The problem with the code above is that it doesn’t work if your certificate is not valid. Why would I be posting to a web page with and invalid SSL certificate? Because I’m cheap and I didn’t feel like paying Verisign or one of the other **-*s for a cert to my test box so I self signed it. When I sent the request I got a lovely exception thrown at me:

System.Net.WebException The underlying connection was closed. Could not establish trust relationship with remote server.

I don’t know about you, but to me that exception looked like something that would be caused by a silly mistake in my code that was causing the POST to fail. So I kept searching, and tweaking and doing all kinds of weird things. Only after I googled the ***n thing I found out that the default behavior after encountering an invalid SSL cert is to throw this very exception. .."

Update value of a nested dictionary of varying depth

Yes! And another solution. My solution differs in the keys that are being checked. In all other solutions we only look at the keys in dict_b. But here we look in the union of both dictionaries.

Do with it as you please

def update_nested(dict_a, dict_b):
    set_keys = set(dict_a.keys()).union(set(dict_b.keys()))
    for k in set_keys:
        v = dict_a.get(k)
        if isinstance(v, dict):
            new_dict = dict_b.get(k, None)
            if new_dict:
                update_nested(v, new_dict)
        else:
            new_value = dict_b.get(k, None)
            if new_value:
                dict_a[k] = new_value

How to get subarray from array?

Take a look at Array.slice(begin, end)

_x000D_
_x000D_
const ar  = [1, 2, 3, 4, 5];

// slice from 1..3 - add 1 as the end index is not included

const ar2 = ar.slice(1, 3 + 1);

console.log(ar2);
_x000D_
_x000D_
_x000D_

Store output of subprocess.Popen call in a string

This works perfectly for me:

import subprocess
try:
    #prints results and merges stdout and std
    result = subprocess.check_output("echo %USERNAME%", stderr=subprocess.STDOUT, shell=True)
    print result
    #causes error and merges stdout and stderr
    result = subprocess.check_output("copy testfds", stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError, ex: # error code <> 0 
    print "--------error------"
    print ex.cmd
    print ex.message
    print ex.returncode
    print ex.output # contains stdout and stderr together 

How do I read image data from a URL in Python?

I use the requests library. It seems to be more robust.

from PIL import Image
import requests
from StringIO import StringIO

response = requests.get(url)
img = Image.open(StringIO(response.content))

TypeError: 'function' object is not subscriptable - Python

You have two objects both named bank_holiday -- one a list and one a function. Disambiguate the two.

bank_holiday[month] is raising an error because Python thinks bank_holiday refers to the function (the last object bound to the name bank_holiday), whereas you probably intend it to mean the list.

"for" vs "each" in Ruby

As far as I know, using blocks instead of in-language control structures is more idiomatic.

Joining 2 SQL SELECT result sets into one

SELECT table1.col_a, table1.col_b, table2.col_c 
  FROM table1 
  INNER JOIN table2 ON table1.col_a = table2.col_a

Switching the order of block elements with CSS

Hows this for low tech...

put the ad at the top and bottom and use media queries to display:none as appropriate.

If the ad wasn't too big, it wouldn't add too much size to the download, you could even customise where the ad sent you for iPhone/pc.

Place API key in Headers or URL

passing api key in parameters makes it difficult for clients to keep their APIkeys secret, they tend to leak keys on a regular basis. A better approach is to pass it in header of request url.you can set user-key header in your code . For testing your request Url you can use Postman app in google chrome by setting user-key header to your api-key.

Passing Variable through JavaScript from one html page to another page

Without reading your code but just your scenario, I would solve by using localStorage. Here's an example, I'll use prompt() for short.

On page1:

window.onload = function() {
   var getInput = prompt("Hey type something here: ");
   localStorage.setItem("storageName",getInput);
}

On page2:

window.onload = alert(localStorage.getItem("storageName"));

You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.

javascript - match string against the array of regular expressions

So we make a function that takes in a literal string, and the array we want to look through. it returns a new array with the matches found. We create a new regexp object inside this function and then execute a String.search on each element element in the array. If found, it pushes the string into a new array and returns.

// literal_string: a regex search, like /thisword/ig
// target_arr: the array you want to search /thisword/ig for.

function arr_grep(literal_string, target_arr) {
  var match_bin = [];
  // o_regex: a new regex object.
  var o_regex = new RegExp(literal_string);
  for (var i = 0; i < target_arr.length; i++) {
    //loop through array. regex search each element.
    var test = String(target_arr[i]).search(o_regex);
    if (test > -1) {
    // if found push the element@index into our matchbin.
    match_bin.push(target_arr[i]);
    }
  }
  return match_bin;
}

// arr_grep(/.*this_word.*/ig, someArray)

Reset the database (purge all), then seed a database

I use rake db:reset which drops and then recreates the database and includes your seeds.rb file. http://guides.rubyonrails.org/migrations.html#resetting-the-database

How to play a notification sound on websites?

if you want calling event on the code The best way to do that is to create trigger because the browser will not respond if the user is not on the page

<button type="button" style="display:none" id="playSoundBtn" onclick="playSound();"></button>

now you can trigger your button when you want to play sound

$('#playSoundBtn').trigger('click');

Random / noise functions for GLSL

A straight, jagged version of 1d Perlin, essentially a random lfo zigzag.

half  rn(float xx){         
    half x0=floor(xx);
    half x1=x0+1;
    half v0 = frac(sin (x0*.014686)*31718.927+x0);
    half v1 = frac(sin (x1*.014686)*31718.927+x1);          

    return (v0*(1-frac(xx))+v1*(frac(xx)))*2-1*sin(xx);
}

I also have found 1-2-3-4d perlin noise on shadertoy owner inigo quilez perlin tutorial website, and voronoi and so forth, he has full fast implementations and codes for them.

Passing Parameters JavaFX FXML

javafx.scene.Node class has a pair of methods setUserData(Object) and Object getUserData()

Which you could use to add your info to the Node.

So, you can call page.setUserData(info);

And controller can check, if info is set. Also, you could use ObjectProperty for back-forward data transfering, if needed.

Observe a documentation here: http://docs.oracle.com/javafx/2/api/javafx/fxml/doc-files/introduction_to_fxml.html Before the phrase "In the first version, the handleButtonAction() is tagged with @FXML to allow markup defined in the controller's document to invoke it. In the second example, the button field is annotated to allow the loader to set its value. The initialize() method is similarly annotated."

So, you need to associate a controller with a node, and set a user data to the node.

Iterator Loop vs index loop

The special thing about iterators is that they provide the glue between algorithms and containers. For generic code, the recommendation would be to use a combination of STL algorithms (e.g. find, sort, remove, copy) etc. that carries out the computation that you have in mind on your data structure (vector, list, map etc.), and to supply that algorithm with iterators into your container.

Your particular example could be written as a combination of the for_each algorithm and the vector container (see option 3) below), but it's only one out of four distinct ways to iterate over a std::vector:

1) index-based iteration

for (std::size_t i = 0; i != v.size(); ++i) {
    // access element as v[i]

    // any code including continue, break, return
}

Advantages: familiar to anyone familiar with C-style code, can loop using different strides (e.g. i += 2).

Disadvantages: only for sequential random access containers (vector, array, deque), doesn't work for list, forward_list or the associative containers. Also the loop control is a little verbose (init, check, increment). People need to be aware of the 0-based indexing in C++.

2) iterator-based iteration

for (auto it = v.begin(); it != v.end(); ++it) {
    // if the current index is needed:
    auto i = std::distance(v.begin(), it); 

    // access element as *it

    // any code including continue, break, return
}

Advantages: more generic, works for all containers (even the new unordered associative containers, can also use different strides (e.g. std::advance(it, 2));

Disadvantages: need extra work to get the index of the current element (could be O(N) for list or forward_list). Again, the loop control is a little verbose (init, check, increment).

3) STL for_each algorithm + lambda

std::for_each(v.begin(), v.end(), [](T const& elem) {
     // if the current index is needed:
     auto i = &elem - &v[0];

     // cannot continue, break or return out of the loop
});

Advantages: same as 2) plus small reduction in loop control (no check and increment), this can greatly reduce your bug rate (wrong init, check or increment, off-by-one errors).

Disadvantages: same as explicit iterator-loop plus restricted possibilities for flow control in the loop (cannot use continue, break or return) and no option for different strides (unless you use an iterator adapter that overloads operator++).

4) range-for loop

for (auto& elem: v) {
     // if the current index is needed:
     auto i = &elem - &v[0];

    // any code including continue, break, return
}

Advantages: very compact loop control, direct access to the current element.

Disadvantages: extra statement to get the index. Cannot use different strides.

What to use?

For your particular example of iterating over std::vector: if you really need the index (e.g. access the previous or next element, printing/logging the index inside the loop etc.) or you need a stride different than 1, then I would go for the explicitly indexed-loop, otherwise I'd go for the range-for loop.

For generic algorithms on generic containers I'd go for the explicit iterator loop unless the code contained no flow control inside the loop and needed stride 1, in which case I'd go for the STL for_each + a lambda.

round up to 2 decimal places in java?

I know this is 2 year old question but as every body faces a problem to round off the values at some point of time.I would like to share a different way which can give us rounded values to any scale by using BigDecimal class .Here we can avoid extra steps which are required to get the final value if we use DecimalFormat("0.00") or using Math.round(a * 100) / 100 .

import java.math.BigDecimal;

public class RoundingNumbers {
    public static void main(String args[]){
        double number = 123.13698;
        int decimalsToConsider = 2;
        BigDecimal bigDecimal = new BigDecimal(number);
        BigDecimal roundedWithScale = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println("Rounded value with setting scale = "+roundedWithScale);

        bigDecimal = new BigDecimal(number);
        BigDecimal roundedValueWithDivideLogic = bigDecimal.divide(BigDecimal.ONE,decimalsToConsider,BigDecimal.ROUND_HALF_UP);
        System.out.println("Rounded value with Dividing by one = "+roundedValueWithDivideLogic);

    }
}

This program would give us below output

Rounded value with setting scale = 123.14
Rounded value with Dividing by one = 123.14

Remove git mapping in Visual Studio 2015

In addition to Juliano Nunes Silva Oliveira's answer, the simplest and most clean way without hacking into the regedit, removing hidden .git folders or changing your VS15 settings is by connecting to a different repository. When connected you see the text of the other repository bold then select your Git local repository. Now you see that the

Remove

menu item is enabled so you are able to delete your Git local repository.

It's the same type of behaviour when dealing with Branches when using Git with visual studio 2015. You need to select different branch before you can delete the branch you wan to delete.

For the ones who needs visualization to understand it better. see link image: how it's done

Happy coding

Rewrite all requests to index.php with nginx

Here is what worked for me to solve part 1 of this question:

    location / {
            rewrite ^([^.]*[^/])$ $1/ permanent;
            try_files $uri $uri/ /index.php =404;
            include fastcgi_params;
            fastcgi_pass php5-fpm-sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_intercept_errors on;
    }

rewrite ^([^.]*[^/])$ $1/ permanent; rewrites non-file addresses (addresses without file extensions) to have a "/" at the end. I did this because I was running into "Access denied." message when I tried to access the folder without it.

try_files $uri $uri/ /index.php =404; is borrowed from SanjuD's answer, but with an extra 404 reroute if the location still isn't found.

fastcgi_index index.php; was the final piece of the puzzle that I was missing. The folder didn't reroute to the index.php without this line.

What is the correct way of reading from a TCP socket in C/C++?

If you actually create the buffer as per dirks suggestion, then:

  int readResult = read(socketFileDescriptor, buffer, BUFFER_SIZE);

may completely fill the buffer, possibly overwriting the terminating zero character which you depend on when extracting to a stringstream. You need:

  int readResult = read(socketFileDescriptor, buffer, BUFFER_SIZE - 1 );

Error: 'int' object is not subscriptable - Python

The problem is in the line,

int([x[age1]])

What you want is

x = int(age1)

You also need to convert the int to a string for the output...

print "Hi, " + name1+ " you will be 21 in: " + str(twentyone) + " years."

The complete script looks like,

name1 = raw_input("What's your name? ")
age1 = raw_input ("how old are you? ")
x = 0
x = int(age1)
twentyone = 21 - x
print "Hi, " + name1+ " you will be 21 in: " + str(twentyone) + " years."

How would you implement an LRU cache in Java?

Here is my implementation for LRU. I have used PriorityQueue, which basically works as FIFO and not threadsafe. Used Comparator based on the page time creation and based on the performs the ordering of the pages for the least recently used time.

Pages for consideration : 2, 1, 0, 2, 8, 2, 4

Page added into cache is : 2
Page added into cache is : 1
Page added into cache is : 0
Page: 2 already exisit in cache. Last accessed time updated
Page Fault, PAGE: 1, Replaced with PAGE: 8
Page added into cache is : 8
Page: 2 already exisit in cache. Last accessed time updated
Page Fault, PAGE: 0, Replaced with PAGE: 4
Page added into cache is : 4

OUTPUT

LRUCache Pages
-------------
PageName: 8, PageCreationTime: 1365957019974
PageName: 2, PageCreationTime: 1365957020074
PageName: 4, PageCreationTime: 1365957020174

enter code here

import java.util.Comparator;
import java.util.Iterator;
import java.util.PriorityQueue;


public class LRUForCache {
    private PriorityQueue<LRUPage> priorityQueue = new PriorityQueue<LRUPage>(3, new LRUPageComparator());
    public static void main(String[] args) throws InterruptedException {

        System.out.println(" Pages for consideration : 2, 1, 0, 2, 8, 2, 4");
        System.out.println("----------------------------------------------\n");

        LRUForCache cache = new LRUForCache();
        cache.addPageToQueue(new LRUPage("2"));
        Thread.sleep(100);
        cache.addPageToQueue(new LRUPage("1"));
        Thread.sleep(100);
        cache.addPageToQueue(new LRUPage("0"));
        Thread.sleep(100);
        cache.addPageToQueue(new LRUPage("2"));
        Thread.sleep(100);
        cache.addPageToQueue(new LRUPage("8"));
        Thread.sleep(100);
        cache.addPageToQueue(new LRUPage("2"));
        Thread.sleep(100);
        cache.addPageToQueue(new LRUPage("4"));
        Thread.sleep(100);

        System.out.println("\nLRUCache Pages");
        System.out.println("-------------");
        cache.displayPriorityQueue();
    }


    public synchronized void  addPageToQueue(LRUPage page){
        boolean pageExists = false;
        if(priorityQueue.size() == 3){
            Iterator<LRUPage> iterator = priorityQueue.iterator();

            while(iterator.hasNext()){
                LRUPage next = iterator.next();
                if(next.getPageName().equals(page.getPageName())){
                    /* wanted to just change the time, so that no need to poll and add again.
                       but elements ordering does not happen, it happens only at the time of adding
                       to the queue

                       In case somebody finds it, plz let me know.
                     */
                    //next.setPageCreationTime(page.getPageCreationTime()); 

                    priorityQueue.remove(next);
                    System.out.println("Page: " + page.getPageName() + " already exisit in cache. Last accessed time updated");
                    pageExists = true;
                    break;
                }
            }
            if(!pageExists){
                // enable it for printing the queue elemnts
                //System.out.println(priorityQueue);
                LRUPage poll = priorityQueue.poll();
                System.out.println("Page Fault, PAGE: " + poll.getPageName()+", Replaced with PAGE: "+page.getPageName());

            }
        }
        if(!pageExists){
            System.out.println("Page added into cache is : " + page.getPageName());
        }
        priorityQueue.add(page);

    }

    public void displayPriorityQueue(){
        Iterator<LRUPage> iterator = priorityQueue.iterator();
        while(iterator.hasNext()){
            LRUPage next = iterator.next();
            System.out.println(next);
        }
    }
}

class LRUPage{
    private String pageName;
    private long pageCreationTime;
    public LRUPage(String pagename){
        this.pageName = pagename;
        this.pageCreationTime = System.currentTimeMillis();
    }

    public String getPageName() {
        return pageName;
    }

    public long getPageCreationTime() {
        return pageCreationTime;
    }

    public void setPageCreationTime(long pageCreationTime) {
        this.pageCreationTime = pageCreationTime;
    }

    @Override
    public boolean equals(Object obj) {
        LRUPage page = (LRUPage)obj; 
        if(pageCreationTime == page.pageCreationTime){
            return true;
        }
        return false;
    }

    @Override
    public int hashCode() {
        return (int) (31 * pageCreationTime);
    }

    @Override
    public String toString() {
        return "PageName: " + pageName +", PageCreationTime: "+pageCreationTime;
    }
}


class LRUPageComparator implements Comparator<LRUPage>{

    @Override
    public int compare(LRUPage o1, LRUPage o2) {
        if(o1.getPageCreationTime() > o2.getPageCreationTime()){
            return 1;
        }
        if(o1.getPageCreationTime() < o2.getPageCreationTime()){
            return -1;
        }
        return 0;
    }
}

How to keep one variable constant with other one changing with row in excel

=(B0+4)/($A$0)

$ means keep same (press a few times F4 after typing A4 to flip through combos quick!)

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

This is to synchronize IOs from C and C++ world. If you synchronize, then you have a guaranty that the orders of all IOs is exactly what you expect. In general, the problem is the buffering of IOs that causes the problem, synchronizing let both worlds to share the same buffers. For example cout << "Hello"; printf("World"); cout << "Ciao";; without synchronization you'll never know if you'll get HelloCiaoWorld or HelloWorldCiao or WorldHelloCiao...

tie lets you have the guaranty that IOs channels in C++ world are tied one to each other, which means for example that every output have been flushed before inputs occurs (think about cout << "What's your name ?"; cin >> name;).

You can always mix C or C++ IOs, but if you want some reasonable behavior you must synchronize both worlds. Beware that in general it is not recommended to mix them, if you program in C use C stdio, and if you program in C++ use streams. But you may want to mix existing C libraries into C++ code, and in such a case it is needed to synchronize both.

How do I escape a percentage sign in T-SQL?

In MySQL,

WHERE column_name LIKE '%|%%' ESCAPE '|'

PHP convert date format dd/mm/yyyy => yyyy-mm-dd

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. Check more here.

Use the default date function.

$var = "20/04/2012";
echo date("Y-m-d", strtotime($var) );

EDIT I just tested it, and somehow, PHP doesn't work well with dd/mm/yyyy format. Here's another solution.

$var = '20/04/2012';
$date = str_replace('/', '-', $var);
echo date('Y-m-d', strtotime($date));

Get a worksheet name using Excel VBA

This works for me.

worksheetName = ActiveSheet.Name  

Angular 5 - Copy to clipboard

Use navigator.clipboard.writeText to copy the content to clipboard

navigator.clipboard.writeText(content).then().catch(e => console.error(e));

scp files from local to remote machine error: no such file or directory

i had a kind of similar problem. i tried to copy from a server to my desktop and always got the same message for the local path. the problem was, i already was logged in to my server per ssh, so it was searching for the local path in the server path.

solution: i had to log out and run the command again and it worked

How/when to use ng-click to call a route?

You can use:

<a ng-href="#/about">About</a>

If you want some dynamic variable inside href you can do like this way:

<a ng-href="{{link + 123}}">Link to 123</a>

Where link is Angular scope variable.

How to get the current date and time of your timezone in Java?

With the java.time classes built into Java 8 and later:

public static void main(String[] args) {
        LocalDateTime localNow = LocalDateTime.now(TimeZone.getTimeZone("Europe/Madrid").toZoneId());
        System.out.println(localNow);
        // Prints current time of given zone without zone information : 2016-04-28T15:41:17.611
        ZonedDateTime zoneNow = ZonedDateTime.now(TimeZone.getTimeZone("Europe/Madrid").toZoneId());
        System.out.println(zoneNow);
        // Prints current time of given zone with zone information : 2016-04-28T15:41:17.627+02:00[Europe/Madrid]
    }

How do I print to the debug output window in a Win32 app?

I was looking for a way to do this myself and figured out a simple solution.

I'm assuming that you started a default Win32 Project (Windows application) in Visual Studio, which provides a "WinMain" function. By default, Visual Studio sets the entry point to "SUBSYSTEM:WINDOWS". You need to first change this by going to:

Project -> Properties -> Linker -> System -> Subsystem

And select "Console (/SUBSYSTEM:CONSOLE)" from the drop-down list.

Now, the program will not run, since a "main" function is needed instead of the "WinMain" function.

So now you can add a "main" function like you normally would in C++. After this, to start the GUI program, you can call the "WinMain" function from inside the "main" function.

The starting part of your program should now look something like this:

#include <iostream>

using namespace std;

// Main function for the console
int main(){

    // Calling the wWinMain function to start the GUI program
    // Parameters:
    // GetModuleHandle(NULL) - To get a handle to the current instance
    // NULL - Previous instance is not needed
    // NULL - Command line parameters are not needed
    // 1 - To show the window normally
    wWinMain(GetModuleHandle(NULL), NULL,NULL, 1); 

    system("pause");
    return 0;
}

// Function for entry into GUI program
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPWSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
    // This will display "Hello World" in the console as soon as the GUI begins.
    cout << "Hello World" << endl;
.
.
.

Result of my implementation

Now you can use functions to output to the console in any part of your GUI program for debugging or other purposes.

Why can't static methods be abstract in Java?

I see that there are a god-zillion answers already but I don't see any practical solutions. Of course this is a real problem and there is no good reason for excluding this syntax in Java. Since the original question lacks a context where this may be need, I provide both a context and a solution:

Suppose you have a static method in a bunch of classes that are identical. These methods call a static method that is class specific:

class C1 {
    static void doWork() {
        ...
        for (int k: list)
            doMoreWork(k);
        ...
    }
    private static void doMoreWork(int k) {
        // code specific to class C1
    }
}
class C2 {
    static void doWork() {
        ...
        for (int k: list)
            doMoreWork(k);
        ...
    }
    private static void doMoreWork(int k) {
        // code specific to class C2
    }
}

doWork() methods in C1 and C2 are identical. There may be a lot of these calsses: C3 C4 etc. If static abstract was allowed, you'd eliminate the duplicate code by doing something like:

abstract class C {
    static void doWork() {
        ...
        for (int k: list)
            doMoreWork(k);
        ...
    }

    static abstract void doMoreWork(int k);
}

class C1 extends C {
    private static void doMoreWork(int k) {
        // code for class C1
    }
}

class C2 extends C {
    private static void doMoreWork(int k) {
        // code for class C2
    }
}

but this would not compile because static abstract combination is not allowed. However, this can be circumvented with static class construct, which is allowed:

abstract class C {
    void doWork() {
        ...
        for (int k: list)
            doMoreWork(k);
        ...
    }
    abstract void doMoreWork(int k);
}
class C1 {
    private static final C c = new  C(){  
        @Override void doMoreWork(int k) {
            System.out.println("code for C1");
        }
    };
    public static void doWork() {
        c.doWork();
    }
}
class C2 {
    private static final C c = new C() {
        @Override void doMoreWork(int k) {
            System.out.println("code for C2");
        }
    };
    public static void doWork() {
        c.doWork();
    }
}

With this solution the only code that is duplicated is

    public static void doWork() {
        c.doWork();
    }

How to remove duplicate objects in a List<MyObject> without equals/hashcode?

You can use distinct to remove duplicates

List<Blog> blogList = ....// add your list here

blogList.stream().distinct().collect(Collectors.toList());

How to create a hex dump of file containing only the hex characters without spaces in bash?

Format strings can make hexdump behave exactly as you want it to (no whitespace at all, byte by byte):

hexdump -ve '1/1 "%.2x"'

1/1 means "each format is applied once and takes one byte", and "%.2x" is the actual format string, like in printf. In this case: 2-character hexadecimal number, leading zeros if shorter.

What is a stack trace, and how can I use it to debug my application errors?

There is one more stacktrace feature offered by Throwable family - the possibility to manipulate stack trace information.

Standard behavior:

package test.stack.trace;

public class SomeClass {

    public void methodA() {
        methodB();
    }

    public void methodB() {
        methodC();
    }

    public void methodC() {
        throw new RuntimeException();
    }

    public static void main(String[] args) {
        new SomeClass().methodA();
    }
}

Stack trace:

Exception in thread "main" java.lang.RuntimeException
    at test.stack.trace.SomeClass.methodC(SomeClass.java:18)
    at test.stack.trace.SomeClass.methodB(SomeClass.java:13)
    at test.stack.trace.SomeClass.methodA(SomeClass.java:9)
    at test.stack.trace.SomeClass.main(SomeClass.java:27)

Manipulated stack trace:

package test.stack.trace;

public class SomeClass {

    ...

    public void methodC() {
        RuntimeException e = new RuntimeException();
        e.setStackTrace(new StackTraceElement[]{
                new StackTraceElement("OtherClass", "methodX", "String.java", 99),
                new StackTraceElement("OtherClass", "methodY", "String.java", 55)
        });
        throw e;
    }

    public static void main(String[] args) {
        new SomeClass().methodA();
    }
}

Stack trace:

Exception in thread "main" java.lang.RuntimeException
    at OtherClass.methodX(String.java:99)
    at OtherClass.methodY(String.java:55)

Unordered List (<ul>) default indent

If you don't want indention in your list and also don't care about or don't want bullets, there is the CSS-free option of using a "definition list" (HTML 4.01) or "description list" (HTML 5). Use only the non-indenting definition <dt> tags, but not the indenting description <dd> tags, neither of which produces a bullet.

<dl>
  <dt>Item 1</dt>
  <dt>Item 2</dt>
  <dt>Item 3</dt>
</dl>

The output looks like this:

Item 1
Item 2
Item 3

Switch php versions on commandline ubuntu 16.04

I made a bash script to switch between different PHP versions on Ubuntu.

Hope it helps someone.

Here's the script: (save it in /usr/local/bin/sphp.sh, don't forget to add +x flag with command: sudo chmod +x /usr/local/bin/sphp.sh)

_x000D_
_x000D_
#!/bin/bash_x000D_
_x000D_
# Usage_x000D_
if [ $# -ne 1 ]; then_x000D_
  echo "Usage: sphp [phpversion]"_x000D_
  echo "Example: sphp 7.2"_x000D_
  exit 1_x000D_
fi_x000D_
_x000D_
currentversion="`php -r \"error_reporting(0); echo str_replace('.', '', substr(phpversion(), 0, 3));\"`"_x000D_
newversion="$1"_x000D_
_x000D_
majorOld=${currentversion:0:1}_x000D_
minorOld=${currentversion:1:1}_x000D_
majorNew=${newversion:0:1}_x000D_
minorNew=${newversion:2:1}_x000D_
_x000D_
if [ $? -eq 0 ]; then_x000D_
  if [ "${newversion}" == "${currentversion}" ]; then_x000D_
    echo "PHP version [${newversion}] is already being used"_x000D_
    exit 1_x000D_
  fi_x000D_
_x000D_
  echo "PHP version [$newversion] found"_x000D_
  echo "Switching from [php${currentversion}] to [php${newversion}] ... "_x000D_
_x000D_
  printf "a2dismod php$majorOld.$minorOld ... "_x000D_
  sudo a2dismod "php${majorOld}.${minorOld}"_x000D_
  printf "[OK] and "_x000D_
_x000D_
  printf "a2enmod php${newversion} ... "_x000D_
  sudo a2enmod "php${majorNew}.${minorNew}"_x000D_
  printf "[OK]\n"_x000D_
_x000D_
  printf "update-alternatives ... "_x000D_
  sudo update-alternatives --set php "/usr/bin/php${majorNew}.${minorNew}"_x000D_
  printf "[OK]\n"_x000D_
_x000D_
  sudo service apache2 restart_x000D_
  printf "[OK] apache2 restarted\n"_x000D_
else_x000D_
  echo "PHP version $majorNew.$minorNew was not found."_x000D_
  echo "Try \`sudo apt install php@${newversion}\` first."_x000D_
  exit 1_x000D_
fi_x000D_
_x000D_
echo "DONE!"
_x000D_
_x000D_
_x000D_

Ordering by the order of values in a SQL IN() clause

Ans to get sorted data.

SELECT ...
FROM ...
ORDER  BY FIELD(user_id,5,3,2,...,50)  LIMIT 10

Can someone explain Microsoft Unity?

I am covering most of the examples of Dependency Injection in ASP.NET Web API 2

public interface IShape
{
    string Name { get; set; }
}

public class NoShape : IShape
{
    public string Name { get; set; } = "I have No Shape";
}

public class Circle : IShape
{
    public string Name { get; set; } = "Circle";
}

public class Rectangle : IShape
{
    public Rectangle(string name)
    {
        this.Name = name;
    }

    public string Name { get; set; } = "Rectangle";
}

In DIAutoV2Controller.cs Auto Injection mechanism is used

[RoutePrefix("api/v2/DIAutoExample")]
public class DIAutoV2Controller : ApiController
{
    private string ConstructorInjected;
    private string MethodInjected1;
    private string MethodInjected2;
    private string MethodInjected3;

    [Dependency]
    public IShape NoShape { get; set; }

    [Dependency("Circle")]
    public IShape ShapeCircle { get; set; }

    [Dependency("Rectangle")]
    public IShape ShapeRectangle { get; set; }

    [Dependency("PiValueExample1")]
    public double PiValue { get; set; }

    [InjectionConstructor]
    public DIAutoV2Controller([Dependency("Circle")]IShape shape1, [Dependency("Rectangle")]IShape shape2, IShape shape3)
    {
        this.ConstructorInjected = shape1.Name + " & " + shape2.Name + " & " + shape3.Name;
    }

    [NonAction]
    [InjectionMethod]
    public void Initialize()
    {
        this.MethodInjected1 = "Default Initialize done";
    }

    [NonAction]
    [InjectionMethod]
    public void Initialize2([Dependency("Circle")]IShape shape1)
    {
        this.MethodInjected2 = shape1.Name;
    }

    [NonAction]
    [InjectionMethod]
    public void Initialize3(IShape shape1)
    {
        this.MethodInjected3 = shape1.Name;
    }

    [HttpGet]
    [Route("constructorinjection")]
    public string constructorinjection()
    {
        return "Constructor Injected: " + this.ConstructorInjected;
    }

    [HttpGet]
    [Route("GetNoShape")]
    public string GetNoShape()
    {
        return "Property Injected: " + this.NoShape.Name;
    }

    [HttpGet]
    [Route("GetShapeCircle")]
    public string GetShapeCircle()
    {
        return "Property Injected: " + this.ShapeCircle.Name;
    }

    [HttpGet]
    [Route("GetShapeRectangle")]
    public string GetShapeRectangle()
    {
        return "Property Injected: " + this.ShapeRectangle.Name;
    }

    [HttpGet]
    [Route("GetPiValue")]
    public string GetPiValue()
    {
        return "Property Injected: " + this.PiValue;
    }

    [HttpGet]
    [Route("MethodInjected1")]
    public string InjectionMethod1()
    {
        return "Method Injected: " + this.MethodInjected1;
    }

    [HttpGet]
    [Route("MethodInjected2")]
    public string InjectionMethod2()
    {
        return "Method Injected: " + this.MethodInjected2;
    }

    [HttpGet]
    [Route("MethodInjected3")]
    public string InjectionMethod3()
    {
        return "Method Injected: " + this.MethodInjected3;
    }
}

In DIV2Controller.cs everything will be injected from the Dependency Configuration Resolver class

[RoutePrefix("api/v2/DIExample")]
public class DIV2Controller : ApiController
{
    private string ConstructorInjected;
    private string MethodInjected1;
    private string MethodInjected2;
    public string MyPropertyName { get; set; }
    public double PiValue1 { get; set; }
    public double PiValue2 { get; set; }
    public IShape Shape { get; set; }

    // MethodInjected
    [NonAction]
    public void Initialize()
    {
        this.MethodInjected1 = "Default Initialize done";
    }

    // MethodInjected
    [NonAction]
    public void Initialize2(string myproperty1, IShape shape1, string myproperty2, IShape shape2)
    {
        this.MethodInjected2 = myproperty1 + " & " + shape1.Name + " & " + myproperty2 + " & " + shape2.Name;
    }

    public DIV2Controller(string myproperty1, IShape shape1, string myproperty2, IShape shape2)
    {
        this.ConstructorInjected = myproperty1 + " & " + shape1.Name + " & " + myproperty2 + " & " + shape2.Name;
    }

    [HttpGet]
    [Route("constructorinjection")]
    public string constructorinjection()
    {
        return "Constructor Injected: " + this.ConstructorInjected;
    }

    [HttpGet]
    [Route("PropertyInjected")]
    public string InjectionProperty()
    {
        return "Property Injected: " + this.MyPropertyName;
    }

    [HttpGet]
    [Route("GetPiValue1")]
    public string GetPiValue1()
    {
        return "Property Injected: " + this.PiValue1;
    }

    [HttpGet]
    [Route("GetPiValue2")]
    public string GetPiValue2()
    {
        return "Property Injected: " + this.PiValue2;
    }

    [HttpGet]
    [Route("GetShape")]
    public string GetShape()
    {
        return "Property Injected: " + this.Shape.Name;
    }

    [HttpGet]
    [Route("MethodInjected1")]
    public string InjectionMethod1()
    {
        return "Method Injected: " + this.MethodInjected1;
    }

    [HttpGet]
    [Route("MethodInjected2")]
    public string InjectionMethod2()
    {
        return "Method Injected: " + this.MethodInjected2;
    }
}

Configuring the Dependency Resolver

public static void Register(HttpConfiguration config)
{
    var container = new UnityContainer();
    RegisterInterfaces(container);
    config.DependencyResolver = new UnityResolver(container);

    // Other Web API configuration not shown.
}

private static void RegisterInterfaces(UnityContainer container)
{
    var dbContext = new SchoolDbContext();
    // Registration with constructor injection
    container.RegisterType<IStudentRepository, StudentRepository>(new InjectionConstructor(dbContext));
    container.RegisterType<ICourseRepository, CourseRepository>(new InjectionConstructor(dbContext));

    // Set constant/default value of Pi = 3.141 
    container.RegisterInstance<double>("PiValueExample1", 3.141);
    container.RegisterInstance<double>("PiValueExample2", 3.14);

    // without a name
    container.RegisterInstance<IShape>(new NoShape());

    // with circle name
    container.RegisterType<IShape, Circle>("Circle", new InjectionProperty("Name", "I am Circle"));

    // with rectangle name
    container.RegisterType<IShape, Rectangle>("Rectangle", new InjectionConstructor("I am Rectangle"));

    // Complex type like Constructor, Property and method injection
    container.RegisterType<DIV2Controller, DIV2Controller>(
        new InjectionConstructor("Constructor Value1", container.Resolve<IShape>("Circle"), "Constructor Value2", container.Resolve<IShape>()),
        new InjectionMethod("Initialize"),
        new InjectionMethod("Initialize2", "Value1", container.Resolve<IShape>("Circle"), "Value2", container.Resolve<IShape>()),
        new InjectionProperty("MyPropertyName", "Property Value"),
        new InjectionProperty("PiValue1", container.Resolve<double>("PiValueExample1")),
        new InjectionProperty("Shape", container.Resolve<IShape>("Rectangle")),
        new InjectionProperty("PiValue2", container.Resolve<double>("PiValueExample2")));
}

Remove a folder from git tracking

To forget directory recursively add /*/* to the path:

git update-index --assume-unchanged wordpress/wp-content/uploads/*/*

Using git rm --cached is not good for collaboration. More details here: How to stop tracking and ignore changes to a file in Git?

Design Patterns web based applications

BalusC excellent answer covers most of the patterns for web applications.

Some application may require Chain-of-responsibility_pattern

In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain.

Use case to use this pattern:

When handler to process a request(command) is unknown and this request can be sent to multiple objects. Generally you set successor to object. If current object can't handle the request or process the request partially and forward the same request to successor object.

Useful SE questions/articles:

Why would I ever use a Chain of Responsibility over a Decorator?

Common usages for chain of responsibility?

chain-of-responsibility-pattern from oodesign

chain_of_responsibility from sourcemaking

Cron job every three days

I don't think you have what you need with:

0 0 */3 * * ## <<< WARNING!!! CAUSES UNEVEN INTERVALS AT END OF MONTH!!

Unfortunately, the */3 is setting the interval on every n day of the month and not every n days. See: explanation here. At the end of the month there is recurring issue guaranteed.

1st  at 2019-02-01 00:00:00
then at 2019-02-04 00:00:00 << 3 days, etc. OK
then at 2019-02-07 00:00:00
...
then at 2019-02-25 00:00:00
then at 2019-01-28 00:00:00
then at 2019-03-01 00:00:00 << 1 day WRONG
then at 2019-03-04 00:00:00
...

According to this article, you need to add some modulo math to the command being executed to get a TRUE "every N days". For example:

0 0 * * *  bash -c '(( $(date +\%s) / 86400 \% 3 == 0 )) && runmyjob.sh

In this example, the job will be checked daily at 12:00 AM, but will only execute when the number of days since 01-01-1970 modulo 3 is 0.

If you want it to be every 3 days from a specific date, use the following format:

0 0 * * *  bash -c '(( $(date +\%s -d "2019-01-01") / 86400 \% 3 == 0 )) && runmyjob.sh

Can a table row expand and close?

Well, I'd say use the DIV instead of table as it would be much easier (but there's nothing wrong with using tables).

My approach would be to use jQuery.ajax and request more data from server and that way, the selected DIV (or TD if you use table) will automatically expand based on requested content.

That way, it saves bandwidth and makes it go faster as you don't load all content at once. It loads only when it's selected.

How to call javascript from a href?

Not sure why this worked for me while nothing else did but just in case anyone else is still looking...

In between head tags:

<script>
     function myFunction() {
           script code
     }
</script>

Then for the < a > tag:

<a href='' onclick='myFunction()' > Call Function </a>

How to check if cursor exists (open status)

This happened to me when a stored procedure running in SSMS encountered an error during the loop, while the cursor was in use to iterate over records and before the it was closed. To fix it I added extra code in the CATCH block to close the cursor if it is still open (using CURSOR_STATUS as other answers here suggest).

How to pass a single object[] to a params object[]

new[] { (object) 0, (object) null, (object) false }

XPath query to get nth instance of an element

This is a FAQ:

//somexpression[$N]

means "Find every node selected by //somexpression that is the $Nth child of its parent".

What you want is:

(//input[@id="search_query"])[2]

Remember: The [] operator has higher precedence (priority) than the // abbreviation.

Selecting option by text content with jQuery

I know this question is too old, but still, I think this approach would be cleaner:

cat = $.URLDecode(cat);
$('#cbCategory option:contains("' + cat + '")').prop('selected', true);

In this case you wont need to go over the entire options with each(). Although by that time prop() didn't exist so for older versions of jQuery use attr().


UPDATE

You have to be certain when using contains because you can find multiple options, in case of the string inside cat matches a substring of a different option than the one you intend to match.

Then you should use:

cat = $.URLDecode(cat);
$('#cbCategory option')
    .filter(function(index) { return $(this).text() === cat; })
    .prop('selected', true);

How to search in array of object in mongodb

The right way is:

db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}})

$elemMatch allows you to match more than one component within the same array element.

Without $elemMatch mongo will look for users with National Medal in some year and some award in 1975s, but not for users with National Medal in 1975.

See MongoDB $elemMatch Documentation for more info. See Read Operations Documentation for more information about querying documents with arrays.

How can I tell jackson to ignore a property for which I don't have control over the source code?

You can use Jackson Mixins. For example:

class YourClass {
  public int ignoreThis() { return 0; }    
}

With this Mixin

abstract class MixIn {
  @JsonIgnore abstract int ignoreThis(); // we don't need it!  
}

With this:

objectMapper.getSerializationConfig().addMixInAnnotations(YourClass.class, MixIn.class);

Edit:

Thanks to the comments, with Jackson 2.5+, the API has changed and should be called with objectMapper.addMixIn(Class<?> target, Class<?> mixinSource)

How to get first two characters of a string in oracle query?

select substr(orderno,1,2) from shipment;

You may want to have a look at the documentation too.

Jenkins - passing variables between jobs?

Reading through the answers, I don't see another option that I like so will offer it as well. I love the parameterization of jobs, but it doesn't always scale well. If you have jobs which are not directly downstream of the first job but farther down the pipeline, you don't really want to parameterize every job in the pipeline so as to be able to pass the parameters all the way through. Or if you have a large number of parameters used by a variety of other jobs (especially those not necessarily tied to one parent or master job), again parameterization doesn't work.

In these cases, I favor outputting the values to a properties file and then injecting that in whatever job I need using the EnvInject plugin. This can be done dynamically, which is another way to solve the issue from another answer above where parameterized jobs were still used. This solution scales very well in many scenarios.

Difference between text and varchar (character varying)

On PostgreSQL manual

There is no performance difference among these three types, apart from increased storage space when using the blank-padded type, and a few extra CPU cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact character(n) is usually the slowest of the three because of its additional storage costs. In most situations text or character varying should be used instead.

I usually use text

References: http://www.postgresql.org/docs/current/static/datatype-character.html

Add new column with foreign key constraint in one command

Try this:

ALTER TABLE product
ADD FOREIGN KEY (product_ID) REFERENCES product(product_ID);

How does Facebook disable the browser's integrated Developer Tools?

I'm a security engineer at Facebook and this is my fault. We're testing this for some users to see if it can slow down some attacks where users are tricked into pasting (malicious) JavaScript code into the browser console.

Just to be clear: trying to block hackers client-side is a bad idea in general; this is to protect against a specific social engineering attack.

If you ended up in the test group and are annoyed by this, sorry. I tried to make the old opt-out page (now help page) as simple as possible while still being scary enough to stop at least some of the victims.

The actual code is pretty similar to @joeldixon66's link; ours is a little more complicated for no good reason.

Chrome wraps all console code in

with ((console && console._commandLineAPI) || {}) {
  <code goes here>
}

... so the site redefines console._commandLineAPI to throw:

Object.defineProperty(console, '_commandLineAPI',
   { get : function() { throw 'Nooo!' } })

This is not quite enough (try it!), but that's the main trick.


Epilogue: The Chrome team decided that defeating the console from user-side JS was a bug and fixed the issue, rendering this technique invalid. Afterwards, additional protection was added to protect users from self-xss.

__proto__ VS. prototype in JavaScript

A nice way to think of it is...

prototype is used by constructor functions. It should've really been called something like, "prototypeToInstall", since that's what it is.

and __proto__ is that "installed prototype" on an object (that was created/installed upon the object from said constructor() function)

Find out which remote branch a local branch is tracking

If you want to find the upstream for any branch (as opposed to just the one you are on), here is a slight modification to @cdunn2001's answer:

git rev-parse --abbrev-ref --symbolic-full-name YOUR_LOCAL_BRANCH_NAME@{upstream}

That will give you the remote branch name for the local branch named YOUR_LOCAL_BRANCH_NAME.

Android: making a fullscreen application

I recently had the exact same issue and benefitted from the following post as well (in addition to Rohit5k2's solution above):

https://bsgconsultancy.wordpress.com/2015/09/13/convert-any-website-into-android-application-by-using-android-studio/

In Step 3, MainActivity extends Activity instead of ActionBarActivity (as Rohit5k2 mentioned). Putting the NoTitleBar and Fullscreen theme elements into the correct places in the AndroidManifest.xml file is also very important (take a look at Step 4).

Writing string to a file on a new line every time

Just a note, file isn't supported in Python 3 and was removed. You can do the same with the open built-in function.

f = open('test.txt', 'w')
f.write('test\n')

Converting newline formatting from Mac to Windows

This is an improved version of Anne's answer -- if you use perl, you can do the edit on the file 'in-place' rather than generating a new file:

perl -pi -e 's/\r\n|\n|\r/\r\n/g' file-to-convert  # Convert to DOS
perl -pi -e 's/\r\n|\n|\r/\n/g'   file-to-convert  # Convert to UNIX

Why does ++[[]][+[]]+[+[]] return the string "10"?

If we split it up, the mess is equal to:

++[[]][+[]]
+
[+[]]

In JavaScript, it is true that +[] === 0. + converts something into a number, and in this case it will come down to +"" or 0 (see specification details below).

Therefore, we can simplify it (++ has precendence over +):

++[[]][0]
+
[0]

Because [[]][0] means: get the first element from [[]], it is true that:

[[]][0] returns the inner array ([]). Due to references it's wrong to say [[]][0] === [], but let's call the inner array A to avoid the wrong notation.

++ before its operand means “increment by one and return the incremented result”. So ++[[]][0] is equivalent to Number(A) + 1 (or +A + 1).

Again, we can simplify the mess into something more legible. Let's substitute [] back for A:

(+[] + 1)
+
[0]

Before +[] can coerce the array into the number 0, it needs to be coerced into a string first, which is "", again. Finally, 1 is added, which results in 1.

  • (+[] + 1) === (+"" + 1)
  • (+"" + 1) === (0 + 1)
  • (0 + 1) === 1

Let's simplify it even more:

1
+
[0]

Also, this is true in JavaScript: [0] == "0", because it's joining an array with one element. Joining will concatenate the elements separated by ,. With one element, you can deduce that this logic will result in the first element itself.

In this case, + sees two operands: a number and an array. It’s now trying to coerce the two into the same type. First, the array is coerced into the string "0", next, the number is coerced into a string ("1"). Number + String === String.

"1" + "0" === "10" // Yay!

Specification details for +[]:

This is quite a maze, but to do +[], first it is being converted to a string because that's what + says:

11.4.6 Unary + Operator

The unary + operator converts its operand to Number type.

The production UnaryExpression : + UnaryExpression is evaluated as follows:

  1. Let expr be the result of evaluating UnaryExpression.

  2. Return ToNumber(GetValue(expr)).

ToNumber() says:

Object

Apply the following steps:

  1. Let primValue be ToPrimitive(input argument, hint String).

  2. Return ToString(primValue).

ToPrimitive() says:

Object

Return a default value for the Object. The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object, passing the optional hint PreferredType. The behaviour of the [[DefaultValue]] internal method is defined by this specification for all native ECMAScript objects in 8.12.8.

[[DefaultValue]] says:

8.12.8 [[DefaultValue]] (hint)

When the [[DefaultValue]] internal method of O is called with hint String, the following steps are taken:

  1. Let toString be the result of calling the [[Get]] internal method of object O with argument "toString".

  2. If IsCallable(toString) is true then,

a. Let str be the result of calling the [[Call]] internal method of toString, with O as the this value and an empty argument list.

b. If str is a primitive value, return str.

The .toString of an array says:

15.4.4.2 Array.prototype.toString ( )

When the toString method is called, the following steps are taken:

  1. Let array be the result of calling ToObject on the this value.

  2. Let func be the result of calling the [[Get]] internal method of array with argument "join".

  3. If IsCallable(func) is false, then let func be the standard built-in method Object.prototype.toString (15.2.4.2).

  4. Return the result of calling the [[Call]] internal method of func providing array as the this value and an empty arguments list.

So +[] comes down to +"", because [].join() === "".

Again, the + is defined as:

11.4.6 Unary + Operator

The unary + operator converts its operand to Number type.

The production UnaryExpression : + UnaryExpression is evaluated as follows:

  1. Let expr be the result of evaluating UnaryExpression.

  2. Return ToNumber(GetValue(expr)).

ToNumber is defined for "" as:

The MV of StringNumericLiteral ::: [empty] is 0.

So +"" === 0, and thus +[] === 0.

How do you find out the caller function in JavaScript?

To recap (and make it clearer) ...

this code:

function Hello() {
    alert("caller is " + arguments.callee.caller.toString());
}

is equivalent to this:

function Hello() {
    alert("caller is " + Hello.caller.toString());
}

Clearly the first bit is more portable, since you can change the name of the function, say from "Hello" to "Ciao", and still get the whole thing to work.

In the latter, in case you decide to refactor the name of the invoked function (Hello), you would have to change all its occurrences :(

What is Haskell used for in the real world?

One example of Haskell in action is xmonad, a "featureful window manager in less than 1200 lines of code".

Create SQLite database in android

To understand how to use sqlite database in android with best practices see - Android with sqlite database

There are few classes about which you should know and those will help you model your tables and models i.e android.provider.BaseColumns

Below is an example of a table

public class ProductTable implements BaseColumns {
  public static final String NAME = "name";
  public static final String PRICE = "price";
  public static final String TABLE_NAME = "products";

  public static final String CREATE_QUERY = "create table " + TABLE_NAME + " (" +
      _ID + " INTEGER, " +
      NAME + " TEXT, " +
      PRICE + " INTEGER)";

  public static final String DROP_QUERY = "drop table " + TABLE_NAME;
  public static final String SElECT_QUERY = "select * from " + TABLE_NAME;
}

What are OLTP and OLAP. What is the difference between them?

The difference is quite simple:

OLTP (Online Transaction Processing)

OLTP is a class of information systems that facilitate and manage transaction-oriented applications. OLTP has also been used to refer to processing in which the system responds immediately to user requests. Online transaction processing applications are high throughput and insert or update-intensive in database management. Some examples of OLTP systems include order entry, retail sales, and financial transaction systems.

OLAP (Online Analytical Processing)

OLAP is part of the broader category of business intelligence, which also encompasses relational database, report writing and data mining. Typical applications of OLAP include business reporting for sales, marketing, management reporting, business process management (BPM), budgeting and forecasting, financial reporting and similar areas.

See more details OLTP and OLAP

Get PostGIS version

Did you try using SELECT PostGIS_version();

Filling a List with all enum values in Java

You can use also:

Collections.singletonList(Something.values())

printf with std::string?

printf accepts a variable number of arguments. Those can only have Plain Old Data (POD) types. Code that passes anything other than POD to printf only compiles because the compiler assumes you got your format right. %s means that the respective argument is supposed to be a pointer to a char. In your case it is an std::string not const char*. printf does not know it because the argument type goes lost and is supposed to be restored from the format parameter. When turning that std::string argument into const char* the resulting pointer will point to some irrelevant region of memory instead of your desired C string. For that reason your code prints out gibberish.

While printf is an excellent choice for printing out formatted text, (especially if you intend to have padding), it can be dangerous if you haven't enabled compiler warnings. Always enable warnings because then mistakes like this are easily avoidable. There is no reason to use the clumsy std::cout mechanism if the printf family can do the same task in a much faster and prettier way. Just make sure you have enabled all warnings (-Wall -Wextra) and you will be good. In case you use your own custom printf implementation you should declare it with the __attribute__ mechanism that enables the compiler to check the format string against the parameters provided.

What does elementFormDefault do in XSD?

New, detailed answer and explanation to an old, frequently asked question...

Short answer: If you don't add elementFormDefault="qualified" to xsd:schema, then the default unqualified value means that locally declared elements are in no namespace.

There's a lot of confusion regarding what elementFormDefault does, but this can be quickly clarified with a short example...

Streamlined version of your XSD:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
        xmlns:target="http://www.levijackson.net/web340/ns"
        targetNamespace="http://www.levijackson.net/web340/ns">
  <element name="assignments">
    <complexType>
      <sequence>
        <element name="assignment" type="target:assignmentInfo" 
                 minOccurs="1" maxOccurs="unbounded"/>
      </sequence>
    </complexType>
  </element>
  <complexType name="assignmentInfo">
    <sequence>
      <element name="name" type="string"/>
    </sequence>
    <attribute name="id" type="string" use="required"/>
  </complexType>
</schema>

Key points:

  • The assignment element is locally defined.
  • Elements locally defined in XSD are in no namespace by default.
    • This is because the default value for elementFormDefault is unqualified.
    • This arguably is a design mistake by the creators of XSD.
    • Standard practice is to always use elementFormDefault="qualified" so that assignment is in the target namespace as one would expect.
  • It is a rarely used form attribute on xs:element declarations for which elementFormDefault establishes default values.

Seemingly Valid XML

This XML looks like it should be valid according to the above XSD:

<assignments xmlns="http://www.levijackson.net/web340/ns"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.levijackson.net/web340/ns try.xsd">
  <assignment id="a1">
    <name>John</name>
  </assignment>
</assignments>

Notice:

  • The default namespace on assignments places assignments and all of its descendents in the default namespace (http://www.levijackson.net/web340/ns).

Perplexing Validation Error

Despite looking valid, the above XML yields the following confusing validation error:

[Error] try.xml:4:23: cvc-complex-type.2.4.a: Invalid content was found starting with element 'assignment'. One of '{assignment}' is expected.

Notes:

  • You would not be the first developer to curse this diagnostic that seems to say that the content is invalid because it expected to find an assignment element but it actually found an assignment element. (WTF)
  • What this really means: The { and } around assignment means that validation was expecting assignment in no namespace here. Unfortunately, when it says that it found an assignment element, it doesn't mention that it found it in a default namespace which differs from no namespace.

Solution

  • Vast majority of the time: Add elementFormDefault="qualified" to the xsd:schema element of the XSD. This means valid XML must place elements in the target namespace when locally declared in the XSD; otherwise, valid XML must place locally declared elements in no namespace.
  • Tiny minority of the time: Change the XML to comply with the XSD's requirement that assignment be in no namespace. This can be achieved, for example, by adding xmlns="" to the assignment element.

Credits: Thanks to Michael Kay for helpful feedback on this answer.

How would one write object-oriented code in C?

Check out GObject. It's meant to be OO in C and one implementation of what you're looking for. If you really want OO though, go with C++ or some other OOP language. GObject can be really tough to work with at times if you're used to dealing with OO languages, but like anything, you'll get used to the conventions and flow.

"Sub or Function not defined" when trying to run a VBA script in Outlook

I solved the problem by following the instructions on msdn.microsoft.com more closely. There, it is stated that one must create the new macro by selecting Developer -> Macros, typing a new macro name, and clicking "Create". Creating the macro in this way, I was able to run it (see message box below).

enter image description here

‘ant’ is not recognized as an internal or external command

Please follow these steps

  1. In User Variables

    Set VARIABLE NAME=ANT_HOME VARIABLE PATH =C:\Program Files\apache-ant-1.9.7

2.Edit User Variable PATH = %ANT_HOME%\bin

  1. Go to System Variables

    • Set Path =%ANT_HOME%\bin

Convert Pandas Column to DateTime

If you have more than one column to be converted you can do the following:

df[["col1", "col2", "col3"]] = df[["col1", "col2", "col3"]].apply(pd.to_datetime)

Angular: Cannot Get /

The problem was that I ran the commands within the folder /project/src/app. Navigating back to the project folder so to /project and running ng serve from there solved my problem.

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

You have to stop the current process and run your new one. In Eclipse, you can press this button to ReLaunch your application: enter image description here

PHP script to loop through all of the files in a directory?

you can do this as well

$path = "/public";

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);

foreach ($objects as $name => $object) {
  if ('.' === $object) continue;
  if ('..' === $object) continue;

str_replace('/public/', '/', $object->getPathname());

// for example : /public/admin/image.png => /admin/image.png

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

In kotlin you can use like this

fun changeDateFormats(currentFormat: String, dateString: String): String {
        var result = ""
        try {
            val formatterOld = SimpleDateFormat(currentFormat, Locale.getDefault())
            formatterOld.timeZone = TimeZone.getTimeZone("UTC")

            var date: Date? = null

            date = formatterOld.parse(dateString)

            val dayFormate = SimpleDateFormat("d", Locale.getDefault())
            var day = dayFormate.format(date)

            val formatterNew = SimpleDateFormat("hh:mm a, d'" + getDayOfMonthSuffix(day.toInt()) + "' MMM yy", Locale.getDefault())

            if (date != null) {
                result = formatterNew.format(date)
            }

        } catch (e: ParseException) {
            e.printStackTrace()
            return dateString
        }

        return result
    }


    private fun getDayOfMonthSuffix(n: Int): String {
        if (n in 11..13) {
            return "th"
        }
        when (n % 10) {
            1 -> return "st"
            2 -> return "nd"
            3 -> return "rd"
            else -> return "th"
        }
    }

set like this

  txt_chat_time_me.text = changeDateFormats("SERVER_DATE", "DATE")

How to get row count using ResultSet in Java?

If you have table and storing the ID as primary and auto increment then this will work

Example code to get the total row count http://www.java2s.com/Tutorial/Java/0340__Database/GettheNumberofRowsinaDatabaseTable.htm

Below is code

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class Main {
  public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
        ResultSet.CONCUR_UPDATABLE);

    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
    st.executeUpdate("insert into survey (id,name ) values (2,null)");
    st.executeUpdate("insert into survey (id,name ) values (3,'Tom')");
    st = conn.createStatement();
    ResultSet rs = st.executeQuery("SELECT * FROM survey");

    rs = st.executeQuery("SELECT COUNT(*) FROM survey");
    // get the number of rows from the result set
    rs.next();
    int rowCount = rs.getInt(1);
    System.out.println(rowCount);

    rs.close();
    st.close();
    conn.close();

  }

  private static Connection getConnection() throws Exception {
    Class.forName("org.hsqldb.jdbcDriver");
    String url = "jdbc:hsqldb:mem:data/tutorial";

    return DriverManager.getConnection(url, "sa", "");
  }
}

Reading InputStream as UTF-8

Solved my own problem. This line:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

needs to be:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));

or since Java 7:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));

Array versus List<T>: When to use which?

Really just answering to add a link which I'm surprised hasn't been mentioned yet: Eric's Lippert's blog entry on "Arrays considered somewhat harmful."

You can judge from the title that it's suggesting using collections wherever practical - but as Marc rightly points out, there are plenty of places where an array really is the only practical solution.

download csv file from web api in angular js

The a.download is not supported by IE. At least at the HTML5 "supported" pages. :(

PHP: Limit foreach() statement?

you should use the break statement

usually it's use this way

$i = 0;
foreach($data as $key => $row){
    if(++$i > 2) break;
}

on the same fashion the continue statement exists if you need to skip some items.

POST request not allowed - 405 Not Allowed - nginx, even with headers included

This configuration to your nginx.conf should help you.

https://gist.github.com/baskaran-md/e46cc25ccfac83f153bb

server {
    listen       80;
    server_name  localhost;

    location / {
        root   html;
        index  index.html index.htm;
    }

    error_page  404     /404.html;
    error_page  403     /403.html;

    # To allow POST on static pages
    error_page  405     =200 $uri;

    # ...
}

HTML encoding issues - "Â" character showing up instead of "&nbsp;"

Somewhere in that mess, the non-breaking spaces from the HTML template (the  s) are encoding as ISO-8859-1 so that they show up incorrectly as an "Â" character

That'd be encoding to UTF-8 then, not ISO-8859-1. The non-breaking space character is byte 0xA0 in ISO-8859-1; when encoded to UTF-8 it'd be 0xC2,0xA0, which, if you (incorrectly) view it as ISO-8859-1 comes out as " ". That includes a trailing nbsp which you might not be noticing; if that byte isn't there, then something else has mauled your document and we need to see further up to find out what.

What's the regexp, how does the templating work? There would seem to be a proper HTML parser involved somewhere if your &nbsp; strings are (correctly) being turned into U+00A0 NON-BREAKING SPACE characters. If so, you could just process your template natively in the DOM, and ask it to serialise using the ASCII encoding to keep non-ASCII characters as character references. That would also stop you having to do regex post-processing on the HTML itself, which is always a highly dodgy business.

Well anyway, for now you can add one of the following to your document's <head> and see if that makes it look right in the browser:

  • for HTML4: <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  • for HTML5: <meta charset="utf-8">

If you've done that, then any remaining problem is ActivePDF's fault.

Python IndentationError: unexpected indent

find all tabs and replaced by 4 spaces in notepad ++ .It worked.

Authorize attribute in ASP.NET MVC

Using [Authorize] attributes can help prevent security holes in your application. The way that MVC handles URL's (i.e. routing them to a controller rather than to an actual file) makes it difficult to actually secure everything via the web.config file.

Read more here: http://blogs.msdn.com/b/rickandy/archive/2012/03/23/securing-your-asp-net-mvc-4-app-and-the-new-allowanonymous-attribute.aspx (via archive.org)

How do I scroll the UIScrollView when the keyboard appears?

The following is my solutions which works ( 5 steps )

Step1: Add an observer to catch which UITEXTFIELD or UITEXTVIEW ShoudBeginEditing ( where object is inited or ViewDidLoad.

[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(updateActiveField:)
                                             name:@"UPDATE_ACTIVE_FIELD" object:nil];

Step2: Post a notification when ..ShouldBeginEditing with OBJECT of UITEXTFIELD or UITEXTVIEW

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView {

[[NSNotificationCenter defaultCenter] postNotificationName:@"UPDATE_ACTIVE_FIELD" 
                                                    object:textView];
return YES;
}

Step3: The method that (Step1 calles ) assigns the current UITEXTFIELD or UITEXTVIEW

-(void) updateActiveField: (id) sender {
    activeField = [sender object];
}

Step4: Add Keyboard observer UIKeyboardWillShowNotification ( same place as Step1 )

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWasShown:)
                                             name:UIKeyboardDidShowNotification object:nil];

and method:

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);

    _currentEdgeInsets = self.layoutPanel.contentInset; // store current insets to restore them later
    self.layoutPanel.contentInset = contentInsets;
    self.layoutPanel.scrollIndicatorInsets = contentInsets;

    // If active text field is hidden by keyboard, scroll it so it's visible
    CGRect aRect =  self.view.frame;
    aRect.size.height -= kbSize.height;

    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    CGPoint p = [activeField convertPoint:activeField.bounds.origin toView:window];

    if (!CGRectContainsPoint(aRect, p) ) {
        CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y +kbSize.height);
       [self.layoutPanel setContentOffset:scrollPoint animated:YES];
       self.layoutPanel.scrollEnabled = NO;
    }
}

Step5: Add Keyboard observer UIKeyboardWillHideNotification ( same place as step 1 )

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];

and method:

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    self.layoutPanel.contentInset = _currentEdgeInsets;
    self.layoutPanel.scrollIndicatorInsets = _currentEdgeInsets;
    self.layoutPanel.scrollEnabled = YES;
}

Remember to remove observers!

How to list the files in current directory?

Maybe the dot notation for current folder is incorrect?

Print the result of File.getCanonicalFile() to check the path.

Can anyone explain to me why src isn't the current folder?

Your IDE is setting the class-path when invoking the JVM.

E.G. (reaches for Netbeans) If you select menus File | Project Properties (all classes) you might see something similar to:

Netbeans project options

It is the Working Directory that is of interest here.

How to programmatically empty browser cache?

There's no way a browser will let you clear its cache. It would be a huge security issue if that were possible. This could be very easily abused - the minute a browser supports such a "feature" will be the minute I uninstall it from my computer.

What you can do is to tell it not to cache your page, by sending the appropriate headers or using these meta tags:

<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>

You might also want to consider turning off auto-complete on form fields, although I'm afraid there's a standard way to do it (see this question).

Regardless, I would like to point out that if you are working with sensitive data you should be using SSL. If you aren't using SSL, anyone with access to the network can sniff network traffic and easily see what your user is seeing.

Using SSL also makes some browsers not use caching unless explicitly told to. See this question.

Understanding __get__ and __set__ and Python descriptors

I tried (with minor changes as suggested) the code from Andrew Cooke's answer. (I am running python 2.7).

The code:

#!/usr/bin/env python
class Celsius:
    def __get__(self, instance, owner): return 9 * (instance.fahrenheit + 32) / 5.0
    def __set__(self, instance, value): instance.fahrenheit = 32 + 5 * value / 9.0

class Temperature:
    def __init__(self, initial_f): self.fahrenheit = initial_f
    celsius = Celsius()

if __name__ == "__main__":

    t = Temperature(212)
    print(t.celsius)
    t.celsius = 0
    print(t.fahrenheit)

The result:

C:\Users\gkuhn\Desktop>python test2.py
<__main__.Celsius instance at 0x02E95A80>
212

With Python prior to 3, make sure you subclass from object which will make the descriptor work correctly as the get magic does not work for old style classes.

Using the Underscore module with Node.js

Note: The following only works for the next line of code, and only due to a coincidence.

With Lodash,

require('lodash');
_.isArray([]); // true

No var _ = require('lodash') since Lodash mysteriously sets this value globally when required.

Extracting text from HTML file using Python

Here's the code I use on a regular basis.

from bs4 import BeautifulSoup
import urllib.request


def processText(webpage):

    # EMPTY LIST TO STORE PROCESSED TEXT
    proc_text = []

    try:
        news_open = urllib.request.urlopen(webpage.group())
        news_soup = BeautifulSoup(news_open, "lxml")
        news_para = news_soup.find_all("p", text = True)

        for item in news_para:
            # SPLIT WORDS, JOIN WORDS TO REMOVE EXTRA SPACES
            para_text = (' ').join((item.text).split())

            # COMBINE LINES/PARAGRAPHS INTO A LIST
            proc_text.append(para_text)

    except urllib.error.HTTPError:
        pass

    return proc_text

I hope that helps.

Update row values where certain condition is met in pandas

I think you can use loc if you need update two columns to same value:

df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2        aaaa         aaaa
c       2        aaaa         aaaa
d       3  some_value   some_value

If you need update separate, one option is use:

df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2          10   some_value
c       2          10   some_value
d       3  some_value   some_value

Another common option is use numpy.where:

df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
   stream  feat another_feat
a       1    20   some_value
b       2    10   some_value
c       2    10   some_value
d       3    20   some_value

EDIT: If you need divide all columns without stream where condition is True, use:

print df1
   stream  feat  another_feat
a       1     4             5
b       2     4             5
c       2     2             9
d       3     1             7

#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']

df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
   stream  feat  another_feat
a       1   4.0           5.0
b       2   2.0           2.5
c       2   1.0           4.5
d       3   1.0           7.0

If working with multiple conditions is possible use multiple numpy.where or numpy.select:

df0 = pd.DataFrame({'Col':[5,0,-6]})

df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing', 
                          np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))

df0['New Col2'] = np.select([df0['Col'] > 0, df0['Col'] < 0],
                            ['Increasing',  'Decreasing'], 
                            default='No Change')

print (df0)
   Col    New Col1    New Col2
0    5  Increasing  Increasing
1    0   No Change   No Change
2   -6  Decreasing  Decreasing

Using HTML5 file uploads with AJAX and jQuery

It's not too hard. Firstly, take a look at FileReader Interface.

So, when the form is submitted, catch the submission process and

var file = document.getElementById('fileBox').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = shipOff;
//reader.onloadstart = ...
//reader.onprogress = ... <-- Allows you to update a progress bar.
//reader.onabort = ...
//reader.onerror = ...
//reader.onloadend = ...


function shipOff(event) {
    var result = event.target.result;
    var fileName = document.getElementById('fileBox').files[0].name; //Should be 'picture.jpg'
    $.post('/myscript.php', { data: result, name: fileName }, continueSubmission);
}

Then, on the server side (i.e. myscript.php):

$data = $_POST['data'];
$fileName = $_POST['name'];
$serverFile = time().$fileName;
$fp = fopen('/uploads/'.$serverFile,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
fclose($fp);
$returnData = array( "serverFile" => $serverFile );
echo json_encode($returnData);

Or something like it. I may be mistaken (and if I am, please, correct me), but this should store the file as something like 1287916771myPicture.jpg in /uploads/ on your server, and respond with a JSON variable (to a continueSubmission() function) containing the fileName on the server.

Check out fwrite() and jQuery.post().

On the above page it details how to use readAsBinaryString(), readAsDataUrl(), and readAsArrayBuffer() for your other needs (e.g. images, videos, etc).

Which Java library provides base64 encoding/decoding?

Within Apache Commons, commons-codec-1.7.jar contains a Base64 class which can be used to encode.

Via Maven:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>20041127.091804</version>
</dependency>

Direct Download

onchange equivalent in angular2

In Angular you can define event listeners like in the example below:

<!-- Here you can call public methods from parental component -->
<input (change)="method_name()"> 

Regex: Specify "space or start of string" and "space or end of string"

\b matches at word boundaries (without actually matching any characters), so the following should do what you want:

\bstackoverflow\b

How to generate a create table script for an existing table in phpmyadmin?

  1. SHOW CREATE TABLE your_table_name => Press GO button

After show table, above the table ( +options ) Hyperlink is there.

  1. Press (+options) Hyperlink then appear some options select (Full texts) => Press GO button.

JavaScript by reference vs. by value

Yes, Javascript always passes by value, but in an array or object, the value is a reference to it, so you can 'change' the contents.

But, I think you already read it on SO; here you have the documentation you want:

http://snook.ca/archives/javascript/javascript_pass

Switch/toggle div (jQuery)

I think this works:

$(document).ready(function(){

    // Hide (collapse) the toggle containers on load
    $(".toggle_container").hide();

    // Switch the "Open" and "Close" state per click then 
    // slide up/down (depending on open/close state)
    $("h2.trigger").click(function(){
        $(this).toggleClass("active").next().slideToggle("slow");
        return false; // Prevent the browser jump to the link anchor
    });
});

Git push/clone to new server

There are many ways to move repositories around, git bundle is a nice way if you have insufficient network availability. Since a Git repository is really just a directory full of files, you can "clone" a repository by making a copy of the .git directory in whatever way suits you best.

The most efficient way is to use an external repository somewhere (use GitHub or set up Gitosis), and then git push.

Update OpenSSL on OS X with Homebrew

If you're using Homebrew /usr/local/bin should already be at the front of $PATH or at least come before /usr/bin. If you now run brew link --force openssl in your terminal window, open a new one and run which openssl in it. It should now show openssl under /usr/local/bin.

How can I require at least one checkbox be checked before a form can be submitted?

This should have what you need, check out the jsfiddle at the bottom:

$(document).ready(function () {
$('#txt').val($("input[type=checkbox]:checked").length);
$('#txt2').val($("input[type=checkbox]").length);

$('input[type=checkbox]').change(function () {
checked = $("input[type=checkbox]:checked").length;
$('#block').show();
$('#block2').hide();
if (checked > 0) {
  $('#block').hide();
  $('#block2').show();
  $('#txt').val(checked);
 }
});
});

WebView and HTML5 <video>

A-M's is similar to what the BrowerActivity does. for FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams (768, 512);

I think we can use

FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,
            FrameLayout.LayoutParams.FILL_PARENT) 

instead.

Another issue I met is if the video is playing, and user clicks the back button, next time, you go to this activity(singleTop one) and can not play the video. to fix this, I called the

try { 
    mCustomVideoView.stopPlayback();  
    mCustomViewCallback.onCustomViewHidden();
} catch(Throwable e) { //ignore }

in the activity's onBackPressed method.

Adding form action in html in laravel

Form Post Action :

<form method="post" action="{{url('login')}}" accept-charset="UTF-8">

Change your Route : In Routes -> Web.php

Route::post('login','WelcomeController@log_in');

Call to a member function on a non-object

I realized that I wasn't passing $objPage into page_properties(). It works fine now.

How to get a substring between two strings in PHP?

This is the function I'm using for this. I combined two answers in one function for single or multiple delimiters.

function getStringBetweenDelimiters($p_string, $p_from, $p_to, $p_multiple=false){
    //checking for valid main string  
    if (strlen($p_string) > 0) {
        //checking for multiple strings 
        if ($p_multiple) {
            // getting list of results by end delimiter
            $result_list = explode($p_to, $p_string);
            //looping through result list array 
            foreach ( $result_list AS $rlkey => $rlrow) {
                // getting result start position
                $result_start_pos   = strpos($rlrow, $p_from);
                // calculating result length
                $result_len         =  strlen($rlrow) - $result_start_pos;

                // return only valid rows
                if ($result_start_pos > 0) {
                    // cleanying result string + removing $p_from text from result
                    $result[] =   substr($rlrow, $result_start_pos + strlen($p_from), $result_len);                 
                }// end if 
            } // end foreach 

        // if single string
        } else {
            // result start point + removing $p_from text from result
            $result_start_pos   = strpos($p_string, $p_from) + strlen($p_from);
            // lenght of result string
            $result_length      = strpos($p_string, $p_to, $result_start_pos);
            // cleaning result string
            $result             = substr($p_string, $result_start_pos+1, $result_length );
        } // end if else 
    // if empty main string
    } else {
        $result = false;
    } // end if else 

    return $result;


} // end func. get string between

For simple use (returns two):

$result = getStringBetweenDelimiters(" one two three ", 'one', 'three');

For getting each row in a table to result array :

$result = getStringBetweenDelimiters($table, '<tr>', '</tr>', true);

How can I find my Apple Developer Team id and Team Agent Apple ID?

If you're on OSX you can also find it your keychain. Your developer and distribution certificates have your Team ID in them.

Applications -> Utilities -> Keychain Access.

Under the 'login' Keychain, go into the 'Certificates' category.

Scroll to find your development or distribution certificate. They will read:

iPhone Distribution: Team Name (certificate id)

or

iPhone Developer: Team Name (certificate id)

Simply double-click on the item, and the

"Organizational Unit"

is the "Team ID"

enter image description here

Note that this is the only way to find your

"Personal team" ID

You can not find the "Personal team" ID on the Apple web interface.

For example, if you are automating a build from say Unity, during development you'll want it to appear in Xcode as your "Personal team" - this is the only way to get that value.

What is the symbol for whitespace in C?

There is no particular symbol for whitespace. It is actually a set of some characters which are:

' '      space 
'\t'     horizontal tab 
'\n'     newline
'\v'     vertical tab 
'\f'     feed 
'\r'     carriage return    

Use isspace standard library function from ctype.h if you want to check for any of these white-spaces.

For just a space, use ' '.

Automatically open default email client and pre-populate content

Implemented this way without using Jquery:

<button class="emailReplyButton" onClick="sendEmail(message)">Reply</button>

sendEmail(message) {
    var email = message.emailId;
    var subject = message.subject;
    var emailBody = 'Hi '+message.from;
    document.location = "mailto:"+email+"?subject="+subject+"&body="+emailBody;
}

Jackson JSON custom serialization for certain fields

Add a @JsonProperty annotated getter, which returns a String, for the favoriteNumber field:

public class Person {
    public String name;
    public int age;
    private int favoriteNumber;

    public Person(String name, int age, int favoriteNumber) {
        this.name = name;
        this.age = age;
        this.favoriteNumber = favoriteNumber;
    }

    @JsonProperty
    public String getFavoriteNumber() {
        return String.valueOf(favoriteNumber);
    }

    public static void main(String... args) throws Exception {
        Person p = new Person("Joe", 25, 123);
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writeValueAsString(p)); 
        // {"name":"Joe","age":25,"favoriteNumber":"123"}
    }
}

How to initialize an array's length in JavaScript?

(this was probably better as a comment, but got too long)

So, after reading this I was curious if pre-allocating was actually faster, because in theory it should be. However, this blog gave some tips advising against it http://www.html5rocks.com/en/tutorials/speed/v8/.

So still being unsure, I put it to the test. And as it turns out it seems to in fact be slower.

var time = Date.now();
var temp = [];
for(var i=0;i<100000;i++){
    temp[i]=i;
}
console.log(Date.now()-time);


var time = Date.now();
var temp2 = new Array(100000);
for(var i=0;i<100000;i++){
    temp2[i] = i;
}
console.log(Date.now()-time); 

This code yields the following after a few casual runs:

$ node main.js 
9
16
$ node main.js 
8
14
$ node main.js 
7
20
$ node main.js 
9
14
$ node main.js 
9
19

jQuery SVG, why can't I addClass?

jQuery 3 does not have this problem

One of the changes listed on the jQuery 3.0 revisions is:

add SVG class manipulation (#2199, 20aaed3)

One solution for this issue would be to upgrade to jQuery 3. It works great:

_x000D_
_x000D_
var flip = true;
setInterval(function() {
    // Could use toggleClass, but demonstrating addClass.
    if (flip) {
        $('svg circle').addClass('green');
    }
    else {
        $('svg circle').removeClass('green');
    }
    flip = !flip;
}, 1000);
_x000D_
svg circle {
    fill: red;
    stroke: black;
    stroke-width: 5;
}
svg circle.green {
    fill: green;
}
_x000D_
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>

<svg>
    <circle cx="50" cy="50" r="25" />
</svg>
_x000D_
_x000D_
_x000D_


The Problem:

The reason the jQuery class manipulation functions do not work with the SVG elements is because jQuery versions prior to 3.0 use the className property for these functions.

Excerpt from jQuery attributes/classes.js:

cur = elem.nodeType === 1 && ( elem.className ?
    ( " " + elem.className + " " ).replace( rclass, " " ) :
    " "
);

This behaves as expected for HTML elements, but for SVG elements className is a little different. For an SVG element, className is not a string, but an instance of SVGAnimatedString.

Consider the following code:

_x000D_
_x000D_
var test_div = document.getElementById('test-div');
var test_svg = document.getElementById('test-svg');
console.log(test_div.className);
console.log(test_svg.className);
_x000D_
#test-div {
    width: 200px;
    height: 50px;
    background: blue;
}
_x000D_
<div class="test div" id="test-div"></div>

<svg width="200" height="50" viewBox="0 0 200 50">
  <rect width="200" height="50" fill="green" class="test svg" id="test-svg" />
</svg>
_x000D_
_x000D_
_x000D_

If you run this code you will see something like the following in your developer console.

test div
SVGAnimatedString { baseVal="test svg",  animVal="test svg"}

If we were to cast that SVGAnimatedString object to a string as jQuery does, we would have [object SVGAnimatedString], which is where jQuery fails.

How the jQuery SVG plugin handles this:

The jQuery SVG plugin works around this by patching the relevant functions to add SVG support.

Excerpt from jQuery SVG jquery.svgdom.js:

function getClassNames(elem) {
    return (!$.svg.isSVGElem(elem) ? elem.className :
        (elem.className ? elem.className.baseVal : elem.getAttribute('class'))) || '';
}

This function will detect if an element is an SVG element, and if it is it will use the baseVal property of the SVGAnimatedString object if available, before falling back on the class attribute.

jQuery's historical stance on the issue:

jQuery currently lists this issue on their Won’t Fix page. Here is the relevant parts.

SVG/VML or Namespaced Elements Bugs

jQuery is primarily a library for the HTML DOM, so most problems related to SVG/VML documents or namespaced elements are out of scope. We do try to address problems that "bleed through" to HTML documents, such as events that bubble out of SVG.

Evidently jQuery considered full SVG support outside the scope of the jQuery core, and better suited for plugins.

UICollectionView cell selection and cell reuse

I had a horizontal scrolling collection view (I use collection view in Tableview) and I too faced problems withcell reuse, whenever I select one item and scroll towards right, some other cells in the next visible set gets select automatically. Trying to solve this using any custom cell properties like "selected", highlighted etc didnt help me so I came up with the below solution and this worked for me.

Step1:

Create a variable in the collectionView to store the selected index, here I have used a class level variable called selectedIndex

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    MyCVCell *cell = (MyCVCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"MyCVCell" forIndexPath:indexPath];    

// When scrolling happens, set the selection status only if the index matches the selected Index

if (selectedIndex == indexPath.row) {

        cell.layer.borderWidth = 1.0;

        cell.layer.borderColor = [[UIColor redColor] CGColor];

    }
    else
    {
        // Turn off the selection
        cell.layer.borderWidth = 0.0;

    }
    return cell;

}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{
    MyCVCell *cell = (MyCVCell *)[collectionView cellForItemAtIndexPath:indexPath];
    // Set the index once user taps on a cell
    selectedIndex = indexPath.row;
    // Set the selection here so that selection of cell is shown to ur user immediately
    cell.layer.borderWidth = 1.0;
    cell.layer.borderColor = [[UIColor redColor] CGColor];
    [cell setNeedsDisplay];
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath

{

    MyCVCell *cell = (MyCVCell *)[collectionView cellForItemAtIndexPath:indexPath];

    // Set the index to an invalid value so that the cells get deselected
    selectedIndex = -1;
    cell.layer.borderWidth = 0.0;
    [cell setNeedsDisplay];

}

-anoop

How to undo 'git reset'?

Old question, and the posted answers work great. I'll chime in with another option though.

git reset ORIG_HEAD

ORIG_HEAD references the commit that HEAD previously referenced.

Python Timezone conversion

Time conversion

To convert a time in one timezone to another timezone in Python, you could use datetime.astimezone():

so, below code is to convert the local time to other time zone.

  • datetime.datetime.today() - return current the local time
  • datetime.astimezone() - convert the time zone, but we have to pass the time zone.
  • pytz.timezone('Asia/Kolkata') -passing the time zone to pytz module
  • Strftime - Convert Datetime to string
# Time conversion from local time
import datetime
import pytz
dt_today = datetime.datetime.today()   # Local time
dt_India = dt_today.astimezone(pytz.timezone('Asia/Kolkata')) 
dt_London = dt_today.astimezone(pytz.timezone('Europe/London'))
India = (dt_India.strftime('%m/%d/%Y %H:%M'))
London = (dt_London.strftime('%m/%d/%Y %H:%M'))
print("Indian standard time: "+India+" IST")
print("British Summer Time: "+London+" BST")

list all the time zone

import pytz
for tz in pytz.all_timezones:
    print(tz)

Laravel Eloquent - Get one Row

Try with it

$color = \App\Color::take(1)->first();

How to style components using makeStyles and still have lifecycle methods in Material UI?

Hi instead of using hook API, you should use Higher-order component API as mentioned here

I'll modify the example in the documentation to suit your need for class component

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/styles';
import Button from '@material-ui/core/Button';

const styles = theme => ({
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
});

class HigherOrderComponentUsageExample extends React.Component {
  
  render(){
    const { classes } = this.props;
    return (
      <Button className={classes.root}>This component is passed to an HOC</Button>
      );
  }
}

HigherOrderComponentUsageExample.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(HigherOrderComponentUsageExample);

Recommended website resolution (width and height)?

All of the answers so far talk about desktop monitors, but I'm using stack overflow on my iPhone and I don't think you should exclude any mobile platform by targeting 1024 or 1280 horizontal pixels. Mark up your page so the browser knows what it all means and making it usable will come for free, even on screen readers and other kit you haven't thought of.

Get the current script file name

alex's answer is correct but you could also do this without regular expressions like so:

str_replace(".php", "", basename($_SERVER["SCRIPT_NAME"]));

"ssl module in Python is not available" when installing package with pip3

If in windows and using anaconda, than I solved it by first,

conda activate
pip install <lib>

This worked for me.

how to pass parameter from @Url.Action to controller function

you can pass it this way :

Url.Action("CreatePerson", "Person", new RouteValueDictionary(new { id = id }));

OR can also pass this way

Url.Action("CreatePerson", "Person", new { id = id });

Difference between string and text in rails?

If the attribute is matching f.text_field in form use string, if it is matching f.text_area use text.

PHP: Update multiple MySQL fields in single query

Add your multiple columns with comma separations:

UPDATE settings SET postsPerPage = $postsPerPage, style= $style WHERE id = '1'

However, you're not sanitizing your inputs?? This would mean any random hacker could destroy your database. See this question: What's the best method for sanitizing user input with PHP?

Also, is style a number or a string? I'm assuming a string, so it would need to be quoted.

What is polymorphism, what is it for, and how is it used?

Polymorphism gives you the ability to create one module calling another, and yet have the compile time dependency point against the flow of control instead of with the flow of control.

By using polymorphism, a high level module does not depend on low-level module. Both depend on abstractions. This helps us to apply the dependency inversion principle(https://en.wikipedia.org/wiki/Dependency_inversion_principle).

This is where I found the above definition. Around 50 minutes into the video the instructor explains the above. https://www.youtube.com/watch?v=TMuno5RZNeE

How to show changed file name only with git log?

Thanks for your answers, @mvp, @xero, I get what I want base on both of your answers.

git log --name-only 

or

git log --name-only --oneline

for short.

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

In my case I have to use something like <username>@<domain> to successfully login.

sample_user@sample_domain

Static Block in Java

Static blocks are used for initializaing the code and will be executed when JVM loads the class.Refer to the below link which gives the detailed explanation. http://www.jusfortechies.com/java/core-java/static-blocks.php

What is the "assert" function?

C++11 N3337 standard draft

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf

19.3 Assertions

1 The header <cassert>, described in (Table 42), provides a macro for documenting C ++ program assertions and a mechanism for disabling the assertion checks.

2 The contents are the same as the Standard C library header <assert.h>.

C99 N1256 standard draft

http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf

7.2 Diagnostics <assert.h>

1 The header <assert.h> defines the assert macro and refers to another macro, NDEBUG which is not defined by <assert.h>. If NDEBUG is defined as a macro name at the point in the source file where <assert.h> is included, the assert macro is defined simply as

 #define assert(ignore) ((void)0)

The assert macro is redefined according to the current state of NDEBUG each time that <assert.h> is included.

2. The assert macro shall be implemented as a macro, not as an actual function. If the macro definition is suppressed in order to access an actual function, the behavior is undefined.

7.2.1 Program diagnostics

7.2.1.1 The assert macro

Synopsis

1.

#include <assert.h>
void assert(scalar expression);

Description

2 The assert macro puts diagnostic tests into programs; it expands to a void expression. When it is executed, if expression (which shall have a scalar type) is false (that is, compares equal to 0), the assert macro writes information about the particular call that failed (including the text of the argument, the name of the source file, the source line number, and the name of the enclosing function — the latter are respectively the values of the preprocessing macros __FILE__ and __LINE__ and of the identifier __func__) on the standard error stream in an implementation-defined format. 165) It then calls the abort function.

Returns

3 The assert macro returns no value.

Pass a data.frame column name to a function

With dplyr it's now also possible to access a specific column of a dataframe by simply using double curly braces {{...}} around the desired column name within the function body, e.g. for col_name:

library(tidyverse)

fun <- function(df, col_name){
   df %>% 
     filter({{col_name}} == "test_string")
} 

Convert timedelta to total seconds

Use timedelta.total_seconds().

>>> import datetime
>>> datetime.timedelta(seconds=24*60*60).total_seconds()
86400.0

Best way to import Observable from rxjs

Rxjs v 6.*

It got simplified with newer version of rxjs .

1) Operators

import {map} from 'rxjs/operators';

2) Others

import {Observable,of, from } from 'rxjs';

Instead of chaining we need to pipe . For example

Old syntax :

source.map().switchMap().subscribe()

New Syntax:

source.pipe(map(), switchMap()).subscribe()

Note: Some operators have a name change due to name collisions with JavaScript reserved words! These include:

do -> tap,

catch -> catchError

switch -> switchAll

finally -> finalize


Rxjs v 5.*

I am writing this answer partly to help myself as I keep checking docs everytime I need to import an operator . Let me know if something can be done better way.

1) import { Rx } from 'rxjs/Rx';

This imports the entire library. Then you don't need to worry about loading each operator . But you need to append Rx. I hope tree-shaking will optimize and pick only needed funcionts( need to verify ) As mentioned in comments , tree-shaking can not help. So this is not optimized way.

public cache = new Rx.BehaviorSubject('');

Or you can import individual operators .

This will Optimize your app to use only those files :

2) import { _______ } from 'rxjs/_________';

This syntax usually used for main Object like Rx itself or Observable etc.,

Keywords which can be imported with this syntax

 Observable, Observer, BehaviorSubject, Subject, ReplaySubject

3) import 'rxjs/add/observable/__________';

Update for Angular 5

With Angular 5, which uses rxjs 5.5.2+

import { empty } from 'rxjs/observable/empty';
import { concat} from 'rxjs/observable/concat';

These are usually accompanied with Observable directly. For example

Observable.from()
Observable.of()

Other such keywords which can be imported using this syntax:

concat, defer, empty, forkJoin, from, fromPromise, if, interval, merge, of, 
range, throw, timer, using, zip

4) import 'rxjs/add/operator/_________';

Update for Angular 5

With Angular 5, which uses rxjs 5.5.2+

import { filter } from 'rxjs/operators/filter';
import { map } from 'rxjs/operators/map';

These usually come in the stream after the Observable is created. Like flatMap in this code snippet:

Observable.of([1,2,3,4])
          .flatMap(arr => Observable.from(arr));

Other such keywords using this syntax:

audit, buffer, catch, combineAll, combineLatest, concat, count, debounce, delay, 
distinct, do, every, expand, filter, finally, find , first, groupBy,
ignoreElements, isEmpty, last, let, map, max, merge, mergeMap, min, pluck, 
publish, race, reduce, repeat, scan, skip, startWith, switch, switchMap, take, 
takeUntil, throttle, timeout, toArray, toPromise, withLatestFrom, zip

FlatMap: flatMap is alias to mergeMap so we need to import mergeMap to use flatMap.


Note for /add imports :

We only need to import once in whole project. So its advised to do it at a single place. If they are included in multiple files, and one of them is deleted, the build will fail for wrong reasons.

AngularJS multiple filter with custom filter function

In view file (HTML or EJS)

<div ng-repeat="item in vm.itemList  | filter: myFilter > </div>

and In Controller

$scope.myFilter = function(item) {
return (item.propertyA === 'value' || item.propertyA === 'value');
}

Iterate through dictionary values?

You can just look for the value that corresponds with the key and then check if the input is equal to the key.

for key in PIX0:
    NUM = input("Which standard has a resolution of %s " % PIX0[key])
    if NUM == key:

Also, you will have to change the last line to fit in, so it will print the key instead of the value if you get the wrong answer.

print("I'm sorry but thats wrong. The correct answer was: %s." % key )

Also, I would recommend using str.format for string formatting instead of the % syntax.

Your full code should look like this (after adding in string formatting)

PIX0 = {"QVGA":"320x240", "VGA":"640x480", "SVGA":"800x600"}

for key in PIX0:
    NUM = input("Which standard has a resolution of {}".format(PIX0[key]))
    if NUM == key:
        print ("Nice Job!")
        count = count + 1
    else:
        print("I'm sorry but that's wrong. The correct answer was: {}.".format(key))

Adding an onclick event to a table row

Head stuck in jq for too long. This will work.

function addRowHandlers() {
    var table = document.getElementById("tableId");
    var rows = table.getElementsByTagName("tr");
    for (i = 1; i < rows.length; i++) {
        var row = table.rows[i];
        row.onclick = function(myrow){
                          return function() { 
                             var cell = myrow.getElementsByTagName("td")[0];
                             var id = cell.innerHTML;
                             alert("id:" + id);
                      };
                  }(row);
    }
}

Summarizing multiple columns with dplyr?

For completeness: with dplyr v0.2 ddply with colwise will also do this:

> ddply(df, .(grp), colwise(mean))
  grp        a    b        c        d
1   1 4.333333 4.00 1.000000 2.000000
2   2 2.000000 2.75 2.750000 2.750000
3   3 3.000000 4.00 4.333333 3.666667

but it is slower, at least in this case:

> microbenchmark(ddply(df, .(grp), colwise(mean)), 
                  df %>% group_by(grp) %>% summarise_each(funs(mean)))
Unit: milliseconds
                                            expr      min       lq     mean
                ddply(df, .(grp), colwise(mean))     3.278002 3.331744 3.533835
 df %>% group_by(grp) %>% summarise_each(funs(mean)) 1.001789 1.031528 1.109337

   median       uq      max neval
 3.353633 3.378089 7.592209   100
 1.121954 1.133428 2.292216   100

Passing base64 encoded strings in URL

Introductory Note I'm inclined to post a few clarifications since some of the answers here were a little misleading (if not incorrect).

The answer is NO, you cannot simply pass a base64 encoded parameter within a URL query string since plus signs are converted to a SPACE inside the $_GET global array. In other words, if you sent test.php?myVar=stringwith+sign to

//test.php
print $_GET['myVar'];

the result would be:
stringwith sign

The easy way to solve this is to simply urlencode() your base64 string before adding it to the query string to escape the +, =, and / characters to %## codes. For instance, urlencode("stringwith+sign") returns stringwith%2Bsign

When you process the action, PHP takes care of decoding the query string automatically when it populates the $_GET global. For example, if I sent test.php?myVar=stringwith%2Bsign to

//test.php
print $_GET['myVar'];

the result would is:
stringwith+sign

You do not want to urldecode() the returned $_GET string as +'s will be converted to spaces.
In other words if I sent the same test.php?myVar=stringwith%2Bsign to

//test.php
$string = urldecode($_GET['myVar']);
print $string;

the result is an unexpected:
stringwith sign

It would be safe to rawurldecode() the input, however, it would be redundant and therefore unnecessary.

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

My attempt.

Only acts if all text is lowercase or all uppercase, uses Locale case conversion. Attempts to respect intentional case difference or a ' or " in names. Happens on Blur as to not cause annoyances on phones. Although left in selection start/end so if changed to keyup maybe useful still. Should work on phones but have not tried.

$.fn.capitalize = function() {
    $(this).blur(function(event) {
        var box = event.target;
        var txt = $(this).val();
        var lc = txt.toLocaleLowerCase();
        var startingWithLowerCaseLetterRegex = new RegExp("\b([a-z])", "g");
        if (!/([-'"])/.test(txt) && txt === lc || txt === txt.toLocaleUpperCase()) {
            var stringStart = box.selectionStart;
            var stringEnd = box.selectionEnd;
            $(this).val(lc.replace(startingWithLowerCaseLetterRegex, function(c) { return c.toLocaleUpperCase() }).trim());
            box.setSelectionRange(stringStart, stringEnd);
        }
    });
   return this;
}

// Usage:
$('input[type=text].capitalize').capitalize();

Server.MapPath("."), Server.MapPath("~"), Server.MapPath(@"\"), Server.MapPath("/"). What is the difference?

Just to expand on @splattne's answer a little:

MapPath(string virtualPath) calls the following:

public string MapPath(string virtualPath)
{
    return this.MapPath(VirtualPath.CreateAllowNull(virtualPath));
}

MapPath(VirtualPath virtualPath) in turn calls MapPath(VirtualPath virtualPath, VirtualPath baseVirtualDir, bool allowCrossAppMapping) which contains the following:

//...
if (virtualPath == null)
{
    virtualPath = VirtualPath.Create(".");
}
//...

So if you call MapPath(null) or MapPath(""), you are effectively calling MapPath(".")

Calculating Covariance with Python and Numpy

When a and b are 1-dimensional sequences, numpy.cov(a,b)[0][1] is equivalent to your cov(a,b).

The 2x2 array returned by np.cov(a,b) has elements equal to

cov(a,a)  cov(a,b)

cov(a,b)  cov(b,b)

(where, again, cov is the function you defined above.)

C#: List All Classes in Assembly

I'd just like to add to Jon's example. To get a reference to your own assembly, you can use:

Assembly myAssembly = Assembly.GetExecutingAssembly();

System.Reflection namespace.

If you want to examine an assembly that you have no reference to, you can use either of these:

Assembly assembly = Assembly.ReflectionOnlyLoad(fullAssemblyName);
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(fileName);

If you intend to instantiate your type once you've found it:

Assembly assembly = Assembly.Load(fullAssemblyName);
Assembly assembly = Assembly.LoadFrom(fileName);

See the Assembly class documentation for more information.

Once you have the reference to the Assembly object, you can use assembly.GetTypes() like Jon already demonstrated.

Read file data without saving it in Flask

We simply did:

import io
from pathlib import Path

    def test_my_upload(self, accept_json):
        """Test my uploads endpoint for POST."""
        data = {
            "filePath[]": "/tmp/bin",
            "manifest[]": (io.StringIO(str(Path(__file__).parent /
                                           "path_to_file/npmlist.json")).read(),
                           'npmlist.json'),
        }
        headers = {
            'a': 'A',
            'b': 'B'
        }
        res = self.client.post(api_route_for('/test'),
                               data=data,
                               content_type='multipart/form-data',
                               headers=headers,
                               )
        assert res.status_code == 200

how to overlap two div in css?

check this fiddle , and if you want to move the overlapped div you set its position to absolute then change it's top and left values

Java: Check if enum contains a given string?

public boolean contains(Choices value) {
   return EnumSet.allOf(Choices.class).contains(value);
}

argparse module How to add option without any argument?

To create an option that needs no value, set the action [docs] of it to 'store_const', 'store_true' or 'store_false'.

Example:

parser.add_argument('-s', '--simulate', action='store_true')

How can I use jQuery to make an input readonly?

<html xmlns="http://www.w3.org/1999/xhtml">
<head >
    <title></title>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

</head>
<body>
    <div>
        <input id="fieldName" name="fieldName" type="text" class="text_box" value="Firstname" />
    </div>
</body>

<script type="text/javascript">
    $(function()
    {
        $('#fieldName').attr('disabled', 'disabled');

    });
</script>
</html>

Fixed position but relative to container

The answer is yes, as long as you don't set left: 0 or right: 0 after you set the div position to fixed.

http://jsfiddle.net/T2PL5/85/

Checkout the sidebar div. It is fixed, but related to the parent, not to the window view point.

_x000D_
_x000D_
body {
  background: #ccc;
}

.wrapper {
  margin: 0 auto;
  height: 1400px;
  width: 650px;
  background: green;
}

.sidebar {
  background-color: #ddd;
  float: left;
  width: 300px;
  height: 100px;
  position: fixed;
}

.main {
  float: right;
  background-color: yellow;
  width: 300px;
  height: 1400px;
}
_x000D_
<div class="wrapper">wrapper
  <div class="sidebar">sidebar</div>
  <div class="main">main</div>
</div>
_x000D_
_x000D_
_x000D_

How to request Location Permission at runtime

Google has created a library for easy Permissions management. Its called EasyPermissions

Here is a simple example on requesting Location permission using this library.

public class MainActivity extends AppCompatActivity {

    private final int REQUEST_LOCATION_PERMISSION = 1;

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

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @AfterPermissionGranted(REQUEST_LOCATION_PERMISSION)
    public void requestLocationPermission() {
        String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
        if(EasyPermissions.hasPermissions(this, perms)) {
            Toast.makeText(this, "Permission already granted", Toast.LENGTH_SHORT).show();
        }
        else {
            EasyPermissions.requestPermissions(this, "Please grant the location permission", REQUEST_LOCATION_PERMISSION, perms);
        }
    }
}

@AfterPermissionsGranted(REQUEST_CODE) is used to indicate the method that needs to be executed after a permission request with the request code REQUEST_CODE has been granted.

This above case, the method requestLocationPermission() method is called if the user grants the permission to access location services. So, that method acts as both a callback and a method to request the permissions.

You can implement separate callbacks for permission granted and permission denied as well. It is explained in the github page.

Android OnClickListener - identify a button

Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v.getId() == R.id.button1){
        Toast.makeText(context, "Button 1 Click", Toast.LENGTH_LONG).show();
    }
}

Check this article for more details

chai test array equality doesn't work as expected

This is how to use chai to deeply test associative arrays.

I had an issue trying to assert that two associative arrays were equal. I know that these shouldn't really be used in javascript but I was writing unit tests around legacy code which returns a reference to an associative array. :-)

I did it by defining the variable as an object (not array) prior to my function call:

var myAssocArray = {};   // not []
var expectedAssocArray = {};  // not []

expectedAssocArray['myKey'] = 'something';
expectedAssocArray['differentKey'] = 'something else';

// legacy function which returns associate array reference
myFunction(myAssocArray);

assert.deepEqual(myAssocArray, expectedAssocArray,'compare two associative arrays');

Delete all documents from index/type without deleting type

Elasticsearch 2.3 the option

    action.destructive_requires_name: true

in elasticsearch.yml do the trip

    curl -XDELETE http://localhost:9200/twitter/tweet

How to convert <font size="10"> to px?

This cannot be answered that easily. It depends on the font used and the points per inch (ppi). This should give an overview of the problem.

How to get the directory of the currently running file?

EDIT: As of Go 1.8 (Released February 2017) the recommended way of doing this is with os.Executable:

func Executable() (string, error)

Executable returns the path name for the executable that started the current process. There is no guarantee that the path is still pointing to the correct executable. If a symlink was used to start the process, depending on the operating system, the result might be the symlink or the path it pointed to. If a stable result is needed, path/filepath.EvalSymlinks might help.

To get just the directory of the executable you can use path/filepath.Dir.

Example:

package main

import (
    "fmt"
    "os"
    "path/filepath"
)

func main() {
    ex, err := os.Executable()
    if err != nil {
        panic(err)
    }
    exPath := filepath.Dir(ex)
    fmt.Println(exPath)
}

OLD ANSWER:

You should be able to use os.Getwd

func Getwd() (pwd string, err error)

Getwd returns a rooted path name corresponding to the current directory. If the current directory can be reached via multiple paths (due to symbolic links), Getwd may return any one of them.

For example:

package main

import (
    "fmt"
    "os"
)

func main() {
    pwd, err := os.Getwd()
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Println(pwd)
}

Read a javascript cookie by name

Unfortunately, Javascript's cookie syntax is nowhere near as nice as that. In fact, in my opinion, it's one of the worst designed parts.

When you try to read document.cookie, you get a string containing all the cookies set. You have to parse the string, separating by the semicolon ; character. Rather than writing this yourself, there are plenty of versions available on the web. My favourite is the one at quirksmode.org. This gives you createCookie, readCookie and deleteCookie functions.

C library function to perform sort

Use qsort() in <stdlib.h>.

@paxdiablo The qsort() function conforms to ISO/IEC 9899:1990 (``ISO C90'').

Clear variable in python

Actually, that does not delete the variable/property. All it will do is set its value to None, therefore the variable will still take up space in memory. If you want to completely wipe all existence of the variable from memory, you can just type:

del self.left

Remove a file from the list that will be committed

You want to do this:

git add -u
git reset HEAD path/to/file
git commit

Be sure and do this from the top level of the repo; add -u adds changes in the current directory (recursively).

The key line tells git to reset the version of the given path in the index (the staging area for the commit) to the version from HEAD (the currently checked-out commit).

And advance warning of a gotcha for others reading this: add -u stages all modifications, but doesn't add untracked files. This is the same as what commit -a does. If you want to add untracked files too, use add . to recursively add everything.

PKIX path building failed: unable to find valid certification path to requested target

If you do not need the SSL security then you might want to switch it off.

 /**
   * disable SSL
   */
  private void disableSslVerification() {
    try {
      // Create a trust manager that does not validate certificate chains
      TrustManager[] trustAllCerts = new TrustManager[] {
          new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
              return null;
            }

            public void checkClientTrusted(X509Certificate[] certs,
                String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs,
                String authType) {
            }
          } };

      // Install the all-trusting trust manager
      SSLContext sc = SSLContext.getInstance("SSL");
      sc.init(null, trustAllCerts, new java.security.SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

      // Create all-trusting host name verifier
      HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
          return true;
        }
      };

      // Install the all-trusting host verifier
      HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (KeyManagementException e) {
      e.printStackTrace();
    }
  }

How the single threaded non blocking IO model works in Node.js

The function c.query() has two argument

c.query("Fetch Data", "Post-Processing of Data")

The operation "Fetch Data" in this case is a DB-Query, now this may be handled by Node.js by spawning off a worker thread and giving it this task of performing the DB-Query. (Remember Node.js can create thread internally). This enables the function to return instantaneously without any delay

The second argument "Post-Processing of Data" is a callback function, the node framework registers this callback and is called by the event loop.

Thus the statement c.query (paramenter1, parameter2) will return instantaneously, enabling node to cater for another request.

P.S: I have just started to understand node, actually I wanted to write this as comment to @Philip but since didn't have enough reputation points so wrote it as an answer.

Hibernate Error: a different object with the same identifier value was already associated with the session

Transfer the task of assigning the object ID from Hibernate to the database by using:

<generator class="native"/>

This solved the problem for me.

How to use Typescript with native ES6 Promises

I had to downgrade @types/core-js to 9.36 to get it to work with "target": "es5" set in my tsconfig.

"@types/core-js": "0.9.36",

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

  1. Please check current version of your Kotlin in below path,

    C:\Program Files\Android\Android Studio\gradle\m2repository\org\jetbrains\kotlin\kotlin-stdlib\1.0.5

change to that version (1.0.5) in project level gradle file.

You can see in your above path does not mentioned any Java - jre version, so remove in your app level gradle file as below,

compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

How do I indent multiple lines at once in Notepad++?

The problem was with the QuickText plugin. After removing it, indent worked as normal.

What are examples of TCP and UDP in real life?

One additional thought on some of the comments above that talks about ordered delivery.... It must be clarified that the destination computer may receive packets out of order on the wire, but the TCP at the destination is responsible for "rearranging out-of-order data" before passing it on to the upper layers of the stack. When you say TCP guarantees ordered packet delivery, what that means is it will deliver packets in correct order to the upper layers of the stack.

CMake link to external library

One more alternative, in the case you are working with the Appstore, need "Entitlements" and as such need to link with an Apple-Framework.

For Entitlements to work (e.g. GameCenter) you need to have a "Link Binary with Libraries"-buildstep and then link with "GameKit.framework". CMake "injects" the libraries on a "low level" into the commandline, hence Xcode doesn't really know about it, and as such you will not get GameKit enabled in the Capabilities screen.

One way to use CMake and have a "Link with Binaries"-buildstep is to generate the xcodeproj with CMake, and then use 'sed' to 'search & replace' and add the GameKit in the way XCode likes it...

The script looks like this (for Xcode 6.3.1).

s#\/\* Begin PBXBuildFile section \*\/#\/\* Begin PBXBuildFile section \*\/\
    26B12AA11C10544700A9A2BA \/\* GameKit.framework in Frameworks \*\/ = {isa = PBXBuildFile; fileRef = 26B12AA01C10544700A9A2BA \/\* GameKit.framework xxx\*\/; };#g

s#\/\* Begin PBXFileReference section \*\/#\/\* Begin PBXFileReference section \*\/\
    26B12AA01C10544700A9A2BA \/\* GameKit.framework xxx\*\/ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GameKit.framework; path = System\/Library\/Frameworks\/GameKit.framework; sourceTree = SDKROOT; };#g

s#\/\* End PBXFileReference section \*\/#\/\* End PBXFileReference section \*\/\
\
\/\* Begin PBXFrameworksBuildPhase section \*\/\
    26B12A9F1C10543B00A9A2BA \/\* Frameworks \*\/ = {\
        isa = PBXFrameworksBuildPhase;\
        buildActionMask = 2147483647;\
        files = (\
            26B12AA11C10544700A9A2BA \/\* GameKit.framework in Frameworks xxx\*\/,\
        );\
        runOnlyForDeploymentPostprocessing = 0;\
    };\
\/\* End PBXFrameworksBuildPhase section \*\/\
#g

s#\/\* CMake PostBuild Rules \*\/,#\/\* CMake PostBuild Rules \*\/,\
            26B12A9F1C10543B00A9A2BA \/\* Frameworks xxx\*\/,#g
s#\/\* Products \*\/,#\/\* Products \*\/,\
            26B12AA01C10544700A9A2BA \/\* GameKit.framework xxx\*\/,#g

save this to "gamecenter.sed" and then "apply" it like this ( it changes your xcodeproj! )

sed -i.pbxprojbak -f gamecenter.sed myproject.xcodeproj/project.pbxproj

You might have to change the script-commands to fit your need.

Warning: it's likely to break with different Xcode-version as the project-format could change, the (hardcoded) unique number might not really by unique - and generally the solutions by other people are better - so unless you need to Support the Appstore + Entitlements (and automated builds), don't do this.

This is a CMake bug, see http://cmake.org/Bug/view.php?id=14185 and http://gitlab.kitware.com/cmake/cmake/issues/14185