Programs & Examples On #Data representation

What is “2's Complement”?

Many of the answers so far nicely explain why two's complement is used to represent negative number, but do not tell us what two's complement number is, particularly not why a '1' is added, and in fact often added in a wrong way.

The confusion comes from a poor understanding of the definition of a complement number. A complement is the missing part that would make something complete.

The radix complement of an n digit number x in radix b is, by definition, b^n-x. In binary 4 is represent by 100, which has 3 digits (n=3) and a radix of 2 (b=2). So its radix complement is b^n-x = 2^3-4=8-4=4 (or 100 in binary).

However, in binary obtaining a radix's complement is not as easy as getting its diminished radix complement, which is defined as (b^n-1)-y, just 1 less than that of radix complement. To get a diminished radix complement, you simply flip all the digits.

100 -> 011 (diminished (one's) radix complement)

to obtain the radix (two's) complement, we simply add 1, as the definition defined.

011 +1 ->100 (two's complement).

Now with this new understanding, let's take a look of the example given by Vincent Ramdhanie (see above second response)

/* start of Vincent

Converting 1111 to decimal:

The number starts with 1, so it's negative, so we find the complement of 1111, which is 0000. Add 1 to 0000, and we obtain 0001. Convert 0001 to decimal, which is 1. Apply the sign = -1. Tada!

end of Vincent */

Should be understood as

The number starts with 1, so it's negative. So we know it is a two's complement of some value x. To find the x represented by its two's complement, we first need find its 1's complement.

two's complement of x: 1111 one's complement of x: 1111-1 ->1110; x = 0001, (flip all digits)

apply the sign -, and the answer =-x =-1.

How to do a SOAP wsdl web services call from the command line

For Windows:

Save the following as MSFT.vbs:

set SOAPClient = createobject("MSSOAP.SOAPClient")
SOAPClient.mssoapinit "https://sandbox.mediamind.com/Eyeblaster.MediaMind.API/V2/AuthenticationService.svc?wsdl"
WScript.Echo "MSFT = " & SOAPClient.GetQuote("MSFT")

Then from a command prompt, run:

C:\>MSFT.vbs

Reference: http://blogs.msdn.com/b/bgroth/archive/2004/10/21/246155.aspx

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

I have just cooked up another solution for this, where it's not longer necessary to use a -much to high- max-height value. It needs a few lines of javascript code to calculate the inner height of the collapsed DIV but after that, it's all CSS.

1) Fetching and setting height

Fetch the inner height of the collapsed element (using scrollHeight). My element has a class .section__accordeon__content and I actually run this in a forEach() loop to set the height for all panels, but you get the idea.

document.querySelectorAll( '.section__accordeon__content' ).style.cssText = "--accordeon-height: " + accordeonPanel.scrollHeight + "px";

2) Use the CSS variable to expand the active item

Next, use the CSS variable to set the max-height value when the item has an .active class.

.section__accordeon__content.active {
  max-height: var(--accordeon-height);
}

Final example

So the full example goes like this: first loop through all accordeon panels and store their scrollHeight values as CSS variables. Next use the CSS variable as the max-height value on the active/expanded/open state of the element.

Javascript:

document.querySelectorAll( '.section__accordeon__content' ).forEach(
  function( accordeonPanel ) {
    accordeonPanel.style.cssText = "--accordeon-height: " + accordeonPanel.scrollHeight + "px";
  }
);

CSS:

.section__accordeon__content {
  max-height: 0px;
  overflow: hidden;
  transition: all 425ms cubic-bezier(0.465, 0.183, 0.153, 0.946);
}

.section__accordeon__content.active {
  max-height: var(--accordeon-height);
}

And there you have it. A adaptive max-height animation using only CSS and a few lines of JavaScript code (no jQuery required).

Hope this helps someone in the future (or my future self for reference).

Call external javascript functions from java code

Use ScriptEngine.eval(java.io.Reader) to read the script

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// read script file
engine.eval(Files.newBufferedReader(Paths.get("C:/Scripts/Jsfunctions.js"), StandardCharsets.UTF_8));

Invocable inv = (Invocable) engine;
// call function from script file
inv.invokeFunction("yourFunction", "param");

How to maintain a Unique List in Java?

You may want to use one of the implementing class of java.util.Set<E> Interface e.g. java.util.HashSet<String> collection class.

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

How can one see content of stack with GDB?

Use:

  • bt - backtrace: show stack functions and args
  • info frame - show stack start/end/args/locals pointers
  • x/100x $sp - show stack memory
(gdb) bt
#0  zzz () at zzz.c:96
#1  0xf7d39cba in yyy (arg=arg@entry=0x0) at yyy.c:542
#2  0xf7d3a4f6 in yyyinit () at yyy.c:590
#3  0x0804ac0c in gnninit () at gnn.c:374
#4  main (argc=1, argv=0xffffd5e4) at gnn.c:389

(gdb) info frame
Stack level 0, frame at 0xffeac770:
 eip = 0x8049047 in main (goo.c:291); saved eip 0xf7f1fea1
 source language c.
 Arglist at 0xffeac768, args: argc=1, argv=0xffffd5e4
 Locals at 0xffeac768, Previous frame's sp is 0xffeac770
 Saved registers:
  ebx at 0xffeac75c, ebp at 0xffeac768, esi at 0xffeac760, edi at 0xffeac764, eip at 0xffeac76c

(gdb) x/10x $sp
0xffeac63c: 0xf7d39cba  0xf7d3c0d8  0xf7d3c21b  0x00000001
0xffeac64c: 0xf78d133f  0xffeac6f4  0xf7a14450  0xffeac678
0xffeac65c: 0x00000000  0xf7d3790e

How to get the date and time values in a C program?

The answers given above are good CRT answers, but if you want you can also use the Win32 solution to this. It's almost identical but IMO if you're programming for Windows you might as well just use its API (although I don't know if you are programming in Windows).

char* arrDayNames[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; 
SYSTEMTIME st;
GetLocalTime(&st); // Alternatively use GetSystemTime for the UTC version of the time
printf("The current date and time are: %d/%d/%d %d:%d:%d:%d", st.wDay, st.wMonth, st.wYear, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
printf("The day is: %s", arrDayNames[st.wDayOfWeek]);

Anyway, this is a Windows solution. I hope it will be helpful for you sometime!

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

Server.MapPath specifies the relative or virtual path to map to a physical directory.

  • Server.MapPath(".")1 returns the current physical directory of the file (e.g. aspx) being executed
  • Server.MapPath("..") returns the parent directory
  • Server.MapPath("~") returns the physical path to the root of the application
  • Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)

An example:

Let's say you pointed a web site application (http://www.example.com/) to

C:\Inetpub\wwwroot

and installed your shop application (sub web as virtual directory in IIS, marked as application) in

D:\WebApps\shop

For example, if you call Server.MapPath() in following request:

http://www.example.com/shop/products/GetProduct.aspx?id=2342

then:

  • Server.MapPath(".")1 returns D:\WebApps\shop\products
  • Server.MapPath("..") returns D:\WebApps\shop
  • Server.MapPath("~") returns D:\WebApps\shop
  • Server.MapPath("/") returns C:\Inetpub\wwwroot
  • Server.MapPath("/shop") returns D:\WebApps\shop

If Path starts with either a forward slash (/) or backward slash (\), the MapPath() returns a path as if Path was a full, virtual path.

If Path doesn't start with a slash, the MapPath() returns a path relative to the directory of the request being processed.

Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.

Footnotes

  1. Server.MapPath(null) and Server.MapPath("") will produce this effect too.

How to create dynamic href in react render function?

Use string concatenation:

href={'/posts/' + post.id}

The JSX syntax allows either to use strings or expressions ({...}) as values. You cannot mix both. Inside an expression you can, as the name suggests, use any JavaScript expression to compute the value.

Angularjs: input[text] ngChange fires while the value is changing

In case anyone else looking for additional "enter" keypress support, here's an update to the fiddle provided by Gloppy

Code for keypress binding:

elm.bind("keydown keypress", function(event) {
    if (event.which === 13) {
        scope.$apply(function() {
            ngModelCtrl.$setViewValue(elm.val());
        });
    }
});

jQuery: select all elements of a given class, except for a particular Id

You could use the .not function like the following examples to remove items that have an exact id, id containing a specific word, id starting with a word, etc... see http://www.w3schools.com/jquery/jquery_ref_selectors.asp for more information on jQuery selectors.

Ignore by Exact ID:

 $(".thisClass").not('[id="thisId"]').doAction();

Ignore ID's that contains the word "Id"

$(".thisClass").not('[id*="Id"]').doAction();

Ignore ID's that start with "my"

$(".thisClass").not('[id^="my"]').doAction();

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

Fit cell width to content

There are many ways to do this!

correct me if I'm wrong but the question is looking for this kind of result.

<table style="white-space:nowrap;width:100%;">
<tr>
<td class="block" style="width:50%">this should stretch</td>
<td class="block" style="width:50%">this should stretch</td>
<td class="block" style="width:auto">this should be the content width</td>
</tr>
</table>

The first 2 fields will "share" the remaining page (NOTE: if you add more text to either 50% fields it will take more space), and the last field will dominate the table constantly.

If you are happy to let text wrap you can move white-space:nowrap; to the style of the 3rd field
will be the only way to start a new line in that field.

alternatively, you can set a length on the last field ie. width:150px, and leave percentage's on the first 2 fields.

Hope this helps!

Error: TypeError: $(...).dialog is not a function

I just experienced this with the line:

$('<div id="editor" />').dialogelfinder({

I got the error "dialogelfinder is not a function" because another component was inserting a call to load an older version of JQuery (1.7.2) after the newer version was loaded.

As soon as I commented out the second load, the error went away.

Facebook Javascript SDK Problem: "FB is not defined"

Use a setTimeout, because sometimes the FB.init takes some time to get declared

function testAPI() {
     console.log('Welcome!  Fetching your information.... ');
     FB.api('/me', function(response) {
         console.log('Good to see you, ' + response.name + '.');
     });
}
function login() {
    FB.login(function(response) {
        if (response.authResponse) {
            testAPI();
        } else {
            // cancelled
        }
    });
}
setTimeout(function() {
    login();
},2000);

Java: Reading a file into an array

Apache Commons I/O provides FileUtils#readLines(), which should be fine for all but huge files: http://commons.apache.org/io/api-release/index.html. The 2.1 distribution includes FileUtils.lineIterator(), which would be suitable for large files. Google's Guava libraries include similar utilities.

How can I print out all possible letter combinations a given phone number can represent?

public class Permutation {

    //display all combination attached to a 3 digit number

    public static void main(String ar[]){

            char data[][]= new char[][]{{'a','k','u'},
                                {'b','l','v'},
                                {'c','m','w'},
                                {'d','n','x'},
                                {'e','o','y'},
                                {'f','p','z'},
                                {'g','q','0'},
                                {'h','r','0'},
                                {'i','s','0'},
                                {'j','t','0'}};


        int num1, num2, num3=0;
        char tempdata[][]= new char[3][3];
        StringBuilder number = new StringBuilder("324"); // a 3 digit number

        //copy data to a tempdata array-------------------
        num1= Integer.parseInt(number.substring(0,1));
        tempdata[0] = data[num1];
        num2= Integer.parseInt(number.substring(1,2));
        tempdata[1] = data[num2];
        num3= Integer.parseInt(number.substring(2,3));
        tempdata[2] = data[num3];

        //display all combinations--------------------
        char temp2[][]=tempdata;
        char tempd, tempd2;
        int i,i2, i3=0;
        for(i=0;i<3;i++){
                tempd = temp2[0][i];
             for (i2=0;i2<3;i2++){
                 tempd2 = temp2[1][i2];
                 for(i3=0;i3<3;i3++){
                     System.out.print(tempd);
                     System.out.print(tempd2);
                     System.out.print(temp2[2][i3]);
                     System.out.println();
                 }//for i3

            }//for i2
         }
    }

}//end of class

I need an unordered list without any bullets

If you're unable to make it work at the <ul> level, you might need to place the list-style-type: none; at the <li> level:

<ul>
    <li style="list-style-type: none;">Item 1</li>
    <li style="list-style-type: none;">Item 2</li>
</ul>

You can create a CSS class to avoid this repetition:

<style>
ul.no-bullets li
{
    list-style-type: none;
}
</style>

<ul class="no-bullets">
    <li>Item 1</li>
    <li>Item 2</li>
</ul>

When necessary, use !important:

<style>
ul.no-bullets li
{
    list-style-type: none !important;
}
</style>

Differences between Html.TextboxFor and Html.EditorFor in MVC and Razor

TextBoxFor: It will render like text input html element corresponding to specified expression. In simple word it will always render like an input textbox irrespective datatype of the property which is getting bind with the control.

EditorFor: This control is bit smart. It renders HTML markup based on the datatype of the property. E.g. suppose there is a boolean property in model. To render this property in the view as a checkbox either we can use CheckBoxFor or EditorFor. Both will be generate the same markup.

What is the advantage of using EditorFor?

As we know, depending on the datatype of the property it generates the html markup. So suppose tomorrow if we change the datatype of property in the model, no need to change anything in the view. EditorFor control will change the html markup automatically.

How to sort an STL vector?

std::sort(object.begin(), object.end(), pred());

where, pred() is a function object defining the order on objects of myclass. Alternatively, you can define myclass::operator<.

For example, you can pass a lambda:

std::sort(object.begin(), object.end(),
          [] (myclass const& a, myclass const& b) { return a.v < b.v; });

Or if you're stuck with C++03, the function object approach (v is the member on which you want to sort):

struct pred {
    bool operator()(myclass const & a, myclass const & b) const {
        return a.v < b.v;
    }
};

How do you tell if a checkbox is selected in Selenium for Java?

 if(checkBox.getAttribute("checked") != null) // if Checked 
    checkBox.click();                         //to Uncheck it 

You can also add an and statement to be sure if checked is true.

How to iterate for loop in reverse order in swift?

You can use reversed() method for easily reverse values.

var i:Int
for i in 1..10.reversed() {
    print(i)
}

The reversed() method reverse the values.

How do I get video durations with YouTube API version 3?

I got it!

$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vId&key=dldfsd981asGhkxHxFf6JqyNrTqIeJ9sjMKFcX4");

$duration = json_decode($dur, true);
foreach ($duration['items'] as $vidTime) {
    $vTime= $vidTime['contentDetails']['duration'];
}

There it returns the time for YouTube API version 3 (the key is made up by the way ;). I used $vId that I had gotten off of the returned list of the videos from the channel I am showing the videos from...

It works. Google REALLY needs to include the duration in the snippet so you can get it all with one call instead of two... it's on their 'wontfix' list.

Flask raises TemplateNotFound error even though template file exists

I think Flask uses the directory templates by default. So your code should be like this

suppose this is your hello.py

from flask import Flask,render_template

app=Flask(__name__,template_folder='template')


@app.route("/")
def home():
    return render_template('home.html')

@app.route("/about/")
def about():
    return render_template('about.html')

if __name__=="__main__":
    app.run(debug=True)

And you work space structure like

project/
    hello.py        
    template/
         home.html
         about.html    
    static/
           js/
             main.js
           css/
               main.css

also you have create two html files with name of home.html and about.html and put those files in templates folder.

Seeding the random number generator in Javascript

A simple approach for a fixed seed:

function fixedrandom(p){
    const seed = 43758.5453123;
    return (Math.abs(Math.sin(p)) * seed)%1;
}

What does the symbol \0 mean in a string-literal?

The length of the array is 7, the NUL character \0 still counts as a character and the string is still terminated with an implicit \0

See this link to see a working example

Note that had you declared str as char str[6]= "Hello\0"; the length would be 6 because the implicit NUL is only added if it can fit (which it can't in this example.)

§ 6.7.8/p14
An array of character type may be initialized by a character string literal, optionally enclosed in braces. Sucessive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

Examples

char str[] = "Hello\0"; /* sizeof == 7, Explicit + Implicit NUL */
char str[5]= "Hello\0"; /* sizeof == 5, str is "Hello" with no NUL (no longer a C-string, just an array of char). This may trigger compiler warning */
char str[6]= "Hello\0"; /* sizeof == 6, Explicit NUL only */
char str[7]= "Hello\0"; /* sizeof == 7, Explicit + Implicit NUL */
char str[8]= "Hello\0"; /* sizeof == 8, Explicit + two Implicit NUL */

Django Forms: if not valid, show form with error message

UPDATE: Added a more detailed description of the formset errors.


Form.errors combines all field and non_field_errors. Therefore you can simplify the html to this:

template

    {% load form_tags %}

    {% if form.errors %}
    <div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
        <div id="form_errors">
            {% for key, value in form.errors.items %}
                <span class="fieldWrapper">
                    {{ key }}:{{ value }}
                </span>
            {% endfor %}
        </div>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    {% endif %}


If you want to generalise it you can create a list_errors.html which you include in every form template. It handles form and formset errors:

    {% if form.errors %}
    <div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
        <div id="form_errors">

            {% for key, value in form.errors.items %}
                <span class="fieldWrapper">
                    {{ key }}:{{ value }}
                </span>
            {% endfor %}
        </div>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    {% elif formset.total_error_count %}
    <div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
        <div id="form_errors">
            {% if formset.non_form_errors %}
                {{ formset.non_form_errors }}
            {% endif %}
            {% for form in formset.forms %}
                {% if form.errors %}
                    Form number {{ forloop.counter }}:
                    <ul class="errorlist">
                    {% for key, error in form.errors.items %}
                        <li>{{form.fields|get_label:key}}
                            <ul class="errorlist">
                                <li>{{error}}</li>
                            </ul>
                        </li>
                    {% endfor %}
                    </ul>
                {% endif %}
            {% endfor %}

        </div>
    </div>

    {% endif %}

form_tags.py

from django import template

register = template.Library()


def get_label(a_dict, key):
    return getattr(a_dict.get(key), 'label', 'No label')


register.filter("get_label", get_label)

One caveat: In contrast to forms Formset.errors does not include non_field_errors.

Scanner vs. BufferedReader

I prefer Scanner because it doesn't throw checked exceptions and therefore it's usage results in a more streamlined code.

How to parse json string in Android?

Below is the link which guide in parsing JSON string in android.

http://www.ibm.com/developerworks/xml/library/x-andbene1/?S_TACT=105AGY82&S_CMP=MAVE

Also according to your json string code snippet must be something like this:-

JSONObject mainObject = new JSONObject(yourstring);

JSONObject universityObject = mainObject.getJSONObject("university");
JSONString name = universityObject.getString("name");  
JSONString url = universityObject.getString("url");

Following is the API reference for JSOnObject: https://developer.android.com/reference/org/json/JSONObject.html#getString(java.lang.String)

Same for other object.

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

import the HttpClientModule in your app.module.ts

import {HttpClientModule} from '@angular/common/http';

...
@NgModule({
...
  imports: [
    //other content,
    HttpClientModule
  ]
})

Promise.all().then() resolve?

But that doesn't seem like the proper way to do it..

That is indeed the proper way to do it (or at least a proper way to do it). This is a key aspect of promises, they're a pipeline, and the data can be massaged by the various handlers in the pipeline.

Example:

_x000D_
_x000D_
const promises = [_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
  .then(data => {_x000D_
    console.log("First handler", data);_x000D_
    return data.map(entry => entry * 10);_x000D_
  })_x000D_
  .then(data => {_x000D_
    console.log("Second handler", data);_x000D_
  });
_x000D_
_x000D_
_x000D_

(catch handler omitted for brevity. In production code, always either propagate the promise, or handle rejection.)

The output we see from that is:

First handler [1,2]
Second handler [10,20]

...because the first handler gets the resolution of the two promises (1 and 2) as an array, and then creates a new array with each of those multiplied by 10 and returns it. The second handler gets what the first handler returned.

If the additional work you're doing is synchronous, you can also put it in the first handler:

Example:

_x000D_
_x000D_
const promises = [_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
  .then(data => {_x000D_
    console.log("Initial data", data);_x000D_
    data = data.map(entry => entry * 10);_x000D_
    console.log("Updated data", data);_x000D_
    return data;_x000D_
  });
_x000D_
_x000D_
_x000D_

...but if it's asynchronous you won't want to do that as it ends up getting nested, and the nesting can quickly get out of hand.

How to reset a select element with jQuery

Try this. This will work. $('#baba').prop('selectedIndex',0);

Check here http://jsfiddle.net/bibin_v/R4s3U/

Docker compose, running containers in net:host

Maybe I am answering very late. But I was also having a problem configuring host network in docker compose. Then I read the documentation thoroughly and made the changes and it worked. Please note this configuration is for docker-compose version "3.7". Here einwohner_net and elk_net_net are my user-defined networks required for my application. I am using host net to get some system metrics.

Link To Documentation https://docs.docker.com/compose/compose-file/#host-or-none

version: '3.7'
services:
  app:
    image: ramansharma/einwohnertomcat:v0.0.1
    deploy:
      replicas: 1
      ports:
       - '8080:8080'
    volumes:
     - type: bind
       source: /proc
       target: /hostfs/proc
       read_only: true
     - type: bind
       source: /sys/fs/cgroup
       target: /hostfs/sys/fs/cgroup
       read_only: true
     - type: bind
       source: /
       target: /hostfs
       read_only: true
    networks:
     hostnet: {}
    networks:
     - einwohner_net
     - elk_elk_net
networks:
 einwohner_net:
 elk_elk_net:
   external: true
 hostnet:
   external: true
   name: host

Python read in string from file and split it into values

Something like this - for each line read into string variable a:

>>> a = "123,456"
>>> b = a.split(",")
>>> b
['123', '456']
>>> c = [int(e) for e in b]
>>> c
[123, 456]
>>> x, y = c
>>> x
123
>>> y
456

Now you can do what is necessary with x and y as assigned, which are integers.

What is the easiest way to remove the first character from a string?

We can use slice to do this:

val = "abc"
 => "abc" 
val.slice!(0)
 => "a" 
val
 => "bc" 

Using slice! we can delete any character by specifying its index.

Find Facebook user (url to profile page) by known email address

Simply use the graph API with this url format: https://graph.facebook.com/[email protected]&type=user&access_token=... You can easily create an application here and grab an access token for it here. I believe you get an estimated 600 requests per 600 seconds, although this isn't documented.

If you are doing this in bulk, you could use batch requests in batches of 20 email addresses. This may help with rate limits (I am not sure if you get 600 batch requests per 600 seconds or 600 individual requests).

Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

You cannot display a lot of websites inside an iFrame. Reason being that they send an "X-Frame-Options: SAMEORIGIN" response header. This option prevents the browser from displaying iFrames that are not hosted on the same domain as the parent page. This is a security feature to prevent click-jacking. Some details at How to show google.com in an iframe?

This could be of some help : https://www.maketecheasier.com/create-survey-form-with-google-docs/

Where are static methods and static variables stored in Java?

When we create a static variable or method it is stored in the special area on heap: PermGen(Permanent Generation), where it lays down with all the data applying to classes(non-instance data). Starting from Java 8 the PermGen became - Metaspace. The difference is that Metaspace is auto-growing space, while PermGen has a fixed Max size, and this space is shared among all of the instances. Plus the Metaspace is a part of a Native Memory and not JVM Memory.

You can look into this for more details.

How to use icons and symbols from "Font Awesome" on Native Android Application

I made this helper class in C# (Xamarin) to programmatically set the text property. It which works pretty well for me:

internal static class FontAwesomeManager
{
    private static readonly Typeface AwesomeFont = Typeface.CreateFromAsset(App.Application.Context.Assets, "FontAwesome.ttf");

    private static readonly Dictionary<FontAwesomeIcon, string> IconMap = new Dictionary<FontAwesomeIcon, string>
    {
        {FontAwesomeIcon.Bars, "\uf0c9"},
        {FontAwesomeIcon.Calendar, "\uf073"},
        {FontAwesomeIcon.Child, "\uf1ae"},
        {FontAwesomeIcon.Cog, "\uf013"},
        {FontAwesomeIcon.Eye, "\uf06e"},
        {FontAwesomeIcon.Filter, "\uf0b0"},
        {FontAwesomeIcon.Link, "\uf0c1"},
        {FontAwesomeIcon.ListOrderedList, "\uf0cb"},
        {FontAwesomeIcon.PencilSquareOutline, "\uf044"},
        {FontAwesomeIcon.Picture, "\uf03e"},
        {FontAwesomeIcon.PlayCircleOutline, "\uf01d"},
        {FontAwesomeIcon.SignOut, "\uf08b"},
        {FontAwesomeIcon.Sliders, "\uf1de"}
    };

    public static void Awesomify(this TextView view, FontAwesomeIcon icon)
    {
        var iconString = IconMap[icon];

        view.Text = iconString;
        view.SetTypeface(AwesomeFont, TypefaceStyle.Normal);
    }
}

enum FontAwesomeIcon
{
    Bars,
    Calendar,
    Child,
    Cog,
    Eye,
    Filter,
    Link,
    ListOrderedList,
    PencilSquareOutline,
    Picture,
    PlayCircleOutline,
    SignOut,
    Sliders
}

Should be easy enough to convert to Java, I think. Hope it helps someone!

Text that shows an underline on hover

<span class="txt">Some Text</span>

.txt:hover {
    text-decoration: underline;
}

Align the form to the center in Bootstrap 4

<div class="d-flex justify-content-center align-items-center container ">

    <div class="row ">


        <form action="">
            <div class="form-group">
                <label for="inputUserName" class="control-label">Enter UserName</label>
                <input type="email" class="form-control" id="inputUserName" aria-labelledby="emailnotification">
                <small id="emailnotification" class="form-text text-muted">Enter Valid Email Id</small>
            </div>
            <div class="form-group">
                <label for="inputPassword" class="control-label">Enter Password</label>
                <input type="password" class="form-control" id="inputPassword" aria-labelledby="passwordnotification">

            </div>
        </form>

    </div>

</div>

How to find the Windows version from the PowerShell command line

To produce identical output to winver.exe in PowerShell v5 on Windows 10 1809:

$Version = Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\'
"Version $($Version.ReleaseId) (OS Build $($Version.CurrentBuildNumber).$($Version.UBR))"

jQuery/JavaScript: accessing contents of an iframe

I prefer to use other variant for accessing. From parent you can have a access to variable in child iframe. $ is a variable too and you can receive access to its just call window.iframe_id.$

For example, window.view.$('div').hide() - hide all divs in iframe with id 'view'

But, it doesn't work in FF. For better compatibility you should use

$('#iframe_id')[0].contentWindow.$

fetch gives an empty response body

Try to use response.json():

fetch('http://example.com/api/node', {
  mode: "no-cors",
  method: "GET",
  headers: {
    "Accept": "application/json"
  }
}).then((response) => {
  console.log(response.json()); // null
  return dispatch({
    type: "GET_CALL",
    response: response.json()
  });
})
.catch(error => { console.log('request failed', error); });

How do I read any request header in PHP

strtolower is lacking in several of the proposed solutions, RFC2616 (HTTP/1.1) defines header fields as case-insensitive entities. The whole thing, not just the value part.

So suggestions like only parsing HTTP_ entries are wrong.

Better would be like this:

if (!function_exists('getallheaders')) {
    foreach ($_SERVER as $name => $value) {
        /* RFC2616 (HTTP/1.1) defines header fields as case-insensitive entities. */
        if (strtolower(substr($name, 0, 5)) == 'http_') {
            $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
        }
    }
    $this->request_headers = $headers;
} else {
    $this->request_headers = getallheaders();
}

Notice the subtle differences with previous suggestions. The function here also works on php-fpm (+nginx).

Android ListView with Checkbox and all clickable

holder.checkbox.setTag(row_id);

and

holder.checkbox.setOnClickListener( new OnClickListener() {

                @Override
                public void onClick(View v) {
                    CheckBox c = (CheckBox) v;

                    int row_id = (Integer) v.getTag();

                    checkboxes.put(row_id, c.isChecked());


                }
        });

Java Replace Line In Text File

At the bottom, I have a general solution to replace lines in a file. But first, here is the answer to the specific question at hand. Helper function:

public static void replaceSelected(String replaceWith, String type) {
    try {
        // input the file content to the StringBuffer "input"
        BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
        StringBuffer inputBuffer = new StringBuffer();
        String line;

        while ((line = file.readLine()) != null) {
            inputBuffer.append(line);
            inputBuffer.append('\n');
        }
        file.close();
        String inputStr = inputBuffer.toString();

        System.out.println(inputStr); // display the original file for debugging

        // logic to replace lines in the string (could use regex here to be generic)
        if (type.equals("0")) {
            inputStr = inputStr.replace(replaceWith + "1", replaceWith + "0"); 
        } else if (type.equals("1")) {
            inputStr = inputStr.replace(replaceWith + "0", replaceWith + "1");
        }

        // display the new file for debugging
        System.out.println("----------------------------------\n" + inputStr);

        // write the new string with the replaced line OVER the same file
        FileOutputStream fileOut = new FileOutputStream("notes.txt");
        fileOut.write(inputStr.getBytes());
        fileOut.close();

    } catch (Exception e) {
        System.out.println("Problem reading file.");
    }
}

Then call it:

public static void main(String[] args) {
    replaceSelected("Do the dishes", "1");   
}

Original Text File Content:

Do the dishes0
Feed the dog0
Cleaned my room1

Output:

Do the dishes0
Feed the dog0
Cleaned my room1
----------------------------------
Do the dishes1
Feed the dog0
Cleaned my room1

New text file content:

Do the dishes1
Feed the dog0
Cleaned my room1


And as a note, if the text file was:

Do the dishes1
Feed the dog0
Cleaned my room1

and you used the method replaceSelected("Do the dishes", "1");, it would just not change the file.


Since this question is pretty specific, I'll add a more general solution here for future readers (based on the title).

// read file one line at a time
// replace line as you read the file and store updated lines in StringBuffer
// overwrite the file with the new lines
public static void replaceLines() {
    try {
        // input the (modified) file content to the StringBuffer "input"
        BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
        StringBuffer inputBuffer = new StringBuffer();
        String line;

        while ((line = file.readLine()) != null) {
            line = ... // replace the line here
            inputBuffer.append(line);
            inputBuffer.append('\n');
        }
        file.close();

        // write the new string with the replaced line OVER the same file
        FileOutputStream fileOut = new FileOutputStream("notes.txt");
        fileOut.write(inputBuffer.toString().getBytes());
        fileOut.close();

    } catch (Exception e) {
        System.out.println("Problem reading file.");
    }
}

How to embed a SWF file in an HTML page?

This is suitable for application from root environment.

<object type="application/x-shockwave-flash" data="/dir/application.swf" 
id="applicationID" style="margin:0 10px;width:auto;height:auto;">

<param name="movie" value="/dir/application.swf" />
<param name="wmode" value="transparent" /> <!-- Or opaque, etc. -->

<!-- ? Required paramter or not, depends on application -->
<param name="FlashVars" value="" />

<param name="quality" value="high" />
<param name="menu" value="false" />

</object>

Additional parameters should be/can be added which depends on .swf it self. No embed, just object and parameters within, so, it remains valid, working and usable everywhere, it doesn't matter which !DOCTYPE is all about. :)

Email Address Validation for ASP.NET

Validating that it is a real email address is much harder.

The regex to confirm the syntax is correct can be very long (see http://www.regular-expressions.info/email.html for example). The best way to confirm an email address is to email the user, and get the user to reply by clicking on a link to validate that they have recieved the email (the way most sign-up systems work).

Pretty git branch graphs

Depends on what they looked like. I use gitx which makes pictures like this one:

simple plot

You can compare git log --graph vs. gitk on a 24-way octopus merge (originally from http://clojure-log.n01se.net/date/2008-12-24.html):

24-way git octopus merge. Original URL was <code>http://lwn.net/images/ns/kernel/gitk-octopus.png</code>

Adding gif image in an ImageView in android

Use VideoView.

Natively ImageView does not support animated image. You have two options to show animated gif file

  1. Use VideoView
  2. Use ImageView and Split the gif file into several parts and then apply animation to it

Bash or KornShell (ksh)?

Bash is the standard for Linux.
My experience is that it is easier to find help for bash than for ksh or csh.

Save text file UTF-8 encoded with VBA

You can use CreateTextFile or OpenTextFile method, both have an attribute "unicode" usefull for encoding settings.

object.CreateTextFile(filename[, overwrite[, unicode]])        
object.OpenTextFile(filename[, iomode[, create[, format]]])

Example: Overwrite:

CreateTextFile:
 fileName = "filename"
 Set fso = CreateObject("Scripting.FileSystemObject")
 Set out = fso.CreateTextFile(fileName, True, True)
 out.WriteLine ("Hello world!")
 ...
 out.close

Example: Append:

 OpenTextFile Set fso = CreateObject("Scripting.FileSystemObject")
 Set out = fso.OpenTextFile("filename", ForAppending, True, 1)
 out.Write "Hello world!"
 ...
 out.Close

See more on MSDN docs

What is "pom" packaging in maven?

“pom” packaging is nothing but the container, which contains other packages/modules like jar, war, and ear.

if you perform any operation on outer package/container like mvn clean compile install. then inner packages/modules also get clean compile install.

no need to perform a separate operation for each package/module.

Bash: Strip trailing linebreak from output

printf already crops the trailing newline for you:

$ printf '%s' $(wc -l < log.txt)

Detail:

  • printf will print your content in place of the %s string place holder.
  • If you do not tell it to print a newline (%s\n), it won't.

How to reset selected file with input tag file type in Angular 2?

In my case I did it as below:

 <input #fileInput hidden (change)="uploadFile($event.target.files)" type="file" />
 <button mat-button color="warn" (click)="fileInput.value=''; fileInput.click()"> Upload File</button>

I am resetting it using #fileInput in HTML rather than creating a ViewChild in component.ts . Whenever the "Upload File" button is being clicked, first it resets the #fileInput and then triggers #fileInput.click() function. If any separate button needed to reset then on click #fileInput.value='' can be executed.

Best font for coding

Inconsolata (http://www.levien.com/type/myfonts/inconsolata.html) is a great monospaced font for programming. Earlier versions tend to act weird on OS X, but the newer versions work out very well.

How can I style a PHP echo text?

You can "style echo" with adding new HTML code.

echo '<span class="city">' . $ip['cityName'] . '</span>';

Deleting a local branch with Git

In my case there were uncommitted changes from the previous branch lingering around. I used following commands and then delete worked.

git checkout *

git checkout master

git branch -D

How to decrypt hash stored by bcrypt

You can't decrypt but you can BRUTEFORCE IT...

I.E: iterate a password list and check if one of them match with stored hash.

script from github: https://github.com/BREAKTEAM/Debcrypt

How to resize an image to a specific size in OpenCV?

You can use CvInvoke.Resize for Emgu.CV 3.0

e.g

CvInvoke.Resize(inputImage, outputImage, new System.Drawing.Size(100, 100), 0, 0, Inter.Cubic);

Details are here

ggplot geom_text font size control

Here are a few options for changing text / label sizes

library(ggplot2)

# Example data using mtcars

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))

p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
            geom_bar(stat="identity",position="dodge") + 
            geom_text(data = a, aes(label = mpg), 
                            position = position_dodge(width=0.9),  size=20)

The size in the geom_text changes the size of the geom_text labels.

p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels

p <- p + theme(axis.title = element_text(size = 25)) # change axis titles

p <- p + theme(text = element_text(size = 10)) # this will change all text size 
                                                             # (except geom_text)


For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?

Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text sizes to theme sizes.

So a horrible fix for uniform sizes is to scale by this ratio

geom.text.size = 7
theme.size = (14/5) * geom.text.size

ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
  geom_bar(stat="identity",position="dodge") + 
  geom_text(data = a, aes(label = mpg), 
            position = position_dodge(width=0.9),  size=geom.text.size) + 
  theme(axis.text = element_text(size = theme.size, colour="black")) 

This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)

Make div (height) occupy parent remaining height

Abstract

I didn't find a fully satisfying answer so I had to find it out myself.

My requirements:

  • the element should take exactly the remaining space either when its content size is smaller or bigger than the remaining space size (in the second case scrollbar should be shown);
  • the solution should work when the parent height is computed, and not specified;
  • calc() should not be used as the remaining element shouldn't know anything about another element sizes;
  • modern and familar layout technique such as flexboxes should be used.

The solution

  • Turn into flexboxes all direct parents with computed height (if any) and the next parent whose height is specified;
  • Specify flex-grow: 1 to all direct parents with computed height (if any) and the element so they will take up all remaining space when the element content size is smaller;
  • Specify flex-shrink: 0 to all flex items with fixed height so they won't become smaller when the element content size is bigger than the remaining space size;
  • Specify overflow: hidden to all direct parents with computed height (if any) to disable scrolling and forbid displaying overflow content;
  • Specify overflow: auto to the element to enable scrolling inside it.

JSFiddle (element has direct parents with computed height)

JSFiddle (simple case: no direct parents with computed height)

Proper usage of Optional.ifPresent()

Use flatMap. If a value is present, flatMap returns a sequential Stream containing only that value, otherwise returns an empty Stream. So there is no need to use ifPresent() . Example:

list.stream().map(data -> data.getSomeValue).map(this::getOptinalValue).flatMap(Optional::stream).collect(Collectors.toList());

How to remove an item from an array in AngularJS scope?

You'll have to find the index of the person in your persons array, then use the array's splice method:

$scope.persons.splice( $scope.persons.indexOf(person), 1 );

What is an NP-complete in computer science?

NP-Complete is a class of problems.

The class P consists of those problems that are solvable in polynomial time. For example, they could be solved in O(nk) for some constant k, where n is the size of the input. Simply put, you can write a program that will run in reasonable time.

The class NP consists of those problems that are verifiable in polynomial time. That is, if we are given a potential solution, then we could check if the given solution is correct in polynomial time.

Some examples are the Boolean Satisfiability (or SAT) problem, or the Hamiltonian-cycle problem. There are many problems that are known to be in the class NP.

NP-Complete means the problem is at least as hard as any problem in NP.

It is important to computer science because it has been proven that any problem in NP can be transformed into another problem in NP-complete. That means that a solution to any one NP-complete problem is a solution to all NP problems.

Many algorithms in security depends on the fact that no known solutions exist for NP hard problems. It would definitely have a significant impact on computing if a solution were found.

How to get controls in WPF to fill available space?

There are also some properties you can set to force a control to fill its available space when it would otherwise not do so. For example, you can say:

HorizontalContentAlignment="Stretch"

... to force the contents of a control to stretch horizontally. Or you can say:

HorizontalAlignment="Stretch"

... to force the control itself to stretch horizontally to fill its parent.

What is the difference between function and procedure in PL/SQL?

A function can be in-lined into a SQL statement, e.g.

select foo
      ,fn_bar (foo)
  from foobar

Which cannot be done with a stored procedure. The architecture of the query optimiser limits what can be done with functions in this context, requiring that they are pure (i.e. the same inputs always produce the same output). This restricts what can be done in the function, but allows it to be used in-line in the query if it is defined to be "pure".

Otherwise, a function (not necessarily deterministic) can return a variable or a result set. In the case of a function returning a result set, you can join it against some other selection in a query. However, you cannot use a non-deterministic function like this in a correlated subquery as the optimiser cannot predict what sort of result set will be returned (this is computationally intractable, like the halting problem).

How to check if that data already exist in the database during update (Mongoose And Express)

Typically you could use mongoose validation but since you need an async result (db query for existing names) and validators don't support promises (from what I can tell), you will need to create your own function and pass a callback. Here is an example:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

mongoose.connect('mongodb://localhost/testDB');

var UserSchema = new Schema({
    name: {type:String}
});

var UserModel = mongoose.model('UserModel',UserSchema);

function updateUser(user,cb){
    UserModel.find({name : user.name}, function (err, docs) {
        if (docs.length){
            cb('Name exists already',null);
        }else{
            user.save(function(err){
                cb(err,user);
            });
        }
    });
}

UserModel.findById(req.param('sid'),function(err,existingUser){
   if (!err && existingUser){
       existingUser.name = 'Kevin';
       updateUser(existingUser,function(err2,user){
           if (err2 || !user){
               console.log('error updated user: ',err2);
           }else{
               console.log('user updated: ',user);
           }

       });
   } 
});

UPDATE: A better way

The pre hook seems to be a more natural place to stop the save:

UserSchema.pre('save', function (next) {
    var self = this;
    UserModel.find({name : self.name}, function (err, docs) {
        if (!docs.length){
            next();
        }else{                
            console.log('user exists: ',self.name);
            next(new Error("User exists!"));
        }
    });
}) ;

UPDATE 2: Async custom validators

It looks like mongoose supports async custom validators now so that would probably be the natural solution:

    var userSchema = new Schema({
      name: {
        type: String,
        validate: {
          validator: function(v, cb) {
            User.find({name: v}, function(err,docs){
               cb(docs.length == 0);
            });
          },
          message: 'User already exists!'
        }
      }
    });

Horizontal ListView in Android?

Since Google introduced Android Support Library v7 21.0.0, you can use RecyclerView to scroll items horizontally. The RecyclerView widget is a more advanced and flexible version of ListView.

To use RecyclerView, just add dependency:

com.android.support:recyclerview-v7:23.0.1

Here is a sample:

public class MyActivity extends Activity {

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

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);

        MyAdapter adapter = new MyAdapter(myDataset);
        recyclerView.setAdapter(adapter);
    }
}

More info about RecyclerView:

Accessing a property in a parent Component

You could:

  • Define a userStatus parameter for the child component and provide the value when using this component from the parent:

    @Component({
      (...)
    })
    export class Profile implements OnInit {
      @Input()
      userStatus:UserStatus;
    
      (...)
    }
    

    and in the parent:

    <profile [userStatus]="userStatus"></profile>
    
  • Inject the parent into the child component:

    @Component({
      (...)
    })
    export class Profile implements OnInit {
      constructor(app:App) {
        this.userStatus = app.userStatus;
      }
    
      (...)
    }
    

    Be careful about cyclic dependencies between them.

How to iterate over arguments in a Bash script

aparse() {
while [[ $# > 0 ]] ; do
  case "$1" in
    --arg1)
      varg1=${2}
      shift
      ;;
    --arg2)
      varg2=true
      ;;
  esac
  shift
done
}

aparse "$@"

Systrace for Windows

A few options:

Process Monitor

Also, see this article about tools built into Windows 7:

Core OS Tools

How do I repair an InnoDB table?

Note: If your issue is, "innodb index is marked as corrupted"! Then, the simple solution can be, just remove the indexes and add them again. That can solve pretty quickly without losing any records nor restarting or moving table contents into a temporary table and back.

Bi-directional Map in Java?

Creating a Guava BiMap and getting its inverted value is not so trivial.

A simple example:

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

public class BiMapTest {

  public static void main(String[] args) {

    BiMap<String, String> biMap = HashBiMap.create();

    biMap.put("k1", "v1");
    biMap.put("k2", "v2");

    System.out.println("k1 = " + biMap.get("k1"));
    System.out.println("v2 = " + biMap.inverse().get("v2"));
  }
}

@Value annotation type casting to Integer from String

In my case, the problem was that my POST request was sent to the same url as GET (with get parameters using "?..=..") and that parameters had the same name as form parameters. Probably Spring is merging them into an array and parsing was throwing error.

Check if a Postgres JSON array contains a string

A small variation but nothing new infact. It's really missing a feature...

select info->>'name' from rabbits 
where '"carrots"' = ANY (ARRAY(
    select * from json_array_elements(info->'food'))::text[]);

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

I had this problem. I searched the internet, took all advices, changes configurations, but the problem is still there. Finally with the help of the server administrator, he found that the problem lies in MySQL database column definition. one of the columns in the a table was assigned to 'Longtext' which leads to allocate 4,294,967,295 bites of memory. It seems working OK if you don't use MySqli prepare statement, but once you use prepare statement, it tries to allocate that amount of memory. I changed the column type to Mediumtext which needs 16,777,215 bites of memory space. The problem is gone. Hope this help.

What are the differences between using the terminal on a mac vs linux?

@Michael Durrant's answer ably covers the shell itself, but the shell environment also includes the various commands you use in the shell and these are going to be similar -- but not identical -- between OS X and linux. In general, both will have the same core commands and features (especially those defined in the Posix standard), but a lot of extensions will be different.

For example, linux systems generally have a useradd command to create new users, but OS X doesn't. On OS X, you generally use the GUI to create users; if you need to create them from the command line, you use dscl (which linux doesn't have) to edit the user database (see here). (Update: starting in macOS High Sierra v10.13, you can use sysadminctl -addUser instead.)

Also, some commands they have in common will have different features and options. For example, linuxes generally include GNU sed, which uses the -r option to invoke extended regular expressions; on OS X, you'd use the -E option to get the same effect. Similarly, in linux you might use ls --color=auto to get colorized output; on macOS, the closest equivalent is ls -G.

EDIT: Another difference is that many linux commands allow options to be specified after their arguments (e.g. ls file1 file2 -l), while most OS X commands require options to come strictly first (ls -l file1 file2).

Finally, since the OS itself is different, some commands wind up behaving differently between the OSes. For example, on linux you'd probably use ifconfig to change your network configuration. On OS X, ifconfig will work (probably with slightly different syntax), but your changes are likely to be overwritten randomly by the system configuration daemon; instead you should edit the network preferences with networksetup, and then let the config daemon apply them to the live network state.

How do I to insert data into an SQL table using C# as well as implement an upload function?

using System;
using System.Data;
using System.Data.SqlClient;

namespace InsertingData
{
    class sqlinsertdata
    {
        static void Main(string[] args)
        {
            try
            { 
            SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
            conn.Open();
                SqlCommand cmd = new SqlCommand("insert into <Table Name>values(1,'nagendra',10000);",conn);
                cmd.ExecuteNonQuery();
                Console.WriteLine("Inserting Data Successfully");
                conn.Close();
        }
            catch(Exception e)
            {
                Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t"  + e.GetType());
            }
            Console.ReadKey();

    }
    }
}

What is the fastest factorial function in JavaScript?

Since a factorial is simply degenerative multiplication from the number given down to 1, it would indeed be easier to just loop through the multiplication:

Math.factorial = function(n) {

  if (n === 0||n === 1) {

    return 1;

  } else {

    for(var i = n; i > 0; --i) { //always make sure to decrement the value BEFORE it's tacked onto the original as a product
      n *= i;
    }

    return n;

  }

}

Safari 3rd party cookie iframe trick no longer working?

Google actually let the cat out of the bag on this one. They were using it for a while to access tracking cookies. It was fixed almost immediately by Apple =\

original Wall Street Journal post

Vertical alignment of text and icon in button

Just wrap the button label in an extra span and add class="align-middle" to both (the icon and the label). This will center your icon with text vertical.

<button id="edit-listing-form-house_Continue" 
    class="btn btn-large btn-primary"
    style=""
    value=""
    name="Continue"
    type="submit">
<span class="align-middle">Continue</span>
<i class="icon-ok align-middle" style="font-size:40px;"></i>

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

Check in Deployment Assembly,

I have the same error, when i generate the war file with the "maven clean install" way and deploy manualy, it works fine, but when i use the runtime enviroment (eclipse) the problems come.

The solution for me (for eclipse IDE) go to: "proyect properties" --> "Deployment Assembly" --> "Add" --> "the jar you need", in my case java "build path entries". Maybe can help a litle!

Why would I use dirname(__FILE__) in an include or include_once statement?

I used this below if this is what you are thinking. It it worked well for me.

<?php
    include $_SERVER['DOCUMENT_ROOT']."/head_lib.php";
?>

What I was trying to do was pulla file called /head_lib.php from the root folder. It would not pull anything to build the webpage. The header, footer and other key features in sub directories would never show up. Until I did above it worked like a champ.

Replace contents of factor column in R dataframe

A more general solution that works with all the data frame at once and where you don't have to add new factors levels is:

data.mtx <- as.matrix(data.df)
data.mtx[which(data.mtx == "old.value.to.replace")] <- "new.value"
data.df <- as.data.frame(data.mtx)

A nice feature of this code is that you can assign as many values as you have in your original data frame at once, not only one "new.value", and the new values can be random values. Thus you can create a complete new random data frame with the same size as the original.

How to check if the key pressed was an arrow key in Java KeyListener?

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_RIGHT ) {
            //Right arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_LEFT ) {
            //Left arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_UP ) {
            //Up arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_DOWN ) {
            //Down arrow key code
    }

    repaint();
}

The KeyEvent codes are all a part of the API: http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html

Javascript to convert UTC to local time

To format your date try the following function:

var d = new Date();
var fromatted = d.toLocaleFormat("%d.%m.%Y %H:%M (%a)");

But the downside of this is, that it's a non-standard function, which is not working in Chrome, but working in FF (afaik).

Chris

Telnet is not recognized as internal or external command

  1. Open "Start" (Windows Button)
  2. Search for "Turn Windows features On or Off"
  3. Check "Telnet client" and check "Telnet server".

Left-pad printf with spaces

If you want exactly 40 spaces before the string then you should just do:

printf("                                        %s\n", myStr );

If that is too dirty, you can do (but it will be slower than manually typing the 40 spaces): printf("%40s%s", "", myStr );

If you want the string to be lined up at column 40 (that is, have up to 39 spaces proceeding it such that the right most character is in column 40) then do this: printf("%40s", myStr);

You can also put "up to" 40 spaces AfTER the string by doing: printf("%-40s", myStr);

SELECT INTO Variable in MySQL DECLARE causes syntax error?

You don't need to DECLARE a variable in MySQL. A variable's type is determined automatically when it is first assigned a value. Its type can be one of: integer, decimal, floating-point, binary or nonbinary string, or NULL value. See the User-Defined Variables documentation for more information:

http://dev.mysql.com/doc/refman/5.0/en/user-variables.html

You can use SELECT ... INTO to assign columns to a variable:

http://dev.mysql.com/doc/refman/5.0/en/select-into-statement.html

Example:

mysql> SELECT 1 INTO @var;
Query OK, 1 row affected (0.00 sec)

mysql> SELECT @var;
+------+
| @var |
+------+
| 1    |
+------+
1 row in set (0.00 sec)

How to increase space between dotted border dots

You could create a canvas (via javascript) and draw a dotted line within. Within the canvas you can control how long the dash and the space in between shall be.

Model Binding to a List MVC 4

~Controller

namespace ListBindingTest.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            List<String> tmp = new List<String>();
            tmp.Add("one");
            tmp.Add("two");
            tmp.Add("Three");
            return View(tmp);
        }

        [HttpPost]
        public ActionResult Send(IList<String> input)
        {
            return View(input);
        }    
    }
}

~ Strongly Typed Index View

@model IList<String>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
    <div>
    @using(Html.BeginForm("Send", "Home", "POST"))
    {
        @Html.EditorFor(x => x)
        <br />
        <input type="submit" value="Send" />
    }
    </div>
</body>
</html>

~ Strongly Typed Send View

@model IList<String>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Send</title>
</head>
<body>
    <div>
    @foreach(var element in @Model)
    {
        @element
        <br />
    }
    </div>
</body>
</html>

This is all that you had to do man, change his MyViewModel model to IList.

Bootstrap modal - close modal when "call to action" button is clicked

Use data-dismiss="modal". In the version of Bootstrap I am using v3.3.5, when data-dismiss="modal" is added to the desired button like shown below it calls my external Javascript (JQuery) function beautifully and magically closes the modal. Its soo Sweet, I was worried I would have to call some modal hide in another function and chain that to the real working function

 <a href="#" id="btnReleaseAll" class="btn btn-primary btn-default btn-small margin-right pull-right" data-dismiss="modal">Yes</a>

In some external script file, and in my doc ready there is of course a function for the click of that identifier ID

 $("#divExamListHeader").on('click', '#btnReleaseAll', function () {
               // Do DatabaseMagic Here for a call a MVC ActionResult

Apache shows PHP code instead of executing it

Wow, lots of solutions here! Here's what I did on Ubuntu 16.04:

sudo apt-get install php libapache2-mod-php
sudo a2enmod mpm_prefork && sudo a2enmod php7.0
sudo service apache2 restart

Best practices for Storyboard login screen, handling clearing of data upon logout

In Xcode 7 you can have multiple storyBoards. It will be better if you can keep the Login flow in a separate storyboard.

This can be done using SELECT VIEWCONTROLLER > Editor > Refactor to Storyboard

And here is the Swift version for setting a view as the RootViewContoller-

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    appDelegate.window!.rootViewController = newRootViewController

    let rootViewController: UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("LoginViewController")

jQuery ui datepicker with Angularjs

I had the same problem and it was solved by putting the references and includes in that order:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>

_x000D_
_x000D_
var datePicker = angular.module('app', []);_x000D_
_x000D_
datePicker.directive('jqdatepicker', function () {_x000D_
    return {_x000D_
        restrict: 'A',_x000D_
        require: 'ngModel',_x000D_
         link: function (scope, element, attrs, ngModelCtrl) {_x000D_
            element.datepicker({_x000D_
                dateFormat: 'dd/mm/yy',_x000D_
                onSelect: function (date) {_x000D_
                    scope.date = date;_x000D_
                    scope.$apply();_x000D_
                }_x000D_
            });_x000D_
        }_x000D_
    };_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>_x000D_
<link href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>_x000D_
_x000D_
<body ng-app="app">_x000D_
<input type="text" ng-model="date" jqdatepicker />_x000D_
<br/>_x000D_
{{ date }}_x000D_
</body>
_x000D_
_x000D_
_x000D_

Setting Environment Variables for Node to retrieve

For windows users this Stack Overflow question and top answer is quite useful on how to set environement variables via the command line

How can i set NODE_ENV=production in Windows?

Handling ExecuteScalar() when no results are returned

Always have a check before reading row.

if (SqlCommand.ExecuteScalar() == null)
{ 

}

If a folder does not exist, create it

You can use a try/catch clause and check to see if it exist:

  try
  {
    if (!Directory.Exists(path))
    {
       // Try to create the directory.
       DirectoryInfo di = Directory.CreateDirectory(path);
    }
  }
  catch (IOException ioex)
  {
     Console.WriteLine(ioex.Message);
  }

How to manage exceptions thrown in filters in Spring?

You can use the following method inside the catch block:

response.sendError(HttpStatus.UNAUTHORIZED.value(), "Invalid token")

Notice that you can use any HttpStatus code and a custom message.

How to get the last char of a string in PHP?

You can find last character using php many ways like substr() and mb_substr().

If you’re using multibyte character encodings like UTF-8, use mb_substr instead of substr

Here i can show you both example:

<?php
    echo substr("testers", -1);
    echo mb_substr("testers", -1);
?>

LIVE DEMO

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

How do I find out which process is locking a file using .NET?

One of the good things about handle.exe is that you can run it as a subprocess and parse the output.

We do this in our deployment script - works like a charm.

What does it mean to "call" a function in Python?

To "call" means to make a reference in your code to a function that is written elsewhere. This function "call" can be made to the standard Python library (stuff that comes installed with Python), third-party libraries (stuff other people wrote that you want to use), or your own code (stuff you wrote). For example:

#!/usr/env python

import os

def foo():
    return "hello world"

print os.getlogin()
print foo()

I created a function called "foo" and called it later on with that print statement. I imported the standard "os" Python library then I called the "getlogin" function within that library.

How to create file execute mode permissions in Git on Windows?

I have no touch and chmod command in my cmd.exe and git update-index --chmod=+x foo.sh doesn't work for me.

I finally resolve it by setting skip-worktree bit:

git update-index --skip-worktree --chmod=+x foo.sh

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

I was getting the same error when i upgrade MVC4 to MVC5 version, Firstly i Upgraded the calling assembly which was depends on

> System.Web.WebPages.Razor, Version=2.0.0.0

after that updated the web.config files under the Views folder, updated following packages from

<configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
</configSections>

to

<configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
 </configSections>

and also updated

<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

to

<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

these steps works for me

How to change the background color on a input checkbox with css?

I always use pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons. it's works like a charm.

Refer this link for more info

CODEPEN

Steps

  1. Hide the default checkbox using css rules like visibility:hidden or opacity:0 or position:absolute;left:-9999px etc.
  2. Create a fake checkbox using :before element and pass either an empty or a non-breaking space '\00a0';
  3. When the checkbox is in :checked state, pass the unicode content: "\2713", which is a checkmark;
  4. Add :focus style to make the checkbox accessible.
  5. Done

Here is how I did it.

_x000D_
_x000D_
.box {_x000D_
  background: #666666;_x000D_
  color: #ffffff;_x000D_
  width: 250px;_x000D_
  padding: 10px;_x000D_
  margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
  margin: 1.5em 0;_x000D_
  padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
  visibility: hidden;_x000D_
}_x000D_
label {_x000D_
  cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
  border: 1px solid #333;_x000D_
  content: "\00a0";_x000D_
  display: inline-block;_x000D_
  font: 16px/1em sans-serif;_x000D_
  height: 16px;_x000D_
  margin: 0 .25em 0 0;_x000D_
  padding: 0;_x000D_
  vertical-align: top;_x000D_
  width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
  background: #fff;_x000D_
  color: #333;_x000D_
  content: "\2713";_x000D_
  text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
    outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="box">_x000D_
    <p>_x000D_
      <input type="checkbox" id="c1" name="cb">_x000D_
      <label for="c1">Option 01</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c2" name="cb">_x000D_
      <label for="c2">Option 02</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c3" name="cb">_x000D_
      <label for="c3">Option 03</label>_x000D_
    </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Much more stylish using :before and :after

_x000D_
_x000D_
body{_x000D_
  font-family: sans-serif;  _x000D_
}_x000D_
_x000D_
.container {_x000D_
    margin-top: 50px;_x000D_
    margin-left: 20px;_x000D_
    margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
    width: 100%;_x000D_
    margin: 15px auto;_x000D_
    position: relative;_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
    width: auto;_x000D_
    opacity: 0.00000001;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
    position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    margin: 4px;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
    transition: transform 0.28s ease;_x000D_
    border-radius: 3px;_x000D_
    border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
  content: '';_x000D_
    display: block;_x000D_
    width: 10px;_x000D_
    height: 5px;_x000D_
    border-bottom: 2px solid #7bbe72;_x000D_
    border-left: 2px solid #7bbe72;_x000D_
    -webkit-transform: rotate(-45deg) scale(0);_x000D_
    transform: rotate(-45deg) scale(0);_x000D_
    transition: transform ease 0.25s;_x000D_
    will-change: transform;_x000D_
    position: absolute;_x000D_
    top: 12px;_x000D_
    left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
    color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
    -webkit-transform: rotate(-45deg) scale(1);_x000D_
    transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
    min-height: 34px;_x000D_
    display: block;_x000D_
    padding-left: 40px;_x000D_
    margin-bottom: 0;_x000D_
    font-weight: normal;_x000D_
    cursor: pointer;_x000D_
    vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    -webkit-transform: translateY(-50%);_x000D_
    transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
    outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox" name="" value="">_x000D_
     <label for="checkbox"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
_x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox2" name="" value="">_x000D_
     <label for="checkbox2"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Check if Cell value exists in Column, and then get the value of the NEXT Cell

How about this?

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", INDIRECT(ADDRESS(MATCH(A1,B:B, 0), 3)))

The "3" at the end means for column C.

Python in Xcode 4+?

Try Editra It's free, has a lot of cool features and plug-ins, it runs on most platforms, and it is written in Python. I use it for all my non-XCode development at home and on Windows/Linux at work.

Better way to find index of item in ArrayList?

There is indeed a fancy shmancy native function in java you should leverage.

ArrayList has an instance method called

indexOf(Object o)

(http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html)

You would be able to call it on _categories as follows:

_categories.indexOf("camels")

I have no experience with programming for Android - but this would work for a standard Java application.

Good luck.

Formatting Phone Numbers in PHP

Phone numbers are hard. For a more robust, international solution, I would recommend this well-maintained PHP port of Google's libphonenumber library.

Using it like this,

use libphonenumber\NumberParseException;
use libphonenumber\PhoneNumber;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\PhoneNumberUtil;

$phoneUtil = PhoneNumberUtil::getInstance();

$numberString = "+12123456789";

try {
    $numberPrototype = $phoneUtil->parse($numberString, "US");

    echo "Input: " .          $numberString . "\n";
    echo "isValid: " .       ($phoneUtil->isValidNumber($numberPrototype) ? "true" : "false") . "\n";
    echo "E164: " .           $phoneUtil->format($numberPrototype, PhoneNumberFormat::E164) . "\n";
    echo "National: " .       $phoneUtil->format($numberPrototype, PhoneNumberFormat::NATIONAL) . "\n";
    echo "International: " .  $phoneUtil->format($numberPrototype, PhoneNumberFormat::INTERNATIONAL) . "\n";
} catch (NumberParseException $e) {
    // handle any errors
}

you will get the following output:

Input: +12123456789
isValid: true
E164: +12123456789
National: (212) 345-6789
International: +1 212-345-6789

I'd recommend using the E164 format for duplicate checks. You could also check whether the number is a actually mobile number or not (using PhoneNumberUtil::getNumberType()), or whether it's even a US number (using PhoneNumberUtil::getRegionCodeForNumber()).

As a bonus, the library can handle pretty much any input. If you, for instance, choose to run 1-800-JETBLUE through the code above, you will get

Input: 1-800-JETBLUE
isValid: true
E164: +18005382583
National: (800) 538-2583
International: +1 800-538-2583

Neato.

It works just as nicely for countries other than the US. Just use another ISO country code in the parse() argument.

grep without showing path/file:line

Just replace -H with -h. Check man grep for more details on options

find . -name '*.bar' -exec grep -hn FOO {} \;

What arguments are passed into AsyncTask<arg1, arg2, arg3>?

Keep it simple!

An AsyncTask is background task which runs in the background thread. It takes an Input, performs Progress and gives Output.

ie AsyncTask<Input,Progress,Output>.

In my opinion the main source of confusion comes when we try to memorize the parameters in the AsyncTask.
The key is Don't memorize.
If you can visualize what your task really needs to do then writing the AsyncTask with the correct signature would be a piece of cake.
Just figure out what your Input, Progress and Output are and you will be good to go.

For example: enter image description here

Heart of the AsyncTask!

doInBackgound() method is the most important method in an AsyncTask because

  • Only this method runs in the background thread and publish data to UI thread.
  • Its signature changes with the AsyncTask parameters.

So lets see the relationship

enter image description here

doInBackground() and onPostExecute(),onProgressUpdate() are also related

enter image description here

Show me the code
So how will I write the code for DownloadTask?

DownloadTask extends AsyncTask<String,Integer,String>{

      @Override
      public void onPreExecute()
      {}

      @Override
      public String doInbackGround(String... params)
      {
               // Download code
               int downloadPerc = // calculate that
               publish(downloadPerc);

               return "Download Success";
      }

      @Override
      public void onPostExecute(String result)
      {
          super.onPostExecute(result);
      }

      @Override
      public void onProgressUpdate(Integer... params)
      {
             // show in spinner, access UI elements
      }

}

How will you run this Task

new DownLoadTask().execute("Paradise.mp3");

Linq order by, group by and order by each group?

I think you want an additional projection that maps each group to a sorted-version of the group:

.Select(group => group.OrderByDescending(student => student.Grade))

It also appears like you might want another flattening operation after that which will give you a sequence of students instead of a sequence of groups:

.SelectMany(group => group)

You can always collapse both into a single SelectMany call that does the projection and flattening together.


EDIT: As Jon Skeet points out, there are certain inefficiencies in the overall query; the information gained from sorting each group is not being used in the ordering of the groups themselves. By moving the sorting of each group to come before the ordering of the groups themselves, the Max query can be dodged into a simpler First query.

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

its not a big issue just change your server name see where to server name change:

enter image description here

how to find server name

  1. open run
  2. write 'cmd'
  3. write in console window "Hostname".

your server name will show you

thank you.

How to build a JSON array from mysql database

Is something like this what you want to do?

$return_arr = array();

$fetch = mysql_query("SELECT * FROM table"); 

while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
    $row_array['id'] = $row['id'];
    $row_array['col1'] = $row['col1'];
    $row_array['col2'] = $row['col2'];

    array_push($return_arr,$row_array);
}

echo json_encode($return_arr);

It returns a json string in this format:

[{"id":"1","col1":"col1_value","col2":"col2_value"},{"id":"2","col1":"col1_value","col2":"col2_value"}]

OR something like this:

$year = date('Y');
$month = date('m');

$json_array = array(

//Each array below must be pulled from database
    //1st record
    array(
    'id' => 111,
    'title' => "Event1",
    'start' => "$year-$month-10",
    'url' => "http://yahoo.com/"
),

     //2nd record
     array(
    'id' => 222,
    'title' => "Event2",
    'start' => "$year-$month-20",
    'end' => "$year-$month-22",
    'url' => "http://yahoo.com/"
)

);

echo json_encode($json_array);

Manually type in a value in a "Select" / Drop-down HTML list?

I faced the same basic problem: trying to combine the functionality of a textbox and a select box which are fundamentally different things in the html spec.

The good news is that selectize.js does exactly this:

Selectize is the hybrid of a textbox and box. It's jQuery-based and it's useful for tagging, contact lists, country selectors, and so on.

How do I change a single value in a data.frame?

data.frame[row_number, column_number] = new_value

For example, if x is your data.frame:

x[1, 4] = 5

Is there any simple way to convert .xls file to .csv file? (Excel)

I need to do the same thing. I ended up with something similar to Kman

       static void ExcelToCSVCoversion(string sourceFile,  string targetFile)
    {
        Application rawData = new Application();

        try
        {
            Workbook workbook = rawData.Workbooks.Open(sourceFile);
            Worksheet ws = (Worksheet) workbook.Sheets[1];
            ws.SaveAs(targetFile, XlFileFormat.xlCSV);
            Marshal.ReleaseComObject(ws);
        }

        finally
        {
            rawData.DisplayAlerts = false;
            rawData.Quit();
            Marshal.ReleaseComObject(rawData);
        }


        Console.WriteLine();
        Console.WriteLine($"The excel file {sourceFile} has been converted into {targetFile} (CSV format).");
        Console.WriteLine();
    }

If there are multiple sheets this is lost in the conversion but you could loop over the number of sheets and save each one as csv.

Does Python SciPy need BLAS?

I guess you are talking about installation in Ubuntu. Just use:

apt-get install python-numpy python-scipy

That should take care of the BLAS libraries compiling as well. Else, compiling the BLAS libraries is very difficult.

How to get first N number of elements from an array

You can filter using index of array.

_x000D_
_x000D_
var months = ['Jan', 'March', 'April', 'June'];_x000D_
months = months.filter((month,idx) => idx < 2)_x000D_
console.log(months);
_x000D_
_x000D_
_x000D_

How to mention C:\Program Files in batchfile

use this as somethink

"C:/Program Files (x86)/Nox/bin/nox_adb" install -r app.apk

where

"path_to_executable" commands_argument

Python write line by line to a text file

Well, the problem you have is wrong line ending/encoding for notepad. Notepad uses Windows' line endings - \r\n and you use \n.

How do I get the current time only in JavaScript

Short and simple:

new Date().toLocaleTimeString(); // 11:18:48 AM
//---
new Date().toLocaleDateString(); // 11/16/2015
//---
new Date().toLocaleString(); // 11/16/2015, 11:18:48 PM

4 hours later (use milisec: sec==1000):

new Date(new Date().getTime() + 4*60*60*1000).toLocaleTimeString(); // 3:18:48 PM or 15:18:48

2 days before:

new Date(new Date().getTime() - 2*24*60*60*1000).toLocaleDateString() // 11/14/2015

How can I remove a character from a string using JavaScript?

The following function worked best for my case:

public static cut(value: string, cutStart: number, cutEnd: number): string {
    return value.substring(0, cutStart) + value.substring(cutEnd + 1, value.length);
}

How to get parameter on Angular2 route in Angular way?

As of Angular 6+, this is handled slightly differently than in previous versions. As @BeetleJuice mentions in the answer above, paramMap is new interface for getting route params, but the execution is a bit different in more recent versions of Angular. Assuming this is in a component:

private _entityId: number;

constructor(private _route: ActivatedRoute) {
    // ...
}

ngOnInit() {
    // For a static snapshot of the route...
    this._entityId = this._route.snapshot.paramMap.get('id');

    // For subscribing to the observable paramMap...
    this._route.paramMap.pipe(
        switchMap((params: ParamMap) => this._entityId = params.get('id'))
    );

    // Or as an alternative, with slightly different execution...
    this._route.paramMap.subscribe((params: ParamMap) =>  {
        this._entityId = params.get('id');
    });
}

I prefer to use both because then on direct page load I can get the ID param, and also if navigating between related entities the subscription will update properly.

Source in Angular Docs

Which icon sizes should my Windows application's icon include?

(Updated answer for Windows 8/10)

View full list of guidelines and sizes here, in new Windows design guidelines: https://msdn.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-app-assets#asset-types

Still include .ICO file with these sizes to support legacy experiences:

  • 16x16
  • 24x24
  • 32x32
  • 48x48
  • 256x256

Generate .pem file used to set up Apple Push Notifications

To enable Push Notification for your iOS app, you will need to create and upload the Apple Push Notification Certificate (.pem file) to us so we will be able to connect to Apple Push Server on your behalf.

(Updated version with updated screen shots Here)

Step 1: Login to iOS Provisioning Portal, click "Certificates" on the left navigation bar. Then, click "+" button.

enter image description here

Step 2: Select Apple Push Notification service SSL (Production) option under Distribution section, then click "Continue" button.

enter image description here

Step 3: Select the App ID you want to use for your BYO app (How to Create An App ID), then click "Continue" to go to next step.

enter image description here

Step 4: Follow the steps "About Creating a Certificate Signing Request (CSR)" to create a Certificate Signing Request.

enter image description here

To supplement the instruction provided by Apple. Here are some of the additional screenshots to assist you to complete the required steps:

Step 4 Supplementary Screenshot 1: Navigate to Certificate Assistant of Keychain Access on your Mac.

enter image description here

Step 4 Supplementary Screenshot 2: Fill in the Certificate Information. Click Continue.

enter image description here

Step 5: Upload the ".certSigningRequest" file which is generated in Step 4, then click "Generate" button.

enter image description here

Step 6: Click "Done" to finish the registration, the iOS Provisioning Portal Page will be refreshed that looks like the following screen:

enter image description here

Then Click "Download" button to download the certificate (.cer file) you've created just now. - Double click the downloaded file to install the certificate into Keychain Access on your Mac.

Step 7: On your Mac, go to "Keychain", look for the certificate you have just installed. If unsure which certificate is the correct one, it should start with "Apple Production IOS Push Services:" followed by your app's bundle ID.

enter image description here

Step 8: Expand the certificate, you should see the private key with either your name or your company name. Select both items by using the "Select" key on your keyboard, right click (or cmd-click if you use a single button mouse), choose "Export 2 items", like Below:

enter image description here

Then save the p12 file with name "pushcert.p12" to your Desktop - now you will be prompted to enter a password to protect it, you can either click Enter to skip the password or enter a password you desire.

Step 9: Now the most difficult part - open "Terminal" on your Mac, and run the following commands:

cd
cd Desktop
openssl pkcs12 -in pushcert.p12 -out pushcert.pem -nodes -clcerts

Step 10: Remove pushcert.p12 from Desktop to avoid mis-uploading it to Build Your Own area. Open "Terminal" on your Mac, and run the following commands:

cd
cd Desktop
rm pushcert.p12

Step 11 - NEW AWS UPDATE: Create new pushcert.p12 to submit to AWS SNS. Double click on the new pushcert.pem, then export the one highlighed on the green only.

enter image description here Credit: AWS new update

Now you have successfully created an Apple Push Notification Certificate (.p12 file)! You will need to upload this file to our Build Your Own area later on. :)

Which browsers support <script async="async" />?

There's two parts to this question, really.

  1. Q: Which browsers support the "async" attribute on a script tag in markup?

    A: IE10p2+, Chrome 11+, Safari 5+, Firefox 3.6+

  2. Q: Which browsers support the new spec that defines behavior for the "async" property in JavaScript, on a dynamically created script element?

    A: IE10p2+, Chrome 12+, Safari 5.1+, Firefox 4+

As for Opera, they are very close to releasing a version which will support both types of async. I've been working with them closely on this, and it should come out soon (I hope!).

More info on ordered-async (aka, "async=false") can be found here: http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order

Also, to test if a browser supports the new dynamic async property behavior: http://test.getify.com/test-async/

In Java, how can I determine if a char array contains a particular character?

From NumberKeyListener source code. This method they use to check if char is contained in defined array of accepted characters:

protected static boolean ok(char[] accept, char c) {
    for (int i = accept.length - 1; i >= 0; i--) {
        if (accept[i] == c) {
            return true;
        }
    }

    return false;
}

It is similar to @ÓscarLópez solution. Might be a bit faster cause of absence of foreach iterator.

Setting Windows PATH for Postgres tools

Settings Windows Path For Postgresql

open my Computer ==>
  right click inside my computer and select properties ==>
    Click on Advanced System Settings ==>
       Environment Variables ==>
          from the System Variables box select "PATH" ==>
             Edit... ==>

then add this at the end of whatever you find their

 ;C:\PostgreSQL\9.2\bin; C:\PostgreSQL\9.2\lib

after that continue to click OK

open cmd/command prompt.... open psql in command prompt with this

psql -U username database

eg. i have a database name FRIENDS and a user MEE.. it will be

psql -U MEE FRIENDS

you will be then prompted to give the password of the user in question. Thanks

Set HTML element's style property in javascript

If you just want to change the color of the row, you could just access the style.backgroundColor property and set it.

Here is a quick link to a CSS property to JS conversion.

Can I return the 'id' field after a LINQ insert?

Try this:

MyContext Context = new MyContext(); 
Context.YourEntity.Add(obj);
Context.SaveChanges();
int ID = obj._ID;

Can't create project on Netbeans 8.2

EDIT: The solution is to install JDK 8, as JDK 9 and beyond are currently not supported.

If however, you already have installed JDK 8, then kindly follow the steps outlined below.

The reason is that there is a conflict with the base JDK that NetBeans starts with. You have to set it to a lower version.

  1. Go to the folder "C:\Program Files\NetBeans 8.2\etc", or wherever NetBeans is installed.
  2. Open the netbeans.conf file.
  3. Locate netbeans_jdkhome and replace the JDK path there with "C:\Program Files\Java\jdk1.8.0_152", or wherever your JDK is installed. Be sure to use the right path, or you will run into problems. Here, JDK 1.8.0_152 is installed.
  4. Save the file, and restart NetBeans. It worked for me, should do for you too.

How to remove duplicates from a list?

I suspect you might not have Customer.equals() implemented properly (or at all).

List.contains() uses equals() to verify whether any of its elements is identical to the object passed as parameter. However, the default implementation of equals tests for physical identity, not value identity. So if you have not overwritten it in Customer, it will return false for two distinct Customer objects having identical state.

Here are the nitty-gritty details of how to implement equals (and hashCode, which is its pair - you must practically always implement both if you need to implement either of them). Since you haven't shown us the Customer class, it is difficult to give more concrete advice.

As others have noted, you are better off using a Set rather than doing the job by hand, but even for that, you still need to implement those methods.

OSX -bash: composer: command not found

Well I tried a lot of things but none seemed to be working. But the following process did it right, I can now use composer command in terminal. I'm in mac OS 10.12.1

$ curl -sS https://getcomposer.org/installer | php
$ chmod +x composer.phar
$ mv composer.phar /usr/local/bin/composer
$ composer

How to check file input size with jQuery?

You can do this type of checking with Flash or Silverlight but not Javascript. The javascript sandbox does not allow access to the file system. The size check would need to be done server side after it has been uploaded.

If you want to go the Silverlight/Flash route, you could check that if they are not installed to default to a regular file upload handler that uses the normal controls. This way, if the do have Silverlight/Flash installed their experience will be a bit more rich.

RegEx - Match Numbers of Variable Length

Try this:

{[0-9]{1,3}:[0-9]{1,3}}

The {1,3} means "match between 1 and 3 of the preceding characters".

What’s the best way to reload / refresh an iframe?

If you using Jquery then there is one line code.

$('#iframeID',window.parent.document).attr('src',$('#iframeID',window.parent.document).attr('src'));

and if you are working with same parent then

$('#iframeID',parent.document).attr('src',$('#iframeID',parent.document).attr('src'));

Performing Breadth First Search recursively

The following method used a DFS algorithm to get all nodes in a particular depth - which is same as doing BFS for that level. If you find out depth of the tree and do this for all levels, the results will be same as a BFS.

public void PrintLevelNodes(Tree root, int level) {
    if (root != null) {
        if (level == 0) {
            Console.Write(root.Data);
            return;
        }
        PrintLevelNodes(root.Left, level - 1);
        PrintLevelNodes(root.Right, level - 1);
    }
}

for (int i = 0; i < depth; i++) {
    PrintLevelNodes(root, i);
}

Finding depth of a tree is a piece of cake:

public int MaxDepth(Tree root) {
    if (root == null) {
        return 0;
    } else {
        return Math.Max(MaxDepth(root.Left), MaxDepth(root.Right)) + 1;
    }
}

Is Java RegEx case-insensitive?

RegexBuddy is telling me if you want to include it at the beginning, this is the correct syntax:

"(?i)\\b(\\w+)\\b(\\s+\\1)+\\b"

How do I set up HttpContent for my HttpClient PostAsync second parameter?

    public async Task<ActionResult> Index()
    {
        apiTable table = new apiTable();
        table.Name = "Asma Nadeem";
        table.Roll = "6655";

        string str = "";
        string str2 = "";

        HttpClient client = new HttpClient();

        string json = JsonConvert.SerializeObject(table);

        StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

        var response = await client.PostAsync("http://YourSite.com/api/apiTables", httpContent);

        str = "" + response.Content + " : " + response.StatusCode;

        if (response.IsSuccessStatusCode)
        {       
            str2 = "Data Posted";
        }

        return View();
    }

C++ - unable to start correctly (0xc0150002)

I take it that is a Vista Window! I often got this when first trying to port a DirectX program from XPsp3 to Vista.

It's a .dll problem. The OpenCV runtime.dll will call upon a system.dll that will be no longer shipped Vista, so unfortunately you will have to to a bit of hunting to find which system.dll it's trying to find. (system.dll could be vc2010 or vista)

This error is also caused by incorrect installation of .dlls (i.e not rolling out) hth Happy hunting

RichTextBox (WPF) does not have string property "Text"

"Extended WPF Toolkit" now provides a richtextbox with the Text property.

You can get or set the text in different formats (XAML, RTF and plaintext).

Here is the link: Extended WPF Toolkit RichTextBox

Can't perform a React state update on an unmounted component

The solution from @ford04 didn't worked to me and specially if you need to use the isMounted in multiple places (multiple useEffect for instance), it's recommended to useRef, as bellow:

  1. Essential packages
"dependencies": 
{
  "react": "17.0.1",
}
"devDependencies": { 
  "typescript": "4.1.5",
}

  1. My Hook Component
export const SubscriptionsView: React.FC = () => {
  const [data, setData] = useState<Subscription[]>();
  const isMounted = React.useRef(true);

  React.useEffect(() => {
    if (isMounted.current) {
      // fetch data
      // setData (fetch result)

      return () => {
        isMounted.current = false;
      };
    }
  }
});

"The system cannot find the file C:\ProgramData\Oracle\Java\javapath\java.exe"

I got same error while running JAVA command. To resolve this, I moved the java path as the first entry in the path, and it resolved the issue. Please have look at this screenshot for reference:

enter image description here

Multiple types were found that match the controller named 'Home'

This error message often happens when you use areas and you have the same controller name inside the area and the root. For example you have the two:

  • ~/Controllers/HomeController.cs
  • ~/Areas/Admin/Controllers/HomeController.cs

In order to resolve this issue (as the error message suggests you), you could use namespaces when declaring your routes. So in the main route definition in Global.asax:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    new[] { "AppName.Controllers" }
);

and in your ~/Areas/Admin/AdminAreaRegistration.cs:

context.MapRoute(
    "Admin_default",
    "Admin/{controller}/{action}/{id}",
    new { action = "Index", id = UrlParameter.Optional },
    new[] { "AppName.Areas.Admin.Controllers" }
);

If you are not using areas it seems that your both applications are hosted inside the same ASP.NET application and conflicts occur because you have the same controllers defined in different namespaces. You will have to configure IIS to host those two as separate ASP.NET applications if you want to avoid such kind of conflicts. Ask your hosting provider for this if you don't have access to the server.

div inside table

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <title>test</title>
  </head>
  <body>
    <table>
      <tr>
        <td>
          <div>content</div>
        </td>
      </tr>
    </table>
  </body>
</html>

This document was successfully checked as XHTML 1.0 Transitional!

Pandas timeseries plot setting x-axis major and minor ticks and labels

Both pandas and matplotlib.dates use matplotlib.units for locating the ticks.

But while matplotlib.dates has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).

So for the moment it seems more reasonable to use matplotlib.dates (as mentioned by @BrenBarn in his comment).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt 
import matplotlib.dates as dates

idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)

fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
                                                interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()

pandas_like_date_fomatting

(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])

Mod in Java produces negative numbers

Since Java 8 you can use the Math.floorMod() method:

Math.floorMod(-1, 2); //== 1

Note: If the modulo-value (here 2) is negative, all output values will be negative too. :)

Source: https://stackoverflow.com/a/25830153/2311557

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

Difference between except: and except Exception as e: in Python

There are differences with some exceptions, e.g. KeyboardInterrupt.

Reading PEP8:

A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:).

Where can I view Tomcat log files in Eclipse?

@royalsampler said:

Go to the Servers view in Eclipse then right click on the server and click Open. The log files are stored in a folder realative to the path in the "Server path" field.

Since the path field is uneditable, you can also "Open Launch Configuration", click Arguments tab, copy the VM argument for catalina.base (within quotes). This is the full path of your WTP webapp directory. Copying the value to the clipboard can save you the laborious task of browsing the file system to the path.

Also note you should be seeing the output to the log file in your Console view as you run or debug.

Java decimal formatting using String.format?

You want java.text.DecimalFormat

Swift performSelector:withObject:afterDelay: is unavailable

Swift is statically typed so the performSelector: methods are to fall by the wayside.

Instead, use GCD to dispatch a suitable block to the relevant queue — in this case it'll presumably be the main queue since it looks like you're doing UIKit work.

EDIT: the relevant performSelector: is also notably missing from the Swift version of the NSRunLoop documentation ("1 Objective-C symbol hidden") so you can't jump straight in with that. With that and its absence from the Swiftified NSObject I'd argue it's pretty clear what Apple is thinking here.

ReactJS lifecycle method inside a function Component

if you using react 16.8 you can use react Hooks... React Hooks are functions that let you “hook into” React state and lifecycle features from function components... docs

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
</div>
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */
}

WORKING DEMO.


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;
}

UPDATED DEMO.

Python pip install module is not found. How to link python to pip location?

No other solutions were working for me, so I tried:

pip uninstall <module> && pip install <module>

And that resolved it for me. Your mileage may vary.

Force file download with php using header()

The problem was that I used ajax to post the message to the server, when I used a direct link to download the file everything worked fine.

I used this other Stackoverflow Q&A material instead, it worked great for me:

Open a link in browser with java button?

Use the Desktop#browse(URI) method. It opens a URI in the user's default browser.

public static boolean openWebpage(URI uri) {
    Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
    if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
        try {
            desktop.browse(uri);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return false;
}

public static boolean openWebpage(URL url) {
    try {
        return openWebpage(url.toURI());
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return false;
}

How do you add CSS with Javascript?

You can also do this using DOM Level 2 CSS interfaces (MDN):

var sheet = window.document.styleSheets[0];
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);

...on all but (naturally) IE8 and prior, which uses its own marginally-different wording:

sheet.addRule('strong', 'color: red;', -1);

There is a theoretical advantage in this compared to the createElement-set-innerHTML method, in that you don't have to worry about putting special HTML characters in the innerHTML, but in practice style elements are CDATA in legacy HTML, and ‘<’ and ‘&’ are rarely used in stylesheets anyway.

You do need a stylesheet in place before you can started appending to it like this. That can be any existing active stylesheet: external, embedded or empty, it doesn't matter. If there isn't one, the only standard way to create it at the moment is with createElement.

Changing SQL Server collation to case insensitive from case sensitive?

You basically need to run the installation again to rebuild the master database with the new collation. You cannot change the entire server's collation any other way.

See:

Update: if you want to change the collation of a database, you can get the current collation using this snippet of T-SQL:

SELECT name, collation_name 
FROM sys.databases
WHERE name = 'test2'   -- put your database name here

This will yield a value something like:

Latin1_General_CI_AS

The _CI means "case insensitive" - if you want case-sensitive, use _CS in its place:

Latin1_General_CS_AS

So your T-SQL command would be:

ALTER DATABASE test2 -- put your database name here
   COLLATE Latin1_General_CS_AS   -- replace with whatever collation you need

You can get a list of all available collations on the server using:

SELECT * FROM ::fn_helpcollations()

You can see the server's current collation using:

SELECT SERVERPROPERTY ('Collation')

How to read a single char from the console in Java (as the user types it)?

There is no portable way to read raw characters from a Java console.

Some platform-dependent workarounds have been presented above. But to be really portable, you'd have to abandon console mode and use a windowing mode, e.g. AWT or Swing.

How to sort a NSArray alphabetically?

The other answers provided here mention using @selector(localizedCaseInsensitiveCompare:) This works great for an array of NSString, however if you want to extend this to another type of object, and sort those objects according to a 'name' property, you should do this instead:

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
sortedArray=[anArray sortedArrayUsingDescriptors:@[sort]];

Your objects will be sorted according to the name property of those objects.

If you want the sorting to be case insensitive, you would need to set the descriptor like this

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];

Fire event on enter key press for a textbox

  1. Wrap the textbox inside asp:Panel tags

  2. Hide a Button that has a click event that does what you want done and give the <asp:panel> a DefaultButton Attribute with the ID of the Hidden Button.

<asp:Panel runat="server" DefaultButton="Button1">
   <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>    
   <asp:Button ID="Button1" runat="server" style="display:none" OnClick="Button1_Click" />
</asp:Panel>

How do you do Impersonation in .NET?

"Impersonation" in the .NET space generally means running code under a specific user account. It is a somewhat separate concept than getting access to that user account via a username and password, although these two ideas pair together frequently. I will describe them both, and then explain how to use my SimpleImpersonation library, which uses them internally.

Impersonation

The APIs for impersonation are provided in .NET via the System.Security.Principal namespace:

  • Newer code (.NET 4.6+, .NET Core, etc.) should generally use WindowsIdentity.RunImpersonated, which accepts a handle to the token of the user account, and then either an Action or Func<T> for the code to execute.

    WindowsIdentity.RunImpersonated(tokenHandle, () =>
    {
        // do whatever you want as this user.
    });
    

    or

    var result = WindowsIdentity.RunImpersonated(tokenHandle, () =>
    {
        // do whatever you want as this user.
        return result;
    });
    
  • Older code used the WindowsIdentity.Impersonate method to retrieve a WindowsImpersonationContext object. This object implements IDisposable, so generally should be called from a using block.

    using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(tokenHandle))
    {
        // do whatever you want as this user.
    }
    

    While this API still exists in .NET Framework, it should generally be avoided, and is not available in .NET Core or .NET Standard.

Accessing the User Account

The API for using a username and password to gain access to a user account in Windows is LogonUser - which is a Win32 native API. There is not currently a built-in .NET API for calling it, so one must resort to P/Invoke.

[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);

This is the basic call definition, however there is a lot more to consider to actually using it in production:

  • Obtaining a handle with the "safe" access pattern.
  • Closing the native handles appropriately
  • Code access security (CAS) trust levels (in .NET Framework only)
  • Passing SecureString when you can collect one safely via user keystrokes.

The amount of code to write to illustrate all of this is beyond what should be in a StackOverflow answer, IMHO.

A Combined and Easier Approach

Instead of writing all of this yourself, consider using my SimpleImpersonation library, which combines impersonation and user access into a single API. It works well in both modern and older code bases, with the same simple API:

var credentials = new UserCredentials(domain, username, password);
Impersonation.RunAsUser(credentials, logonType, () =>
{
    // do whatever you want as this user.
}); 

or

var credentials = new UserCredentials(domain, username, password);
var result = Impersonation.RunAsUser(credentials, logonType, () =>
{
    // do whatever you want as this user.
    return something;
});

Note that it is very similar to the WindowsIdentity.RunImpersonated API, but doesn't require you know anything about token handles.

This is the API as of version 3.0.0. See the project readme for more details. Also note that a previous version of the library used an API with the IDisposable pattern, similar to WindowsIdentity.Impersonate. The newer version is much safer, and both are still used internally.

Xampp MySQL not starting - "Attempting to start MySQL service..."

In Windows, you should go: Start > Run > services.msc > Apache 2.4 > Properties > Start Mode > Automatic > Apply > Start > OK > [Same as MySQL]

Can't install nuget package because of "Failed to initialize the PowerShell host"

There are an awful lot of stabs in the dark here, so I'll add my own.

In my case, I also got a message that there was a missing lock file, and a recommendation to run dnu restore in the package manager console. I did so, restarted VS, and everything is now working.

python list in sql query as parameter

string.join the list values separated by commas, and use the format operator to form a query string.

myquery = "select name from studens where id in (%s)" % ",".join(map(str,mylist))

(Thanks, blair-conrad)

How do I get a file name from a full path with PHP?

To get the exact file name from the URI, I would use this method:

<?php
    $file1 =basename("http://localhost/eFEIS/agency_application_form.php?formid=1&task=edit") ;

    //basename($_SERVER['REQUEST_URI']); // Or use this to get the URI dynamically.

    echo $basename = substr($file1, 0, strpos($file1, '?'));
?>

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

implement addClass and removeClass functionality in angular2

If you want to due this in component.ts

HTML:

<button class="class1 class2" (click)="clicked($event)">Click me</button>

Component:

clicked(event) {
  event.target.classList.add('class3'); // To ADD
  event.target.classList.remove('class1'); // To Remove
  event.target.classList.contains('class2'); // To check
  event.target.classList.toggle('class4'); // To toggle
}

For more options, examples and browser compatibility visit this link.

How do I run a Python script from C#?

Execute Python script from C

Create a C# project and write the following code.

using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            run_cmd();
        }

        private void run_cmd()
        {

            string fileName = @"C:\sample_script.py";

            Process p = new Process();
            p.StartInfo = new ProcessStartInfo(@"C:\Python27\python.exe", fileName)
            {
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };
            p.Start();

            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

            Console.WriteLine(output);

            Console.ReadLine();

        }
    }
}

Python sample_script

print "Python C# Test"

You will see the 'Python C# Test' in the console of C#.

Python Script Uploading files via FTP

Try this:

#!/usr/bin/env python

import os
import paramiko 
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('hostname', username="username", password="password")
sftp = ssh.open_sftp()
localpath = '/home/e100075/python/ss.txt'
remotepath = '/home/developers/screenshots/ss.txt'
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()

How can I disable HREF if onclick is executed?

<a href="http://www.google.com" class="ignore-click">Test</a>

with jQuery:

<script>
    $(".ignore-click").click(function(){
        return false;
    })
</script>

with JavaScript

<script>
        for (var i = 0; i < document.getElementsByClassName("ignore-click").length; i++) {
            document.getElementsByClassName("ignore-click")[i].addEventListener('click', function (event) {
                event.preventDefault();
                return false;
            });
        }
</script>

You assign class .ignore-click to as many elements you like and clicks on those elements will be ignored

Git log out user from command line

If you are facing any issues during push ( in windows OS), just remove the cached git account by following the given steps below: 1. Search for Control panel and open the same. 2. Search for Credential Manager and open this. 3. Click on Windows Credentials under Manage your credentials page. 4. Under Generic Credentials click on GitHub. 5. Click on Remove and then confirm by clicking Yes button. 6. Now start pushing the code and you will get GitHub popup to login again and now you are done. Everything will work properly after successful login.

How to make google spreadsheet refresh itself every 1 minute?

If you are only looking for a refresh rate for the GOOGLEFINANCE function, keep in mind that data delays can be up to 20 minutes (per Google Finance Disclaimer).

Single-symbol refresh rate (using GoogleClock)

Here is a modified version of the refresh action, taking the data delay into consideration, to save on unproductive refresh cycles.

=GoogleClock(GOOGLEFINANCE(symbol,"datadelay"))

For example, with:

  • SYMBOL: GOOG
  • DATA DELAY: 15 (minutes)

then

=GoogleClock(GOOGLEFINANCE("GOOG","datadelay"))

Results in a dynamic data-based refresh rate of:

=GoogleClock(15)

Multi-symbol refresh rate (using GoogleClock)

If your sheet contains a number of rows of symbols, you could add a datadelay column for each symbol and use the lowest value, for example:

=GoogleClock(MIN(dataDelayValuesNamedRange))

Where dataDelayValuesNamedRange is the absolute reference or named reference of the range of cells that contain the data delay values for each symbol (assuming these values are different).

Without GoogleClock()

The GoogleClock() function was removed in 2014 and replaced with settings setup for refreshing sheets. At present, I have confirmed that replacement settings is only on available in Sheets from when accessed from a desktop browser, not the mobile app (I'm using Google's mobile Sheets app updated 2016-03-14).

(This part of the answer is based on, and portions copied from, Google Docs Help)

To change how often "some" Google Sheets functions update:

  1. Open a spreadsheet. Click File > Spreadsheet settings.
  2. In the RECALCULATION section, choose a setting from the drop-down menu.
  3. Setting options are:
    • On change
    • On change and every minute
    • On change and every hour
  4. Click SAVE SETTINGS.

NOTE External data functions recalculate at the following intervals:

  • ImportRange: 30 minutes
  • ImportHtml, ImportFeed, ImportData, ImportXml: 1 hour
  • GoogleFinance: 2 minutes

The references in earlier sections to the display and use of the datadelay attribute still apply, as well as the concepts for more efficient coding of sheets.

On a positive note, the new refresh option continues to be refreshed by Google servers regardless of whether you have the sheet loaded or not. That's a positive for shared sheets for sure; even more so for Google Apps Scripts (GAS), where GAS is used in workflow code or referenced data is used as a trigger for an event.

[*] in my understanding so far (I am currently testing this)

Make .gitignore ignore everything except a few files

To ignore some files in a directory, you have to do this in the correct order:

For example, ignore everything in folder "application" except index.php and folder "config" pay attention to the order.

You must negate want you want first.

FAILS

application/*

!application/config/*

!application/index.php

WORKS

!application/config/*

!application/index.php

application/*

Python - IOError: [Errno 13] Permission denied:

I had a same problem. In my case, the user did not have write permission to the destination directory. Following command helped in my case :

chmod 777 University

reading HttpwebResponse json response, C#

I'd use RestSharp - https://github.com/restsharp/RestSharp

Create class to deserialize to:

public class MyObject {
    public string Id { get; set; }
    public string Text { get; set; }
    ...
}

And the code to get that object:

RestClient client = new RestClient("http://whatever.com");
RestRequest request = new RestRequest("path/to/object");
request.AddParameter("id", "123");

// The above code will make a request URL of 
// "http://whatever.com/path/to/object?id=123"
// You can pick and choose what you need

var response = client.Execute<MyObject>(request);

MyObject obj = response.Data;

Check out http://restsharp.org/ to get started.

number_format() with MySQL

You need this:

CONCAT(REPLACE(FORMAT(number,0),',','.'),',',SUBSTRING_INDEX(FORMAT(number,2),'.',-1))

iPhone UITextField - Change placeholder text color

Also in your storyboard, without single line of code

enter image description here

Unable to connect to mongodb Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112

If any one is facing the problem in windows machine then follow the steps.

  1. Add the path of mongodb in the environmental variable.
  2. Create a directory C:\Data\db.
  3. Open a terminal(cmd) and write mongod. (it will initiate the server).
  4. Open another terminal and write your own code.

Java heap terminology: young, old and permanent generations?

What is the young generation?

The Young Generation is where all new objects are allocated and aged. When the young generation fills up, this causes a minor garbage collection. A young generation full of dead objects is collected very quickly. Some survived objects are aged and eventually move to the old generation.

What is the old generation?

The Old Generation is used to store long surviving objects. Typically, a threshold is set for young generation object and when that age is met, the object gets moved to the old generation. Eventually the old generation needs to be collected. This event is called a major garbage collection

What is the permanent generation?

The Permanent generation contains metadata required by the JVM to describe the classes and methods used in the application. The permanent generation is populated by the JVM at runtime based on classes in use by the application.

PermGen has been replaced with Metaspace since Java 8 release.

PermSize & MaxPermSize parameters will be ignored now

How does the three generations interact/relate to each other?

enter image description here

Image source & oracle technetwork tutorial article: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

"The General Garbage Collection Process" in above article explains the interactions between them with many diagrams.

Have a look at summary diagram:

enter image description here

creating an array of structs in c++

It works perfectly. I have gcc compiler C++11 ready. Try this and you'll see:

#include <iostream>

using namespace std;

int main()
{
    int pause;

    struct Customer
    {
           int uid;
           string name;
    };

    Customer customerRecords[2];
    customerRecords[0] = {25, "Bob Jones"};
    customerRecords[1] = {26, "Jim Smith"};
    cout << customerRecords[0].uid << " " << customerRecords[0].name << endl;
    cout << customerRecords[1].uid << " " << customerRecords[1].name << endl;
    cin >> pause;
return 0;
}

How to create major and minor gridlines with different linestyles in Python

A simple DIY way would be to make the grid yourself:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot([1,2,3], [2,3,4], 'ro')

for xmaj in ax.xaxis.get_majorticklocs():
  ax.axvline(x=xmaj, ls='-')
for xmin in ax.xaxis.get_minorticklocs():
  ax.axvline(x=xmin, ls='--')

for ymaj in ax.yaxis.get_majorticklocs():
  ax.axhline(y=ymaj, ls='-')
for ymin in ax.yaxis.get_minorticklocs():
  ax.axhline(y=ymin, ls='--')
plt.show()

REST - HTTP Post Multipart with JSON

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--

PostgreSQL Crosstab Query

Crosstab function is available under the tablefunc extension. You'll have to create this extension one time for the database.

CREATE EXTENSION tablefunc;

You can use the below code to create pivot table using cross tab:

create table test_Crosstab( section text,
<br/>status text,
<br/>count numeric)

<br/>insert into test_Crosstab values ( 'A','Active',1)
                <br/>,( 'A','Inactive',2)
                <br/>,( 'B','Active',4)
                <br/>,( 'B','Inactive',5)

select * from crosstab(
<br/>'select section
    <br/>,status
    <br/>,count
    <br/>from test_crosstab'
    <br/>)as ctab ("Section" text,"Active" numeric,"Inactive" numeric)

How to list only top level directories in Python?

A very much simpler and elegant way is to use this:

 import os
 dir_list = os.walk('.').next()[1]
 print dir_list

Run this script in the same folder for which you want folder names.It will give you exactly the immediate folders name only(that too without the full path of the folders).

connecting to MySQL from the command line

One way to connect to MySQL directly using proper MySQL username and password is:

mysql --user=root --password=mypass

Here,

root is the MySQL username
mypass is the MySQL user password

This is useful if you have a blank password.

For example, if you have MySQL user called root with an empty password, just use

mysql --user=root --password=

Authentication failed to bitbucket

In windows this worked for me

git config --global http.sslVerify false

initializing a Guava ImmutableMap

if the map is short you can do:

ImmutableMap.of(key, value, key2, value2); // ...up to five k-v pairs

If it is longer then:

ImmutableMap.builder()
   .put(key, value)
   .put(key2, value2)
   // ...
   .build();

Unable to set variables in bash script

folder = "ABC" tries to run a command named folder with arguments = and "ABC". The format of command in bash is:

command arguments separated with space

while assignment is done with:

variable=something

  • In [ -f $newfoldername/Primetime.eyetv], [ is a command (test) and -f and $newfoldername/Primetime.eyetv] are two arguments. It expects a third argument (]) which it can't find (arguments must be separated with space) and thus will show error.
  • [-f $newfoldername/Primetime.eyetv] tries to run a command [-f with argument $newfoldername/Primetime.eyetv]

Generally for cases like this, paste your code in shellcheck and see the feedback.

OAuth: how to test with local URLs?

For Mac users, edit the /etc/hosts file. You have to use sudo vi /etc/hosts if its read-only. After authorization, the oauth server sends the callback URL, and since that callback URL is rendered on your local browser, the local DNS setting will work:

127.0.0.1       mylocal.com

Android Studio says "cannot resolve symbol" but project compiles

I also had this issue with my Android app depending on some of my own Android libraries (using Android Studio 3.0 and 3.1.1).

Whenever I updated a lib and go back to the app, triggering a Gradle Sync, Android Studio was not able to detect the code changes I made to the lib. Compilation worked fine, but Android Studio showed red error lines on some code using the lib.

After investigating, I found that it's because gradle keeps pointing to an old compiled version of my libs. If you go to yourProject/.idea/libraries/ you'll see a list of xml files that contains the link to the compiled version of your libs. These files starts with Gradle__artifacts_*.xml (where * is the name of your libs).

So in order for Android Studio to take the latest version of your libs, you need to delete these Gradle__artifacts_*.xml files, and Android Studio will regenerate them, pointing to the latest compiled version of your libs.

If you don't want to do that manually every time you click on "Gradle sync" (who would want to do that...), you can add this small gradle task in the build.gradle file of your app.

task deleteArtifacts {
    doFirst {
        File librariesFolderPath = file(getProjectDir().absolutePath + "/../.idea/libraries/")
        File[] files = librariesFolderPath.listFiles({ File file -> file.name.startsWith("Gradle__artifacts_") } as FileFilter)

        for (int i = 0; i < files.length; i++) {
            files[i].delete()
        }
    }
}

And in order for your app to always execute this task before doing a gradle sync, you just need to go to the Gradle window, then find the "deleteArtifacts" task under yourApp/Tasks/other/, right click on it and select "Execute Before Sync" (see below).

Gradle window to configure task execution

Now, every time you do a Gradle sync, Android Studio will be forced to use the latest version of your libs.

Make the size of a heatmap bigger with seaborn

You could alter the figsize by passing a tuple showing the width, height parameters you would like to keep.

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10,10))         # Sample figsize in inches
sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax)

EDIT

I remember answering a similar question of yours where you had to set the index as TIMESTAMP. So, you could then do something like below:

df = df.set_index('TIMESTAMP')
df.resample('30min').mean()
fig, ax = plt.subplots()
ax = sns.heatmap(df.iloc[:, 1:6:], annot=True, linewidths=.5)
ax.set_yticklabels([i.strftime("%Y-%m-%d %H:%M:%S") for i in df.index], rotation=0)

For the head of the dataframe you posted, the plot would look like:

enter image description here

Heap vs Binary Search Tree (BST)

Heap just guarantees that elements on higher levels are greater (for max-heap) or smaller (for min-heap) than elements on lower levels

I love the above answer and putting my comment just more specific to my need and usage. I had to get the n locations list find the distance from each location to specific point say (0,0) and then return the a m locations having smaller distance. I used Priority Queue which is Heap. For finding distances and putting in heap it took me n(log(n)) n-locations log(n) each insertion. Then for getting m with shortest distances it took m(log(n)) m-locations log(n) deletions of heaping up.

I if would have to do this with BST, it would have taken me n(n) worst case insertion.(Say the first value is very smaller and all other comes sequentially longer and longer and the tree spans to right child only or left child in case of smaller and smaller. The min would have taken O(1) time but again I had to balance. So from my situation and all above answers what I got is when you are only after the values at min or max priority basis go for heap.

how to stop a running script in Matlab

if you are running your matlab on linux, you can terminate the matlab by command in linux consule. first you should find the PID number of matlab by this code:

top

then you can use this code to kill matlab: kill

example: kill 58056

Mongoose and multiple database in single node.js project

As an alternative approach, Mongoose does export a constructor for a new instance on the default instance. So something like this is possible.

var Mongoose = require('mongoose').Mongoose;

var instance1 = new Mongoose();
instance1.connect('foo');

var instance2 = new Mongoose();
instance2.connect('bar');

This is very useful when working with separate data sources, and also when you want to have a separate database context for each user or request. You will need to be careful, as it is possible to create a LOT of connections when doing this. Make sure to call disconnect() when instances are not needed, and also to limit the pool size created by each instance.