Programs & Examples On #Interprocess

A capability supported by some operating systems that allows one process to communicate with another process. The processes can be running on the same computer or on different computers connected through a network. It enables one application to control another application, and for several applications to share the same data without interfering with one another.

How to change visibility of layout programmatically

You can change layout visibility just in the same way as for regular view. Use setVisibility(View.GONE) etc. All layouts are just Views, they have View as their parent.

Run ssh and immediately execute command

You can use the LocalCommand command-line option if the PermitLocalCommand option is enabled:

ssh username@hostname -o LocalCommand="tmux list-sessions"

For more details about the available options, see the ssh_config man page.

How to set a background image in Xcode using swift?

SWIFT 4

view.layer.contents = #imageLiteral(resourceName: "webbg").cgImage

MySQL Creating tables with Foreign Keys giving errno: 150

As pointed by @andrewdotn the best way is to see the detailed error(SHOW ENGINE INNODB STATUS;) instead of just an error code.

One of the reasons could be that an index already exists with the same name, may be in another table. As a practice, I recommend prefixing table name before the index name to avoid such collisions. e.g. instead of idx_userId use idx_userActionMapping_userId.

Why does my sorting loop seem to append an element where it shouldn't?

Starting from Java 8, you can also use parallelSort which is useful if you have arrays containing a lot of elements.

Example:

public static void main(String[] args) {
    String[] strings = { "x", "a", "c", "b", "y" };
    Arrays.parallelSort(strings);
    System.out.println(Arrays.toString(strings));   // [a, b, c, x, y]
}

If you want to ignore the case, you can use:

public static void main(String[] args) {
    String[] strings = { "x", "a", "c", "B", "y" };
    Arrays.parallelSort(strings, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {              
            return o1.compareToIgnoreCase(o2);
        }
    });
    System.out.println(Arrays.toString(strings));   // [a, B, c, x, y]
}

otherwise B will be before a.

If you want to ignore the trailing spaces during the comparison, you can use trim():

public static void main(String[] args) {
    String[] strings = { "x", "  a", "c ", " b", "y" };
    Arrays.parallelSort(strings, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {              
            return o1.trim().compareTo(o2.trim());
        }
    });
    System.out.println(Arrays.toString(strings)); // [  a,  b, c , x, y]
}

See:

EntityType has no key defined error

All is right but in my case i have two class like this

namespace WebAPI.Model
{
   public class ProductsModel
{ 
        [Table("products")]
        public class Products
        {
            [Key]
            public int slno { get; set; }

            public int productId { get; set; }
            public string ProductName { get; set; }

            public int Price { get; set; }
}
        }
    }

After deleting the upper class it works fine for me.

When to use IMG vs. CSS background-image?

Just a small one to add, you should use the img tag if you want users to be able to 'right click' and 'save-image'/'save-picture', so if you intend to provide the image as a resource for others.

Using background image will (as far as I'm aware on most browsers) disable the option to save the image directly.

How to update an "array of objects" with Firestore?

If anybody is looking for Java firestore sdk solution to add items in array field:

List<String> list = java.util.Arrays.asList("A", "B");
Object[] fieldsToUpdate = list.toArray();
DocumentReference docRef = getCollection().document("docId");
docRef.update(fieldName, FieldValue.arrayUnion(fieldsToUpdate));

To delete items from array user: FieldValue.arrayRemove()

Android Fragment no view found for ID?

The solution was to use getChildFragmentManager()

instead of getFragmentManager()

when calling from a fragment. If you are calling the method from an activity, then use getFragmentManager().

That will solve the problem.

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

I had the same problem after installing TensorFlow package, which downgraded my pandas version from 2.23 to 2.22. I tried all the solutions proposed above + the one suggested by post author, linked here. What eventually worked for me was to reinstall Anaconda distribution.

What are CN, OU, DC in an LDAP search?

  • CN = Common Name
  • OU = Organizational Unit
  • DC = Domain Component

These are all parts of the X.500 Directory Specification, which defines nodes in a LDAP directory.

You can also read up on LDAP data Interchange Format (LDIF), which is an alternate format.

You read it from right to left, the right-most component is the root of the tree, and the left most component is the node (or leaf) you want to reach.

Each = pair is a search criteria.

With your example query

("CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com");

In effect the query is:

From the com Domain Component, find the google Domain Component, and then inside it the gl Domain Component and then inside it the gp Domain Component.

In the gp Domain Component, find the Organizational Unit called Distribution Groups and then find the the object that has a common name of Dev-India.

Examples of good gotos in C or C++

#include <stdio.h>
#include <string.h>

int main()
{
    char name[64];
    char url[80]; /*The final url name with http://www..com*/
    char *pName;
    int x;

    pName = name;

    INPUT:
    printf("\nWrite the name of a web page (Without www, http, .com) ");
    gets(name);

    for(x=0;x<=(strlen(name));x++)
        if(*(pName+0) == '\0' || *(pName+x) == ' ')
        {
            printf("Name blank or with spaces!");
            getch();
            system("cls");
            goto INPUT;
        }

    strcpy(url,"http://www.");
    strcat(url,name);
    strcat(url,".com");

    printf("%s",url);
    return(0);
}

Organizing a multiple-file Go project

Let's explorer how the go get repository_remote_url command manages the project structure under $GOPATH. If we do a go get github.com/gohugoio/hugo It will clone the repository under

$GOPATH/src/repository_remote/user_name/project_name


$GOPATH/src/github.com/gohugoio/hugo

This is a nice way to create your initial project path. Now let's explorer what are the project types out there and how their inner structures are organized. All golang projects in the community can be categorized under

  • Libraries (no executable binaries)
  • Single Project (contains only 1 executable binary)
  • Tooling Projects (contains multiple executable binaries)

Generally golang project files can be packaged under any design principles such as DDD, POD

Most of the available go projects follows this Package Oriented Design

Package Oriented Design encourage the developer to keeps the implementation only inside it's own packages, other than the /internal package those packages can't can communicate with each other


Libraries

  • Projects such as database drivers, qt can put under this category.
  • Some libraries such as color, now follows a flat structure without any other packages.
  • Most of these library projects manages a package called internal.
  • /internal package is mainly used to hide the implementation from other projects.
  • Don't have any executable binaries, so no files that contains the main func.

 ~/$GOPATH/
    bin/
    pkg/
    src/
      repository_remote/
        user_name/
            project_name/
              internal/
              other_pkg/

Single Project

  • Projects such as hugo, etcd has a single main func in root level and.
  • Target is to generate one single binary

Tooling Projects

  • Projects such as kubernetes, go-ethereum has multiple main func organized under a package called cmd
  • cmd/ package manages the number of binaries (tools) that we want to build

 ~/$GOPATH/
    bin/
    pkg/
    src/
      repository_remote/
        user_name/
            project_name/
              cmd/
                binary_one/
                   main.go
                binary_two/
                   main.go
                binary_three/
                   main.go
              other_pkg/

How do I uninstall a package installed using npm link?

npm link pain:

-Module name gulp-task

-Project name project-x


You want to link gulp-task:

1: Go to the gulp-task directory then do npm link this will symlink the project to your global modules

2: Go to your project project-x then do npm install make sure to remove the current node_modules directory


Now you want to remove this madness and use the real gulp-task, we have two options:

Option 1: Unlink via npm:

1: Go to your project and do npm unlink gulp-task this will remove the linked installed module

2: Go to the gulp-task directory and do npm unlink to remove symlink. Notice we didn't use the name of the module

3: celebrate


What if this didn't work, verify by locating your global installed module. My are location ls -la /usr/local/lib/node_modules/ if you are using nvm it will be a different path


Option 2: Remove the symlink like a normal linux guru

1: locate your global dependencies cd /usr/local/lib/node_modules/

2: removing symlink is simply using the rm command

rm gulp-task make sure you don't have / at the end

rm gulp-task/ is wrong

rm gulp-task ??

Get text of label with jquery

for the line you wrote

var g = $('<%=Label1.ClientID%>').val(); // Also I tried .text() and .html()

you missed adding #. it should be like this

var g = $('#<%=Label1.ClientID%>').text();

also I do not prefer using this method

that's because if you are calling a control in master or nested master page or if you are calling a control in page from master. Also controls in Repeater. regardless the MVC. this will cause problems.

you should ALWAYS call the ID of the control directly. like this

$('#ControlID')

this is simple and clear. but do not forget to set

ClientIDMode="Static"

in your controls to remain with same ID name after render. that's because ASP.net will modify the ID name in HTML rendered file in some contexts i.e. the page is for Master page the control name will be ConetentPlaceholderName_controlID

I hope it clears the question Good Luck

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

in controller just convert json data to object using json_decode php function like this

$member = json_decode($json_string); 

and pass to view in view

return view('page',compact('$member'))

in view blade

Member ID: {{$member->member[0]->id}}
Firstname: {{$member->member[0]->firstname}}
Lastname: {{$member->member[0]->lastname}}
Phone: {{$member->member[0]->phone}}

Owner ID: {{$member->owner[0]->id}}
Firstname: {{$member->owner[0]->firstname}}
Lastname: {{$member->owner[0]->lastname}}

Algorithm: efficient way to remove duplicate integers from an array

After review the problem, here is my delphi way, that may help

var
A: Array of Integer;
I,J,C,K, P: Integer;
begin
C:=10;
SetLength(A,10);
A[0]:=1; A[1]:=4; A[2]:=2; A[3]:=6; A[4]:=3; A[5]:=4;
A[6]:=3; A[7]:=4; A[8]:=2; A[9]:=5;

for I := 0 to C-1 do
begin
  for J := I+1 to C-1 do
    if A[I]=A[J] then
    begin
      for K := C-1 Downto J do
        if A[J]<>A[k] then
        begin
          P:=A[K];
          A[K]:=0;
          A[J]:=P;
          C:=K;
          break;
        end
        else
        begin
          A[K]:=0;
          C:=K;
        end;
    end;
end;

//tructate array
setlength(A,C);
end;

Checking if any elements in one list are in another

I wrote the following code in one of my projects. It basically compares each individual element of the list. Feel free to use it, if it works for your requirement.

def reachedGoal(a,b):
    if(len(a)!=len(b)):
        raise ValueError("Wrong lists provided")

    for val1 in range(0,len(a)):
        temp1=a[val1]
        temp2=b[val1]
        for val2 in range(0,len(b)):
            if(temp1[val2]!=temp2[val2]):
                return False
    return True

Multiline TextBox multiple newline

I had the same problem. If I add one Environment.Newline I get one new line in the textbox. But if I add two Environment.Newline I get one new line. In my web app I use a whitespace modul that removes all unnecessary white spaces. If i disable this module I get two new lines in my textbox. Hope that helps.

What is the Eclipse shortcut for "public static void main(String args[])"?

As bmargulies mentioned:

Preferences>Java>Editor>Templates>New...

enter image description here

enter image description here

Now, type psvm then Ctrl + Space on Mac or Windows.

How to throw an exception in C?

In C you could use the combination of the setjmp() and longjmp() functions, defined in setjmp.h. Example from Wikipedia

#include <stdio.h>
#include <setjmp.h>

static jmp_buf buf;

void second(void) {
    printf("second\n");         // prints
    longjmp(buf,1);             // jumps back to where setjmp 
                                //   was called - making setjmp now return 1
}

void first(void) {
    second();
    printf("first\n");          // does not print
}

int main() {   
    if ( ! setjmp(buf) ) {
        first();                // when executed, setjmp returns 0
    } else {                    // when longjmp jumps back, setjmp returns 1
        printf("main");         // prints
    }

    return 0;
}

Note: I would actually advise you not to use them as they work awful with C++ (destructors of local objects wouldn't get called) and it is really hard to understand what is going on. Return some kind of error instead.

Faster alternative in Oracle to SELECT COUNT(*) FROM sometable

You can create a fast refresh materialized view to store the count.

Example:

create table sometable (
id number(10) not null primary key
, name varchar2(100) not null);

create materialized view log on sometable with rowid including new values;

create materialized view sometable_count
refresh on commit
as
select count(*) count
from   sometable;

insert into sometable values (1,'Raymond');
insert into sometable values (2,'Hans');

commit;

select count from sometable_count; 

It will slow mutations on table sometable a bit but the counting will become a lot faster.

You don't have permission to access / on this server

For CentOS 8 your /etc/httpd/conf.d/awstats.conf file needs to look like this and you need to stick in your IP address and restart your httpd service unless you want to whole world to have access to it!

#
# Directives to add to your Apache conf file to allow use of AWStats as a CGI.
# Note that path "/usr/share/awstats/" must reflect your AWStats install path.
#
Alias /awstatsclasses "/usr/share/awstats/wwwroot/classes/"
Alias /awstatscss "/usr/share/awstats/wwwroot/css/"
Alias /awstatsicons "/usr/share/awstats/wwwroot/icon/"
ScriptAlias /awstats/ "/usr/share/awstats/wwwroot/cgi-bin/"
#
# This is to permit URL access to scripts/files in AWStats directory.
#
<Directory "/usr/share/awstats/wwwroot">
    Options None
    AllowOverride None
    <IfModule mod_authz_core.c>
        # Apache 2.4
        <RequireAny>
           Require <Your IP Address here>
        </RequireAny>
    </IfModule>
    <IfModule !mod_authz_core.c>
        # Apache 2.2
        Allow from <Your IP address here>
        Allow from ::1
    </IfModule>
</Directory>
# Additional Perl modules
<IfModule mod_env.c>
    SetEnv PERL5LIB /usr/share/awstats/lib:/usr/share/awstats/plugins
</IfModule>

Remember that if you IP address changes you need to update the file and restart the httpd server. BTW you can see your ip address as it looks from the outside by simply googling "my ip"

How to grant "grant create session" privilege?

You can grant system privileges with or without the admin option. The default being without admin option.

GRANT CREATE SESSION TO username

or with admin option:

GRANT CREATE SESSION TO username WITH ADMIN OPTION

The Grantee with the ADMIN OPTION can grant and revoke privileges to other users

Check if certain value is contained in a dataframe column in pandas

You can simply use this:

'07311954' in df.date.values which returns True or False


Here is the further explanation:

In pandas, using in check directly with DataFrame and Series (e.g. val in df or val in series ) will check whether the val is contained in the Index.

BUT you can still use in check for their values too (instead of Index)! Just using val in df.col_name.values or val in series.values. In this way, you are actually checking the val with a Numpy array.

And .isin(vals) is the other way around, it checks whether the DataFrame/Series values are in the vals. Here vals must be set or list-like. So this is not the natural way to go for the question.

Converting HTML to XML

I was successful using tidy command line utility. On linux I installed it quickly with apt-get install tidy. Then the command:

tidy -q -asxml --numeric-entities yes source.html >file.xml

gave an xml file, which I was able to process with xslt processor. However I needed to set up xhtml1 dtds correctly.

This is their homepage: html-tidy.org (and the legacy one: HTML Tidy)

How can I use a batch file to write to a text file?

  • You can use copy con to write a long text
  • Example:

    C:\COPY CON [drive:][path][File name]

    .... Content

    F6

    1 file(s) is copied

Eclipse Bug: Unhandled event loop exception No more handles

If you use DisplayFusion:

  1. Open Display Fusion settings page
  2. Click compatibility tab
  3. Add Eclipse or STS.exe application
  4. Check "Disable TitleBar Buttons (this application only), "Disable Application Hooks (this application only)", and "Use Process file icon on DisplayFusion taskbar, not window icon"

Reference: Display Fusion FIX

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

Find by key deep in a nested array

I found this page through googling for the similar functionalities. Based on the work provided by Zach and regularmike, I created another version which suits my needs.
BTW, teriffic work Zah and regularmike! I'll post the code here:

function findObjects(obj, targetProp, targetValue, finalResults) {

  function getObject(theObject) {
    let result = null;
    if (theObject instanceof Array) {
      for (let i = 0; i < theObject.length; i++) {
        getObject(theObject[i]);
      }
    }
    else {
      for (let prop in theObject) {
        if(theObject.hasOwnProperty(prop)){
          console.log(prop + ': ' + theObject[prop]);
          if (prop === targetProp) {
            console.log('--found id');
            if (theObject[prop] === targetValue) {
              console.log('----found porop', prop, ', ', theObject[prop]);
              finalResults.push(theObject);
            }
          }
          if (theObject[prop] instanceof Object || theObject[prop] instanceof Array){
            getObject(theObject[prop]);
          }
        }
      }
    }
  }

  getObject(obj);

}

What it does is it find any object inside of obj with property name and value matching to targetProp and targetValue and will push it to the finalResults array. And Here's the jsfiddle to play around: https://jsfiddle.net/alexQch/5u6q2ybc/

Finding the position of bottom of a div with jquery

var bottom = $('#bottom').position().top + $('#bottom').height();

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

IE.Document.getElementById("dgTime").getElementsByTagName("a")(0).Click

EDIT: to loop through the collection (items should appear in the same order as they are in the source document)

Dim links, link 

Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")

'For Each loop
For Each link in links
    link.Click
Next link

'For Next loop
Dim n, i
n = links.length
For i = 0 to n-1 Step 2
    links(i).click
Next I

An implementation of the fast Fourier transform (FFT) in C#

I see this is an old thread, but for what it's worth, here's a free (MIT License) 1-D power-of-2-length-only C# FFT implementation I wrote in 2010.

I haven't compared its performance to other C# FFT implementations. I wrote it mainly to compare the performance of Flash/ActionScript and Silverlight/C#. The latter is much faster, at least for number crunching.

/**
 * Performs an in-place complex FFT.
 *
 * Released under the MIT License
 *
 * Copyright (c) 2010 Gerald T. Beauregard
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */
public class FFT2
{
    // Element for linked list in which we store the
    // input/output data. We use a linked list because
    // for sequential access it's faster than array index.
    class FFTElement
    {
        public double re = 0.0;     // Real component
        public double im = 0.0;     // Imaginary component
        public FFTElement next;     // Next element in linked list
        public uint revTgt;         // Target position post bit-reversal
    }

    private uint m_logN = 0;        // log2 of FFT size
    private uint m_N = 0;           // FFT size
    private FFTElement[] m_X;       // Vector of linked list elements

    /**
     *
     */
    public FFT2()
    {
    }

    /**
     * Initialize class to perform FFT of specified size.
     *
     * @param   logN    Log2 of FFT length. e.g. for 512 pt FFT, logN = 9.
     */
    public void init(
        uint logN )
    {
        m_logN = logN;
        m_N = (uint)(1 << (int)m_logN);

        // Allocate elements for linked list of complex numbers.
        m_X = new FFTElement[m_N];
        for (uint k = 0; k < m_N; k++)
            m_X[k] = new FFTElement();

        // Set up "next" pointers.
        for (uint k = 0; k < m_N-1; k++)
            m_X[k].next = m_X[k+1];

        // Specify target for bit reversal re-ordering.
        for (uint k = 0; k < m_N; k++ )
            m_X[k].revTgt = BitReverse(k,logN);
    }

    /**
     * Performs in-place complex FFT.
     *
     * @param   xRe     Real part of input/output
     * @param   xIm     Imaginary part of input/output
     * @param   inverse If true, do an inverse FFT
     */
    public void run(
        double[] xRe,
        double[] xIm,
        bool inverse = false )
    {
        uint numFlies = m_N >> 1;   // Number of butterflies per sub-FFT
        uint span = m_N >> 1;       // Width of the butterfly
        uint spacing = m_N;         // Distance between start of sub-FFTs
        uint wIndexStep = 1;        // Increment for twiddle table index

        // Copy data into linked complex number objects
        // If it's an IFFT, we divide by N while we're at it
        FFTElement x = m_X[0];
        uint k = 0;
        double scale = inverse ? 1.0/m_N : 1.0;
        while (x != null)
        {
            x.re = scale*xRe[k];
            x.im = scale*xIm[k];
            x = x.next;
            k++;
        }

        // For each stage of the FFT
        for (uint stage = 0; stage < m_logN; stage++)
        {
            // Compute a multiplier factor for the "twiddle factors".
            // The twiddle factors are complex unit vectors spaced at
            // regular angular intervals. The angle by which the twiddle
            // factor advances depends on the FFT stage. In many FFT
            // implementations the twiddle factors are cached, but because
            // array lookup is relatively slow in C#, it's just
            // as fast to compute them on the fly.
            double wAngleInc = wIndexStep * 2.0*Math.PI/m_N;
            if (inverse == false)
                wAngleInc *= -1;
            double wMulRe = Math.Cos(wAngleInc);
            double wMulIm = Math.Sin(wAngleInc);

            for (uint start = 0; start < m_N; start += spacing)
            {
                FFTElement xTop = m_X[start];
                FFTElement xBot = m_X[start+span];

                double wRe = 1.0;
                double wIm = 0.0;

                // For each butterfly in this stage
                for (uint flyCount = 0; flyCount < numFlies; ++flyCount)
                {
                    // Get the top & bottom values
                    double xTopRe = xTop.re;
                    double xTopIm = xTop.im;
                    double xBotRe = xBot.re;
                    double xBotIm = xBot.im;

                    // Top branch of butterfly has addition
                    xTop.re = xTopRe + xBotRe;
                    xTop.im = xTopIm + xBotIm;

                    // Bottom branch of butterly has subtraction,
                    // followed by multiplication by twiddle factor
                    xBotRe = xTopRe - xBotRe;
                    xBotIm = xTopIm - xBotIm;
                    xBot.re = xBotRe*wRe - xBotIm*wIm;
                    xBot.im = xBotRe*wIm + xBotIm*wRe;

                    // Advance butterfly to next top & bottom positions
                    xTop = xTop.next;
                    xBot = xBot.next;

                    // Update the twiddle factor, via complex multiply
                    // by unit vector with the appropriate angle
                    // (wRe + j wIm) = (wRe + j wIm) x (wMulRe + j wMulIm)
                    double tRe = wRe;
                    wRe = wRe*wMulRe - wIm*wMulIm;
                    wIm = tRe*wMulIm + wIm*wMulRe;
                }
            }

            numFlies >>= 1;     // Divide by 2 by right shift
            span >>= 1;
            spacing >>= 1;
            wIndexStep <<= 1;   // Multiply by 2 by left shift
        }

        // The algorithm leaves the result in a scrambled order.
        // Unscramble while copying values from the complex
        // linked list elements back to the input/output vectors.
        x = m_X[0];
        while (x != null)
        {
            uint target = x.revTgt;
            xRe[target] = x.re;
            xIm[target] = x.im;
            x = x.next;
        }
    }

    /**
     * Do bit reversal of specified number of places of an int
     * For example, 1101 bit-reversed is 1011
     *
     * @param   x       Number to be bit-reverse.
     * @param   numBits Number of bits in the number.
     */
    private uint BitReverse(
        uint x,
        uint numBits)
    {
        uint y = 0;
        for (uint i = 0; i < numBits; i++)
        {
            y <<= 1;
            y |= x & 0x0001;
            x >>= 1;
        }
        return y;
    }

}

The best way to remove duplicate values from NSMutableArray in Objective-C?

Available in OS X v10.7 and later.

If you are worried about the order,right way to do

NSArray *no = [[NSOrderedSet orderedSetWithArray:originalArray]allObjects];

Here is the code of removing duplicates values from NSArray in Order.

printf() prints whole array

Incase of arrays, the base address (i.e. address of the array) is the address of the 1st element in the array. Also the array name acts as a pointer.

Consider a row of houses (each is an element in the array). To identify the row, you only need the 1st house address.You know each house is followed by the next (sequential).Getting the address of the 1st house, will also give you the address of the row.

Incase of string literals(character arrays defined at declaration), they are automatically appended by \0.

printf prints using the format specifier and the address provided. Since, you use %s it prints from the 1st address (incrementing the pointer using arithmetic) until '\0'

Swift alert view with OK and Cancel: which button tapped?

You may want to consider using SCLAlertView, alternative for UIAlertView or UIAlertController.

UIAlertController only works on iOS 8.x or above, SCLAlertView is a good option to support older version.

github to see the details

example:

let alertView = SCLAlertView()
alertView.addButton("First Button", target:self, selector:Selector("firstButton"))
alertView.addButton("Second Button") {
    print("Second button tapped")
}
alertView.showSuccess("Button View", subTitle: "This alert view has buttons")

Why does Math.Round(2.5) return 2 instead of 3?

This is ugly as all hell, but always produces correct arithmetic rounding.

public double ArithRound(double number,int places){

  string numberFormat = "###.";

  numberFormat = numberFormat.PadRight(numberFormat.Length + places, '#');

  return double.Parse(number.ToString(numberFormat));

}

How to get height of Keyboard?

Swift 4 .

Simplest Method

override func viewDidLoad() {
      super.viewDidLoad()
      NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
}

func keyboardWillShow(notification: NSNotification) {  

      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
             let keyboardHeight : Int = Int(keyboardSize.height)
             print("keyboardHeight",keyboardHeight) 
      }

}

How can I copy a file from a remote server to using Putty in Windows?

It worked using PSCP. Instructions:

  1. Download PSCP.EXE from Putty download page
  2. Open command prompt and type set PATH=<path to the pscp.exe file>
  3. In command prompt point to the location of the pscp.exe using cd command
  4. Type pscp
  5. use the following command to copy file form remote server to the local system

    pscp [options] [user@]host:source target
    

So to copy the file /etc/hosts from the server example.com as user fred to the file c:\temp\example-hosts.txt, you would type:

pscp [email protected]:/etc/hosts c:\temp\example-hosts.txt

How do I split an int into its digits?

A simple answer to this question can be:

  1. Read A Number "n" From The User.
  2. Using While Loop Make Sure Its Not Zero.
  3. Take modulus 10 Of The Number "n"..This Will Give You Its Last Digit.
  4. Then Divide The Number "n" By 10..This Removes The Last Digit of Number "n" since in int decimal part is omitted.
  5. Display Out The Number.

I Think It Will Help. I Used Simple Code Like:

#include <iostream>
using namespace std;
int main()
{int n,r;

    cout<<"Enter Your Number:";
    cin>>n;


    while(n!=0)
    {
               r=n%10;
               n=n/10;

               cout<<r;
    }
    cout<<endl;

    system("PAUSE");
    return 0;
}

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

Check Ayende post on the topic: Combating the Select N + 1 Problem In NHibernate.

Basically, when using an ORM like NHibernate or EntityFramework, if you have a one-to-many (master-detail) relationship, and want to list all the details per each master record, you have to make N + 1 query calls to the database, "N" being the number of master records: 1 query to get all the master records, and N queries, one per master record, to get all the details per master record.

More database query calls ? more latency time ? decreased application/database performance.

However, ORMs have options to avoid this problem, mainly using JOINs.

C# Wait until condition is true

you can use SpinUntil which is buildin in the .net-framework. Please note: This method causes high cpu-workload.

Verify a certificate chain using openssl verify

The problem is, that openssl -verify does not do the job.

As Priyadi mentioned, openssl -verify stops at the first self signed certificate, hence you do not really verify the chain, as often the intermediate cert is self-signed.

I assume that you want to be 101% sure, that the certificate files are correct before you try to install them in the productive web service. This recipe here performs exactly this pre-flight-check.

Please note that the answer of Peter is correct, however the output of openssl -verify is no clue that everything really works afterwards. Yes, it might find some problems, but quite not all.

Here is a script which does the job to verify a certificate chain before you install it into Apache. Perhaps this can be enhanced with some of the more mystic OpenSSL magic, but I am no OpenSSL guru and following works:

#!/bin/bash
# This Works is placed under the terms of the Copyright Less License,
# see file COPYRIGHT.CLL.  USE AT OWN RISK, ABSOLUTELY NO WARRANTY. 
#
# COPYRIGHT.CLL can be found at http://permalink.de/tino/cll
# (CLL is CC0 as long as not covered by any Copyright)

OOPS() { echo "OOPS: $*" >&2; exit 23; }

PID=
kick() { [ -n "$PID" ] && kill "$PID" && sleep .2; PID=; }
trap 'kick' 0

serve()
{
kick
PID=
openssl s_server -key "$KEY" -cert "$CRT" "$@" -www &
PID=$!
sleep .5    # give it time to startup
}

check()
{
while read -r line
do
    case "$line" in
    'Verify return code: 0 (ok)')   return 0;;
    'Verify return code: '*)    return 1;;
#   *)  echo "::: $line :::";;
    esac
done < <(echo | openssl s_client -verify 8 -CApath /etc/ssl/certs/)
OOPS "Something failed, verification output not found!"
return 2
}

ARG="${1%.}"
KEY="$ARG.key"
CRT="$ARG.crt"
BND="$ARG.bundle"

for a in "$KEY" "$CRT" "$BND"
do
    [ -s "$a" ] || OOPS "missing $a"
done

serve
check && echo "!!! =========> CA-Bundle is not needed! <========"
echo
serve -CAfile "$BND"
check
ret=$?
kick

echo
case $ret in
0)  echo "EVERYTHING OK"
    echo "SSLCertificateKeyFile $KEY"
    echo "SSLCertificateFile    $CRT"
    echo "SSLCACertificateFile  $BND"
    ;;
*)  echo "!!! =========> something is wrong, verification failed! <======== ($ret)";;
esac

exit $ret

Note that the output after EVERYTHING OK is the Apache setting, because people using NginX or haproxy usually can read and understand this perfectly, too ;)

There is a GitHub Gist of this which might have some updates

Prerequisites of this script:

  • You have the trusted CA root data in /etc/ssl/certs as usual for example on Ubuntu
  • Create a directory DIR where you store 3 files:
    • DIR/certificate.crt which contains the certificate
    • DIR/certificate.key which contains the secret key for your webservice (without passphrase)
    • DIR/certificate.bundle which contains the CA-Bundle. On how to prepare the bundle, see below.
  • Now run the script: ./check DIR/certificate (this assumes that the script is named check in the current directory)
  • There is a very unlikely case that the script outputs CA-Bundle is not needed. This means, that you (read: /etc/ssl/certs/) already trusts the signing certificate. But this is highly unlikely in the WWW.
  • For this test port 4433 must be unused on your workstation. And better only run this in a secure environment, as it opens port 4433 shortly to the public, which might see foreign connects in a hostile environment.

How to create the certificate.bundle file?

In the WWW the trust chain usually looks like this:

  • trusted certificate from /etc/ssl/certs
  • unknown intermediate certificate(s), possibly cross signed by another CA
  • your certificate (certificate.crt)

Now, the evaluation takes place from bottom to top, this means, first, your certificate is read, then the unknown intermediate certificate is needed, then perhaps the cross-signing-certificate and then /etc/ssl/certs is consulted to find the proper trusted certificate.

The ca-bundle must be made up in excactly the right processing order, this means, the first needed certificate (the intermediate certificate which signs your certificate) comes first in the bundle. Then the cross-signing-cert is needed.

Usually your CA (the authority who signed your certificate) will provide such a proper ca-bundle-file already. If not, you need to pick all the needed intermediate certificates and cat them together into a single file (on Unix). On Windows you can just open a text editor (like notepad.exe) and paste the certificates into the file, the first needed on top and following the others.

There is another thing. The files need to be in PEM format. Some CAs issue DER (a binary) format. PEM is easy to spot: It is ASCII readable. For mor on how to convert something into PEM, see How to convert .crt to .pem and follow the yellow brick road.

Example:

You have:

  • intermediate2.crt the intermediate cert which signed your certificate.crt
  • intermediate1.crt another intermediate cert, which singed intermediate2.crt
  • crossigned.crt which is a cross signing certificate from another CA, which signed intermediate1.crt
  • crossintermediate.crt which is another intermediate from the other CA which signed crossigned.crt (you probably will never ever see such a thing)

Then the proper cat would look like this:

cat intermediate2.crt intermediate1.crt crossigned.crt crossintermediate.crt > certificate.bundle

And how can you find out which files are needed or not and in which sequence?

Well, experiment, until the check tells you everything is OK. It is like a computer puzzle game to solve the riddle. Every. Single. Time. Even for pros. But you will get better each time you need to do this. So you are definitively not alone with all that pain. It's SSL, ya' know? SSL is probably one of the worst designs I ever saw in over 30 years of professional system administration. Ever wondered why crypto has not become mainstream in the last 30 years? That's why. 'nuff said.

What is the difference between an interface and abstract class?

I am 10 yrs late to the party but would like to attempt any way. Wrote a post about the same on medium few days back. Thought of posting it here.

tl;dr; When you see “Is A” relationship use inheritance/abstract class. when you see “has a” relationship create member variables. When you see “relies on external provider” implement (not inherit) an interface.

Interview Question: What is the difference between an interface and an abstract class? And how do you decide when to use what? I mostly get one or all of the below answers: Answer 1: You cannot create an object of abstract class and interfaces.

ZK (That’s my initials): You cannot create an object of either. So this is not a difference. This is a similarity between an interface and an abstract class. Counter Question: Why can’t you create an object of abstract class or interface?

Answer 2: Abstract classes can have a function body as partial/default implementation.

ZK: Counter Question: So if I change it to a pure abstract class, marking all the virtual functions as abstract and provide no default implementation for any virtual function. Would that make abstract classes and interfaces the same? And could they be used interchangeably after that?

Answer 3: Interfaces allow multi-inheritance and abstract classes don’t.

ZK: Counter Question: Do you really inherit from an interface? or do you just implement an interface and, inherit from an abstract class? What’s the difference between implementing and inheriting? These counter questions throw candidates off and make most scratch their heads or just pass to the next question. That makes me think people need help with these basic building blocks of Object-Oriented Programming. The answer to the original question and all the counter questions is found in the English language and the UML. You must know at least below to understand these two constructs better.

Common Noun: A common noun is a name given “in common” to things of the same class or kind. For e.g. fruits, animals, city, car etc.

Proper Noun: A proper noun is the name of an object, place or thing. Apple, Cat, New York, Honda Accord etc.

Car is a Common Noun. And Honda Accord is a Proper Noun, and probably a Composit Proper noun, a proper noun made using two nouns.

Coming to the UML Part. You should be familiar with below relationships:

  • Is A
  • Has A
  • Uses

Let’s consider the below two sentences. - HondaAccord Is A Car? - HondaAccord Has A Car?

Which one sounds correct? Plain English and comprehension. HondaAccord and Cars share an “Is A” relationship. Honda accord doesn’t have a car in it. It “is a” car. Honda Accord “has a” music player in it.

When two entities share the “Is A” relationship it’s a better candidate for inheritance. And Has a relationship is a better candidate for creating member variables. With this established our code looks like this:

abstract class Car
{
   string color;
   int speed;
}
class HondaAccord : Car
{
   MusicPlayer musicPlayer;
}

Now Honda doesn't manufacture music players. Or at least it’s not their main business.

So they reach out to other companies and sign a contract. If you receive power here and the output signal on these two wires it’ll play just fine on these speakers.

This makes Music Player a perfect candidate for an interface. You don’t care who provides support for it as long as the connections work just fine.

You can replace the MusicPlayer of LG with Sony or the other way. And it won’t change a thing in Honda Accord.

Why can’t you create an object of abstract classes?

Because you can’t walk into a showroom and say give me a car. You’ll have to provide a proper noun. What car? Probably a honda accord. And that’s when a sales agent could get you something.

Why can’t you create an object of an interface? Because you can’t walk into a showroom and say give me a contract of music player. It won’t help. Interfaces sit between consumers and providers just to facilitate an agreement. What will you do with a copy of the agreement? It won’t play music.

Why do interfaces allow multiple inheritance?

Interfaces are not inherited. Interfaces are implemented. The interface is a candidate for interaction with the external world. Honda Accord has an interface for refueling. It has interfaces for inflating tires. And the same hose that is used to inflate a football. So the new code will look like below:

abstract class Car
{
    string color;
    int speed;
}
class HondaAccord : Car, IInflateAir, IRefueling
{
    MusicPlayer musicPlayer;
}

And the English will read like this “Honda Accord is a Car that supports inflating tire and refueling”.

android splash screen sizes for ldpi,mdpi, hdpi, xhdpi displays ? - eg : 1024X768 pixels for ldpi

For Android Mobile Devices

LDPI- icon-36x36, splash-426x320 (now with correct values)


MDPI- icon-48x48, splash-470x320


HDPI- icon 72x72, splash- 640x480


XHDPI- icon-96x96, splash- 960x720


XXHDPI- icon- 144x144

All in pixels.

For Android Tablet Devices

LDPI:
    Portrait: 200x320px
    Landscape: 320x200px
MDPI:
    Portrait: 320x480px
    Landscape: 480x320px
HDPI:
    Portrait: 480x800px
    Landscape: 800x480px
XHDPI:
    Portrait: 720px1280px
    Landscape: 1280x720px

ruby LoadError: cannot load such file

I created my own Gem, but I did it in a directory that is not in my load path:

$ pwd
/Users/myuser/projects
$ gem build my_gem/my_gem.gemspec

Then I ran irb and tried to load the Gem:

> require 'my_gem'
LoadError: cannot load such file -- my_gem

I used the global variable $: to inspect my load path and I realized I am using RVM. And rvm has specific directories in my load path $:. None of those directories included my ~/projects directory where I created the custom gem.

So one solution is to modify the load path itself:

$: << "/Users/myuser/projects/my_gem/lib"

Note that the lib directory is in the path, which holds the my_gem.rb file which will be required in irb:

> require 'my_gem'
 => true 

Now if you want to install the gem in RVM path, then you would need to run:

$ gem install my_gem

But it will need to be in a repository like rubygems.org.

$ gem push my_gem-0.0.0.gem
Pushing gem to RubyGems.org...
Successfully registered gem my_gem

Get image dimensions

Using getimagesize function, we can also get these properties of that specific image-

<?php

list($width, $height, $type, $attr) = getimagesize("image_name.jpg");

echo "Width: " .$width. "<br />";
echo "Height: " .$height. "<br />";
echo "Type: " .$type. "<br />";
echo "Attribute: " .$attr. "<br />";

//Using array
$arr = array('h' => $height, 'w' => $width, 't' => $type, 'a' => $attr);
?>


Result like this -

Width: 200
Height: 100
Type: 2
Attribute: width='200' height='100'


Type of image consider like -

1 = GIF
2 = JPG
3 = PNG
4 = SWF
5 = PSD
6 = BMP
7 = TIFF(intel byte order)
8 = TIFF(motorola byte order)
9 = JPC
10 = JP2
11 = JPX
12 = JB2
13 = SWC
14 = IFF
15 = WBMP
16 = XBM

What's the difference between emulation and simulation?

Please forgive me if I'm wrong. And I have to admit upfront that I haven't done any research on these 2 terms. Anyway...

Emulation is to mimic something with detailed known results, whatever the internal behaviors actually are. We only try to get things done and don't care much about what goes on inside.

Simulation, on the other hand, is to mimic something with some known behaviors to study something not being known yet.

my 2cents

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

When a assembly' s AssemblyVersion is changed, If it has strong name, the referencing assemblies need to be recompiled, otherwise the assembly does not load! If it does not have strong name, if not explicitly added to project file, it will not be copied to output directory when build so you may miss depending assemblies, especially after cleaning the output directory.

How to run a Command Prompt command with Visual Basic code?

Here is an example:

Process.Start("CMD", "/C Pause")


/C  Carries out the command specified by string and then terminates
/K  Carries out the command specified by string but remains

And here is a extended function: (Notice the comment-lines using CMD commands.)

#Region " Run Process Function "

' [ Run Process Function ]
'
' // By Elektro H@cker
'
' Examples :
'
' MsgBox(Run_Process("Process.exe")) 
' MsgBox(Run_Process("Process.exe", "Arguments"))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B", True))
' MsgBox(Run_Process("CMD.exe", "/C @Echo OFF & For /L %X in (0,1,50000) Do (Echo %X)", False, False))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B /S %SYSTEMDRIVE%\*", , False, 500))
' If Run_Process("CMD.exe", "/C Dir /B", True).Contains("File.txt") Then MsgBox("File found")

Private Function Run_Process(ByVal Process_Name As String, _
                             Optional Process_Arguments As String = Nothing, _
                             Optional Read_Output As Boolean = False, _
                             Optional Process_Hide As Boolean = False, _
                             Optional Process_TimeOut As Integer = 999999999)

    ' Returns True if "Read_Output" argument is False and Process was finished OK
    ' Returns False if ExitCode is not "0"
    ' Returns Nothing if process can't be found or can't be started
    ' Returns "ErrorOutput" or "StandardOutput" (In that priority) if Read_Output argument is set to True.

    Try

        Dim My_Process As New Process()
        Dim My_Process_Info As New ProcessStartInfo()

        My_Process_Info.FileName = Process_Name ' Process filename
        My_Process_Info.Arguments = Process_Arguments ' Process arguments
        My_Process_Info.CreateNoWindow = Process_Hide ' Show or hide the process Window
        My_Process_Info.UseShellExecute = False ' Don't use system shell to execute the process
        My_Process_Info.RedirectStandardOutput = Read_Output '  Redirect (1) Output
        My_Process_Info.RedirectStandardError = Read_Output ' Redirect non (1) Output
        My_Process.EnableRaisingEvents = True ' Raise events
        My_Process.StartInfo = My_Process_Info
        My_Process.Start() ' Run the process NOW

        My_Process.WaitForExit(Process_TimeOut) ' Wait X ms to kill the process (Default value is 999999999 ms which is 277 Hours)

        Dim ERRORLEVEL = My_Process.ExitCode ' Stores the ExitCode of the process
        If Not ERRORLEVEL = 0 Then Return False ' Returns the Exitcode if is not 0

        If Read_Output = True Then
            Dim Process_ErrorOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Error Output (If any)
            Dim Process_StandardOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Standard Output (If any)
            ' Return output by priority
            If Process_ErrorOutput IsNot Nothing Then Return Process_ErrorOutput ' Returns the ErrorOutput (if any)
            If Process_StandardOutput IsNot Nothing Then Return Process_StandardOutput ' Returns the StandardOutput (if any)
        End If

    Catch ex As Exception
        'MsgBox(ex.Message)
        Return Nothing ' Returns nothing if the process can't be found or started.
    End Try

    Return True ' Returns True if Read_Output argument is set to False and the process finished without errors.

End Function

#End Region

TypeError: $(...).on is not a function

I tried the solution of Oskar (and many others) but for me it finaly only worked with:

jQuery(function($){
   // Your jQuery code here, using the $
});

See: https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/

SQL Server Management Studio missing

If you have a copy of backup of SQL Server setup then you could add features (Management Tools Basic/Complete) as you requested.

Please use the below steps in Windows machine:

  1. Go to Control Panel -> Programs -> Program and Features -> Select your current version of Microsoft SQL Server
  2. Right Click, select Change/Uninstall
  3. Click Add features
  4. Select the backup copy folder
  5. Do the steps what you done for SQL Server installation until features selection
  6. Now select the features Management Tools Basic/Complete or both
  7. And go ahead with process for complete installation.
  8. Now you should get, SQL Server Management Studio and you can browse your databases.

How to get base url with jquery or javascript?

Here's a short one:

_x000D_
_x000D_
const base = new URL('/', location.href).href;

console.log(base);
_x000D_
_x000D_
_x000D_

Assign an initial value to radio button as checked

Note that if you have two radio button with same "name" attribute and they have "required" attribute, then adding "checked" attribute to them won't make them checked.

Example: This makes both radio button remain unchecked.

<input type="radio" name="gender" value="male" required <?php echo "checked"; ?>/>
<input type="radio" name="gender" value="female" required />

This will makes the "male" radio button checked.

<input type="radio" name="gender" value="male" <?php echo "checked"; ?>/>
<input type="radio" name="gender" value="female" />

Spark SQL: apply aggregate functions to a list of columns

There are multiple ways of applying aggregate functions to multiple columns.

GroupedData class provides a number of methods for the most common functions, including count, max, min, mean and sum, which can be used directly as follows:

  • Python:

    df = sqlContext.createDataFrame(
        [(1.0, 0.3, 1.0), (1.0, 0.5, 0.0), (-1.0, 0.6, 0.5), (-1.0, 5.6, 0.2)],
        ("col1", "col2", "col3"))
    
    df.groupBy("col1").sum()
    
    ## +----+---------+-----------------+---------+
    ## |col1|sum(col1)|        sum(col2)|sum(col3)|
    ## +----+---------+-----------------+---------+
    ## | 1.0|      2.0|              0.8|      1.0|
    ## |-1.0|     -2.0|6.199999999999999|      0.7|
    ## +----+---------+-----------------+---------+
    
  • Scala

    val df = sc.parallelize(Seq(
      (1.0, 0.3, 1.0), (1.0, 0.5, 0.0),
      (-1.0, 0.6, 0.5), (-1.0, 5.6, 0.2))
    ).toDF("col1", "col2", "col3")
    
    df.groupBy($"col1").min().show
    
    // +----+---------+---------+---------+
    // |col1|min(col1)|min(col2)|min(col3)|
    // +----+---------+---------+---------+
    // | 1.0|      1.0|      0.3|      0.0|
    // |-1.0|     -1.0|      0.6|      0.2|
    // +----+---------+---------+---------+
    

Optionally you can pass a list of columns which should be aggregated

df.groupBy("col1").sum("col2", "col3")

You can also pass dictionary / map with columns a the keys and functions as the values:

  • Python

    exprs = {x: "sum" for x in df.columns}
    df.groupBy("col1").agg(exprs).show()
    
    ## +----+---------+
    ## |col1|avg(col3)|
    ## +----+---------+
    ## | 1.0|      0.5|
    ## |-1.0|     0.35|
    ## +----+---------+
    
  • Scala

    val exprs = df.columns.map((_ -> "mean")).toMap
    df.groupBy($"col1").agg(exprs).show()
    
    // +----+---------+------------------+---------+
    // |col1|avg(col1)|         avg(col2)|avg(col3)|
    // +----+---------+------------------+---------+
    // | 1.0|      1.0|               0.4|      0.5|
    // |-1.0|     -1.0|3.0999999999999996|     0.35|
    // +----+---------+------------------+---------+
    

Finally you can use varargs:

  • Python

    from pyspark.sql.functions import min
    
    exprs = [min(x) for x in df.columns]
    df.groupBy("col1").agg(*exprs).show()
    
  • Scala

    import org.apache.spark.sql.functions.sum
    
    val exprs = df.columns.map(sum(_))
    df.groupBy($"col1").agg(exprs.head, exprs.tail: _*)
    

There are some other way to achieve a similar effect but these should more than enough most of the time.

See also:

How add spaces between Slick carousel item

The slick-slide has inner wrapping div which you can use to create spacing between slides without breaking the design:

.slick-list {margin: 0 -5px;}
.slick-slide>div {padding: 0 5px;}

Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

You can use code like:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>window.jQuery || document.write('<script type="text/javascript" src="./scripts/jquery.min.js">\x3C/script>')</script>

But also there are libraries you can use to setup several possible fallbacks for your scripts and optimize the loading process:

  • basket.js
  • RequireJS
  • yepnope

Examples:

basket.js I think the best variant for now. Will cach your script in the localStorage, that will speed up next loadings. The simplest call:

basket.require({ url: '/path/to/jquery.js' });

This will return a promise and you can do next call on error, or load dependencies on success:

basket
    .require({ url: '/path/to/jquery.js' })
    .then(function () {
        // Success
    }, function (error) {
        // There was an error fetching the script
        // Try to load jquery from the next cdn
    });

RequireJS

requirejs.config({
    enforceDefine: true,
    paths: {
        jquery: [
            '//ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min',
            //If the CDN location fails, load from this location
            'js/jquery-2.0.0.min'
        ]
    }
});

//Later
require(['jquery'], function ($) {
});

yepnope

yepnope([{
  load: 'http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min.js',
  complete: function () {
    if (!window.jQuery) {
      yepnope('js/jquery-2.0.0.min.js');
    }
  }
}]);

How to write a confusion matrix in Python?

A numpy-only solution for any number of classes that doesn't require looping:

import numpy as np

classes = 3
true = np.random.randint(0, classes, 50)
pred = np.random.randint(0, classes, 50)

np.bincount(true * classes + pred).reshape((classes, classes))

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

how to draw a rectangle in HTML or CSS?

Use <div id="rectangle" style="width:number px; height:number px; background-color:blue"></div>

This will create a blue rectangle.

Java Loop every minute

You can use Timer

Timer timer = new Timer();

timer.schedule( new TimerTask() {
    public void run() {
       // do your work 
    }
 }, 0, 60*1000);

When the times comes

  timer.cancel();

To shut it down.

In MS DOS copying several files to one file

copy /b file1 + file2 + file3 newfile

Each source file must be added to the copy command with a +, and the last filename listed will be where the concatenated data is copied to.

How to link home brew python version and set it as default

I use these commands to solve it.

mkdir /usr/local/lib
mkdir /usr/local/lib/pkgconfig
brew link python

Type of expression is ambiguous without more context Swift

Not an answer to this question, but as I came here looking for the error others might find this also useful:

For me, I got this Swift error when I tried to use the for (index, object) loop on an array without adding the .enumerated() part ...

How to make type="number" to positive numbers only

_x000D_
_x000D_
<input type="number" min="1" step="1">
_x000D_
_x000D_
_x000D_

Function stoi not declared

Are you running C++ 11? stoi was added in C++ 11, if you're running on an older version use atoi()

MSOnline can't be imported on PowerShell (Connect-MsolService error)

The solution with copying 32-bit libs over to 64-bit did not work for me. What worked was unchecking Target Platform Prefer 32-bit check mark in project properties.

How to copy commits from one branch to another?

Or if You are little less on the evangelist's side You can do a little ugly way I'm using. In deploy_template there are commits I want to copy on my master as branch deploy

git branch deploy deploy_template
git checkout deploy
git rebase master

This will create new branch deploy (I use -f to overwrite existing deploy branch) on deploy_template, then rebase this new branch onto master, leaving deploy_template untouched.

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

I follow all recommendations and all requirements. I install my self signed root CA on my iPhone. I make it trusted. I put certificate signed with this root CA on my local development server and I still get certificated error on safari iOS. Working on all other platforms.

no module named urllib.parse (How should I install it?)

For Python 3, use the following:

import urllib.parse

How can I stop redis-server?

In my case it was:

/etc/init.d/redismaster stop
/etc/init.d/redismaster start

To find out what is your service name, you can run:

sudo updatedb
locate redis

And it will show you every Redis files in your system.

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

For date:

#!/usr/bin/ruby -w

date = Time.new
#set 'date' equal to the current date/time. 

date = date.day.to_s + "/" + date.month.to_s + "/" + date.year.to_s
#Without this it will output 2015-01-10 11:33:05 +0000; this formats it to display DD/MM/YYYY

puts date
#output the date

The above will display, for example, 10/01/15

And for time

time = Time.new
#set 'time' equal to the current time. 

time = time.hour.to_s + ":" + time.min.to_s
#Without this it will output 2015-01-10 11:33:05 +0000; this formats it to display hour and           minute

puts time
#output the time

The above will display, for example, 11:33

Then to put it together, add to the end:

puts date + " " + time

Rounding a number to the nearest 5 or 10 or X

It's simple math. Given a number X and a rounding factor N, the formula would be:

round(X / N)*N

.NET / C# - Convert char[] to string

char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = new string(chars);

Why can't Python parse this JSON data?

There are two types in this parsing.

  1. Parsing data from a file from a system path
  2. Parsing JSON from remote URL.

From a file, you can use the following

import json
json = json.loads(open('/path/to/file.json').read())
value = json['key']
print json['value']

This arcticle explains the full parsing and getting values using two scenarios.Parsing JSON using Python

How to reset the state of a Redux store?

Another option is to:

store.dispatch({type: '@@redux/INIT'})

'@@redux/INIT' is the action type that redux dispatches automatically when you createStore, so assuming your reducers all have a default already, this would get caught by those and start your state off fresh. It might be considered a private implementation detail of redux, though, so buyer beware...

Including all the jars in a directory within the Java classpath

To whom it may concern,

I found this strange behaviour on Windows under an MSYS/MinGW shell.

Works:

$ javac -cp '.;c:\Programs\COMSOL44\plugins\*' Reclaim.java

Doesn't work:

$ javac -cp 'c:\Programs\COMSOL44\plugins\*' Reclaim.java
javac: invalid flag: c:\Programs\COMSOL44\plugins\com.comsol.aco_1.0.0.jar
Usage: javac <options> <source files>
use -help for a list of possible options

I am quite sure that the wildcard is not expanded by the shell, because e.g.

$ echo './*'
./*

(Tried it with another program too, rather than the built-in echo, with the same result.)

I believe that it's javac which is trying to expand it, and it behaves differently whether there is a semicolon in the argument or not. First, it may be trying to expand all arguments that look like paths. And only then it would parse them, with -cp taking only the following token. (Note that com.comsol.aco_1.0.0.jar is the second JAR in that directory.) That's all a guess.

This is

$ javac -version
javac 1.7.0

Oracle ORA-12154: TNS: Could not resolve service name Error?

Hours of problems SOLVED. I had installed the Beta Entity Framework for Oracle and in in visual studio 2010 MVC 3 project I was referencing under the tab .NET the Oracle.DataAccess ... This kept giving me the "Oracle ORA-12154: TNS: Could not..." error. I finally just browsed to the previous Oracle install under c:\Oracle\product.... using the old 10.2.0.100 version of the dll. Finally it works now. Hope it helps someone else.

List and kill at jobs on UNIX

To delete a job which has not yet run, you need the atrm command. You can use atq command to get its number in the at list.

To kill a job which has already started to run, you'll need to grep for it using:

ps -eaf | grep <command name>

and then use kill to stop it.

A quicker way to do this on most systems is:

pkill <command name>

Column calculated from another column?

Generated Column is one of the good approach for MySql version which is 5.7.6 and above.

There are two kinds of Generated Columns:

  • Virtual (default) - column will be calculated on the fly when a record is read from a table
  • Stored - column will be calculated when a new record is written/updated in the table

Both types can have NOT NULL restrictions, but only a stored Generated Column can be a part of an index.

For current case, we are going to use stored generated column. To implement I have considered that both of the values required for calculation are present in table

CREATE TABLE order_details (price DOUBLE, quantity INT, amount DOUBLE AS (price * quantity));

INSERT INTO order_details (price, quantity) VALUES(100,1),(300,4),(60,8);

amount will automatically pop up in table and you can access it directly, also please note that whenever you will update any of the columns, amount will also get updated.

How to run vi on docker container?

The command to run depends on what base image you are using.

For Alpine, vi is installed as part of the base OS. Installing vim would be:

apk -U add vim

For Debian and Ubuntu:

apt-get update && apt-get install -y vim

For CentOS, vi is usually installed with the base OS. For vim:

yum install -y vim

This should only be done in early development. Once you get a working container, the changes to files should be made to your image or configs stored outside of your container. Update your Dockerfile and other files it uses to build a new image. This certainly shouldn't be done in production since changes inside the container are by design ephemeral and will be lost when the container is replaced.

Test if a string contains a word in PHP?

_x000D_
_x000D_
use _x000D_
_x000D_
if(stripos($str,'job')){_x000D_
   // do your work_x000D_
}
_x000D_
_x000D_
_x000D_

How to limit text width

Try

<div style="max-width:200px; word-wrap:break-word;">Texttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt</div>

Where does Chrome store cookies?

Since the expiration time is zero (the third argument, the first false) the cookie is a session cookie, which will expire when the current session ends. (See the setcookie reference).

Therefore it doesn't need to be saved.

How to use Apple's new .p8 certificate for APNs in firebase console

When you upload your p8 file in Firebase, in the box that reads App ID Prefix(required) , you should enter your team ID. You can get it from https://developer.apple.com/account/#/membership and copy/paste the Team ID as shown below.

enter image description here

error: ‘NULL’ was not declared in this scope

You can declare the macro NULL. Add that after your #includes:

#define NULL 0

or

#ifndef NULL
#define NULL 0
#endif

No ";" at the end of the instructions...

Determine the size of an InputStream

you can get the size of InputStream using getBytes(inputStream) of Utils.java check this following link

Get Bytes from Inputstream

Possible to access MVC ViewBag object from Javascript file?

Not in a JavaScript file, no.
Your JavaScript file could contains a class and you could instantiate a new instance of that class in the View, then you can pass ViewBag values in the class constructor.

Or if it's not a class, your only other alternative, is to use data attributes in your HTML elements, assign them to properties in your View and retrieve them in the JS file.

Assuming you had this input:

<input type="text" id="myInput" data-myValue="@ViewBag.MyValue" />

Then in your JS file you could get it by using:

var myVal = $("#myInput").data("myValue");

Unsupported major.minor version 52.0

The smart way to fix that problem is to compile using the latest SDK and use the cross compilation options when compiling. To use the options completely correctly requires the rt.jar of a JRE (not JDK) of the target version.

Given the nature of that applet, it looks like it could be compiled for use with Java 1.1.

Where are SQL Server connection attempts logged?

You can enable connection logging. For SQL Server 2008, you can enable Login Auditing. In SQL Server Management Studio, open SQL Server Properties > Security > Login Auditing select "Both failed and successful logins".

Make sure to restart the SQL Server service.

Once you've done that, connection attempts should be logged into SQL's error log. The physical logs location can be determined here.

Authenticate with GitHub using a token

The password that you use to login to github.com portal does not work in VS Code CLI/Shell. You should copy PAT Token from URL https://github.com/settings/tokens by generating new token and paste that string in CLI as password.

How to format date string in java?

If you are looking for a solution to your particular case, it would be:

Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse("2012-05-20T09:00:00.000Z");
String formattedDate = new SimpleDateFormat("dd/MM/yyyy, Ka").format(date);

how to change namespace of entire project?

Just right click the solution, go to properties, change "default namespace" under 'Application' section.

enter image description here

How to add native library to "java.library.path" with Eclipse launch (instead of overriding it)

The native library file name has to correspond to the Jar file name. This is very very important. Please make sure that jar name and dll name are same. Also,please see the post from Fabian Steeg My download for jawin was containing different names for dll and jar. It was jawin.jar and jawind.dll, note extra 'd' in dll file name. I simply renamed it to jawin.dll and set it as a native library in eclipse as mentioned in post "http://www.eclipsezone.com/eclipse/forums/t49342.html"

iPhone UITextField - Change placeholder text color

For iOS 6.0 +

[textfield setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];

Hope it helps.

Note: Apple may reject (0.01% chances) your app as we are accessing private API. I am using this in all my projects since two years, but Apple didn't ask for this.

HtmlEncode from Class Library

Try this

System.Net.WebUtility.HtmlDecode(string);
System.Net.WebUtility.HtmlEncode(string);

Execute a shell function with timeout

Putting my comment to Tiago Lopo's answer into more readable form:

I think it's more readable to impose a timeout on the most recent subshell, this way we don't need to eval a string and the whole script can be highlighted as shell by your favourite editor. I simply put the commands after the subshell with eval has spawned into a shell-function (tested with zsh, but should work with bash):

timeout_child () {
    trap -- "" SIGTERM
    child=$!
    timeout=$1
    (
            sleep $timeout
            kill $child
    ) &
    wait $child
}

Example usage:

( while true; do echo -n .; sleep 0.1; done) & timeout_child 2

And this way it also works with a shell function (if it runs in the background):

 print_dots () {
     while true
     do
         sleep 0.1
         echo -n .
     done
 }


 > print_dots & timeout_child 2
 [1] 21725
 [3] 21727
 ...................[1]    21725 terminated  print_dots
 [3]  + 21727 done       ( sleep $timeout; kill $child; )

How to make a pure css based dropdown menu?

Tested in IE7 - 9 and Firefox: http://jsfiddle.net/WCaKg/. Markup:

<ul>
    <li>&lt;li&gt;</li>

    <li>&lt;li&gt;</li>

    <li>&lt;li&gt;

        <ul>
            <li>&lt;li&gt;</li>

            <li>&lt;li&gt;</li>

            <li>&lt;li&gt;</li>

            <li>&lt;li&gt;</li>
        </ul>
    </li>

    <li>&lt;li&gt;</li>

    <li>&lt;li&gt;</li>

    <li>&lt;li&gt;</li>
</ul>

CSS:

* {
  margin: 0;
  padding: 0;
}

body {
  font: 200%/1.5 Optima, 'Lucida Grande', Lucida, 'Lucida Sans Unicode', sans-serif;
}

ul {
  width: 9em;
  list-style-type: none;
  font-size: 0.75em;
}

li {
  float: left;
  margin: 0 4px 4px 0;
  background: #60c;
  background: rgba(102, 0, 204, 0.66);
  border: 4px solid #60c;
  color: #fff;
}
li:hover {
  position: relative;
}

ul ul {
  z-index: 1;
  position: absolute;
  left: -999em;
  width: auto;
  background: #ccc;
  background: rgba(204, 204, 204, 0.33);
}

li:hover ul {
  top: 2em;
  left: 3px;
}

li li {
  margin: 0 0 3px 0;
  background: #909;
  background: rgba(153, 0, 153, 0.66);
  border: 3px solid #909;
}

Apache Spark: map vs mapPartitions?

Map:

Map transformation.

The map works on a single Row at a time.

Map returns after each input Row.

The map doesn’t hold the output result in Memory.

Map no way to figure out then to end the service.

// map example

val dfList = (1 to 100) toList

val df = dfList.toDF()

val dfInt = df.map(x => x.getInt(0)+2)

display(dfInt)

MapPartition:

MapPartition transformation.

MapPartition works on a partition at a time.

MapPartition returns after processing all the rows in the partition.

MapPartition output is retained in memory, as it can return after processing all the rows in a particular partition.

MapPartition service can be shut down before returning.

// MapPartition example

Val dfList = (1 to 100) toList

Val df = dfList.toDF()

Val df1 = df.repartition(4).rdd.mapPartition((int) => Iterator(itr.length))

Df1.collec()

//display(df1.collect())

For more details, please refer to the Spark map vs mapPartitions transformation article.

Hope this is helpful!

open() in Python does not create a file if it doesn't exist

I think it's r+, not rw. I'm just a starter, and that's what I've seen in the documentation.

Easiest way to split a string on newlines in .NET?

using System.IO;

string textToSplit;

if (textToSplit != null)
{
    List<string> lines = new List<string>();
    using (StringReader reader = new StringReader(textToSplit))
    {
        for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
        {
            lines.Add(line);
        }
    }
}

Using GregorianCalendar with SimpleDateFormat

A SimpleDateFormat, as its name indicates, formats Dates. Not a Calendar. So, if you want to format a GregorianCalendar using a SimpleDateFormat, you must convert the Calendar to a Date first:

dateFormat.format(calendar.getTime());

And what you see printed is the toString() representation of the calendar. It's intended usage is debugging. It's not intended to be used to display a date in a GUI. For that, use a (Simple)DateFormat.

Finally, to convert from a String to a Date, you should also use a (Simple)DateFormat (its parse() method), rather than splitting the String as you're doing. This will give you a Date object, and you can create a Calendar from the Date by instanciating it (Calendar.getInstance()) and setting its time (calendar.setTime()).

My advice would be: Googling is not the solution here. Reading the API documentation is what you need to do.

Launch an event when checking a checkbox in Angular2

You can use ngModel like

<input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="addProp($event)" data-md-icheck/>

To update the checkbox state by updating the property checkboxValue in your code and when the checkbox is changed by the user addProp() is called.

How to define a two-dimensional array?

I'm on my first Python script, and I was a little confused by the square matrix example so I hope the below example will help you save some time:

 # Creates a 2 x 5 matrix
 Matrix = [[0 for y in xrange(5)] for x in xrange(2)]

so that

Matrix[1][4] = 2 # Valid
Matrix[4][1] = 3 # IndexError: list index out of range

How to extract numbers from a string in Python?

The best option I found is below. It will extract a number and can eliminate any type of char.

def extract_nbr(input_str):
    if input_str is None or input_str == '':
        return 0

    out_number = ''
    for ele in input_str:
        if ele.isdigit():
            out_number += ele
    return float(out_number)    

Hive query output to file

@sarath how to overwrite the file if i want to run another select * command from a different table and write to same file ?

INSERT OVERWRITE LOCAL DIRECTORY '/home/training/mydata/outputs' SELECT expl , count(expl) as total
FROM ( SELECT explode(splits) as expl FROM ( SELECT split(words,' ') as splits FROM wordcount ) t2 ) t3 GROUP BY expl ;

This is an example to sarath's question

the above is a word count job stored in outputs file which is in local directory :)

How to add a linked source folder in Android Studio?

If you're not using gradle (creating a project from an APK, for instance), this can be done through the Android Studio UI (as of version 3.3.2):

  • Right-click the project root directory, pick Open Module Settings
  • Hit the + Add Content Root button (center right)
  • Add your path and hit OK

In my experience (with native code), as long as your .so's are built with debug symbols and from the same absolute paths, breakpoints added in source files will be automatically recognized.

How to break/exit from a each() function in JQuery?

According to the documentation you can simply return false; to break:

$(xml).find("strengths").each(function() {

    if (iWantToBreak)
        return false;
});

How to set a value of a variable inside a template code?

An alternative way that doesn't require that you put everything in the "with" block is to create a custom tag that adds a new variable to the context. As in:

class SetVarNode(template.Node):
    def __init__(self, new_val, var_name):
        self.new_val = new_val
        self.var_name = var_name
    def render(self, context):
        context[self.var_name] = self.new_val
        return ''

import re
@register.tag
def setvar(parser,token):
    # This version uses a regular expression to parse tag contents.
    try:
        # Splitting by None == splitting by spaces.
        tag_name, arg = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents.split()[0]
    m = re.search(r'(.*?) as (\w+)', arg)
    if not m:
        raise template.TemplateSyntaxError, "%r tag had invalid arguments" % tag_name
    new_val, var_name = m.groups()
    if not (new_val[0] == new_val[-1] and new_val[0] in ('"', "'")):
        raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
    return SetVarNode(new_val[1:-1], var_name)

This will allow you to write something like this in your template:

{% setvar "a string" as new_template_var %}

Note that most of this was taken from here

Can't find bundle for base name

If you are using IntelliJ IDE just right click on resources package and go to new and then select Resource Boundle it automatically create a .properties file for you. This did work for me .

Field 'id' doesn't have a default value?

For me the issue got fixed when I changed

<id name="personID" column="person_id">
    <generator class="native"/>
</id>

to

<id name="personID" column="person_id">
    <generator class="increment"/>
</id>

in my Person.hbm.xml.

after that I re-encountered that same error for an another field(mobno). I tried restarting my IDE, recreating the database with previous back issue got eventually fixed when I re-create my tables using (without ENGINE=InnoDB DEFAULT CHARSET=latin1; and removing underscores in the field name)

CREATE TABLE `tbl_customers` (
  `pid` bigint(20) NOT NULL,
  `title` varchar(4) NOT NULL,
  `dob` varchar(10) NOT NULL,
  `address` varchar(100) NOT NULL,
  `country` varchar(4) DEFAULT NULL,
  `hometp` int(12) NOT NULL,
  `worktp` int(12) NOT NULL,
  `mobno` varchar(12) NOT NULL,
  `btcfrom` varchar(8) NOT NULL,
  `btcto` varchar(8) NOT NULL,
  `mmname` varchar(20) NOT NULL
)

instead of

CREATE TABLE `tbl_person` (
  `person_id` bigint(20) NOT NULL,
  `person_nic` int(10) NOT NULL,
  `first_name` varchar(20) NOT NULL,
  `sur_name` varchar(20) NOT NULL,
  `person_email` varchar(20) NOT NULL,
  `person_password` varchar(512) NOT NULL,
  `mobno` varchar(10) NOT NULL DEFAULT '1',
  `role` varchar(10) NOT NULL,
  `verified` int(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

I probably think this due to using ENGINE=InnoDB DEFAULT CHARSET=latin1; , because I once got the error org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Unknown column 'mob_no' in 'field list' even though it was my previous column name, which even do not exist in my current table. Even after backing up the database(with modified column name, using InnoDB engine) I still got that same error with old field name. This probably due to caching in that Engine.

What happens to C# Dictionary<int, int> lookup if the key does not exist?

You should check for Dictionary.ContainsKey(int key) before trying to pull out the value.

Dictionary<int, int> myDictionary = new Dictionary<int, int>();
myDictionary.Add(2,4);
myDictionary.Add(3,5);

int keyToFind = 7;
if(myDictionary.ContainsKey(keyToFind))
{
    myValueLookup = myDictionay[keyToFind];
    // do work...
}
else
{
    // the key doesn't exist.
}

How to empty/destroy a session in rails?

To clear the whole thing use the reset_session method in a controller.

reset_session

Here's the documentation on this method: http://api.rubyonrails.org/classes/ActionController/Base.html#M000668

Resets the session by clearing out all the objects stored within and initializing a new session object.

Good luck!

Explanation of the UML arrows

Aggregations and compositions are a little bit confusing. However, think like compositions are a stronger version of aggregation. What does that mean? Let's take an example: (Aggregation) 1. Take a classroom and students: In this case, we try to analyze the relationship between them. A classroom has a relationship with students. That means classroom comprises of one or many students. Even if we remove the Classroom class, the Students class does not need to destroy, which means we can use Student class independently.

(Composition) 2. Take a look at pages and Book Class. In this case, pages is a book, which means collections of pages makes the book. If we remove the book class, the whole Page class will be destroyed. That means we cannot use the class of the page independently.

If you are still unclear about this topic, watch out this short wonderful video, which has explained the aggregation more clearly.

https://www.youtube.com/watch?v=d5ecYmyFZW0

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

Here's what Oracle's documentation has to say:

By default the heap dump is created in a file called java_pid.hprof in the working directory of the VM, as in the example above. You can specify an alternative file name or directory with the -XX:HeapDumpPath= option. For example -XX:HeapDumpPath=/disk2/dumps will cause the heap dump to be generated in the /disk2/dumps directory.

Interpreting "condition has length > 1" warning from `if` function

maybe you want ifelse:

a <- c(1,1,1,1,0,0,0,0,2,2)
ifelse(a>0,a/sum(a),1)

 [1] 0.125 0.125 0.125 0.125 1.000 1.000 1.000 1.000
 [9] 0.250 0.250

Mongoose (mongodb) batch insert?

You can perform bulk insert using mongoose, as the highest score answer. But the example cannot work, it should be:

/* a humongous amount of potatos */
var potatoBag = [{name:'potato1'}, {name:'potato2'}];

var Potato = mongoose.model('Potato', PotatoSchema);
Potato.collection.insert(potatoBag, onInsert);

function onInsert(err, docs) {
    if (err) {
        // TODO: handle error
    } else {
        console.info('%d potatoes were successfully stored.', docs.length);
    }
}

Don't use a schema instance for the bulk insert, you should use a plain map object.

Reset par to the default values at startup

Use below script to get back to normal 1 plot:

par(mfrow = c(1,1))

Submit two forms with one button

if you want to submit two forms with one button you need to do this:

1- use setTimeout()

2- allow show pop up

<script>
function myFunction() {
setTimeout(function(){ document.getElementById("form1").submit();}, 3000);   
setTimeout(function(){ document.getElementById("form2").submit();}, 6000);   
}
</script>
<form  target="_blank" id="form1">
<input type="text">
<input type="submit">
</form>
<form target="_blank" id="form2">
<input type="text">
<input type="submit">
</form>

javascript doesn't submit two forms at the same time. we submit two forms with one button not at the same time but after secounds.

edit: when we use this code, browser doesn't allow pop up.
if you use this code for your software like me just set browser for show pop up but if you use it in designing site, browser is a barrier and code doesn't run.

How to find difference between two Joda-Time DateTimes in minutes

Something like...

Minutes.minutesBetween(getStart(), getEnd()).getMinutes();

Convert time fields to strings in Excel

If you want to show those number values as a time then change the format of the cell to Time.

And if you want to transform it to a text in another cell:

=TEXT(A1,"hh:mm:ss")

What is the best way to remove a table row with jQuery?

Is the following acceptable:

$('#myTableRow').remove();

Subversion stuck due to "previous operation has not finished"?

In my case a background Java Virtual Machine instance was running, killing which cleanup was successful.

python-pandas and databases like mysql

For Postgres users

import psycopg2
import pandas as pd

conn = psycopg2.connect("database='datawarehouse' user='user1' host='localhost' password='uberdba'")

customers = 'select * from customers'

customers_df = pd.read_sql(customers,conn)

customers_df

How to match a substring in a string, ignoring case

you can also use: s.lower() in str.lower()

How to re-index all subarray elements of a multidimensional array?

To reset the keys of all arrays in an array:

$arr = array_map('array_values', $arr);

In case you just want to reset first-level array keys, use array_values() without array_map.

How do ports work with IPv6?

I would say the best reference is Format for Literal IPv6 Addresses in URL's where usage of [] is defined.

Also, if it is for programming and code, specifically Java, I would suggest this readsClass for Inet6Address java/net/URL definition where usage of Inet4 address in Inet6 connotation and other cases are presented in details. For my case, IPv4-mapped address Of the form::ffff:w.x.y.z, for IPv6 address is used to represent an IPv4 address also solved my problem. It allows the native program to use the same address data structure and also the same socket when communicating with both IPv4 and IPv6 nodes. This is the case on Amazon cloud Linux boxes default setup.

How to convert POJO to JSON and vice versa?

Take a look at https://www.json.org

[edited] Imagine that you have a simple Java class like this:

public class Person {

    private String name;
    private Integer age;

    public String getName() { return this.name; }
    public void setName( String name ) { this.name = name; }

    public Integer getAge() { return this.age; }
    public void setAge( Integer age ) { this.age = age; }

}

So, to transform it to a JSon object, it's very simple. Like this:

import org.json.JSONObject;

public class JsonTest {

    public static void main( String[] args ) {
        Person person = new Person();
        person.setName( "Person Name" );
        person.setAge( 333 );

        JSONObject jsonObj = new JSONObject( person );
        System.out.println( jsonObj );
    }

}

Hope it helps.

[edited] Here there is other example, in this case using Jackson: https://brunozambiazi.wordpress.com/2015/08/15/working-with-json-in-java/

Maven:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.1</version>
</dependency>

And a link (below) to find the latest/greatest version:

https://search.maven.org/classic/#search%7Cga%7C1%7Cg%3A%22com.fasterxml.jackson.core%22%20AND%20a%3A%22jackson-databind%22

Adjust width and height of iframe to fit with content in it

If the content is just a very simple html, the simplest way is to remove the iframe with javascript

HTML code:

<div class="iframe">
    <iframe src="./mypage.html" frameborder="0" onload="removeIframe(this);"></iframe>
</div>

Javascript code:

function removeIframe(obj) {
    var iframeDocument = obj.contentDocument || obj.contentWindow.document;
    var mycontent = iframeDocument.getElementsByTagName("body")[0].innerHTML;
    obj.remove();
    document.getElementsByClassName("iframe")[0].innerHTML = mycontent;
}

What is a Y-combinator?

y-combinator in JavaScript:

var Y = function(f) {
  return (function(g) {
    return g(g);
  })(function(h) {
    return function() {
      return f(h(h)).apply(null, arguments);
    };
  });
};

var factorial = Y(function(recurse) {
  return function(x) {
    return x == 0 ? 1 : x * recurse(x-1);
  };
});

factorial(5)  // -> 120

Edit: I learn a lot from looking at code, but this one is a bit tough to swallow without some background - sorry about that. With some general knowledge presented by other answers, you can begin to pick apart what is happening.

The Y function is the "y-combinator". Now take a look at the var factorial line where Y is used. Notice you pass a function to it that has a parameter (in this example, recurse) that is also used later on in the inner function. The parameter name basically becomes the name of the inner function allowing it to perform a recursive call (since it uses recurse() in it's definition.) The y-combinator performs the magic of associating the otherwise anonymous inner function with the parameter name of the function passed to Y.

For the full explanation of how Y does the magic, checked out the linked article (not by me btw.)

Expand div to max width when float:left is set

Elements that are floated are taken out of the normal flow layout, and block elements, such as DIV's, no longer span the width of their parent. The rules change in this situation. Instead of reinventing the wheel, check out this site for some possible solutions to create the two column layout you are after: http://www.maxdesign.com.au/presentation/page_layouts/

Specifically, the "Liquid Two-Column layout".

Cheers!

How to format date in angularjs

// $scope.dateField="value" in ctrl
<div ng-bind="dateField | date:'MM/dd/yyyy'"></div>

PHP Parse error: syntax error, unexpected '?' in helpers.php 233

I had the same error and the problem is that I had not correctly installed Composer.

I am using Windows and I installed Composer-Setup.exe from getcomposer.org and when you have more than one version of PHP installed you must select the version that you are running at this point of the installation

enter image description here

git rm - fatal: pathspec did not match any files

To remove the tracked and old committed file from git you can use the below command. Here in my case, I want to untrack and remove all the file from dist directory.

git filter-branch --force --index-filter 'git rm -r --cached --ignore-unmatch dist' --tag-name-filter cat -- --all

Then, you need to add it into your .gitignore so it won't be tracked further.

Subprocess changing directory

Another option based on this answer: https://stackoverflow.com/a/29269316/451710

This allows you to execute multiple commands (e.g cd) in the same process.

import subprocess

commands = '''
pwd
cd some-directory
pwd
cd another-directory
pwd
'''

process = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = process.communicate(commands.encode('utf-8'))
print(out.decode('utf-8'))

What is best way to start and stop hadoop ecosystem, with command line?

Starting

start-dfs.sh (starts the namenode and the datanode)
start-mapred.sh (starts the jobtracker and the tasktracker)

Stopping

stop-dfs.sh
stop-mapred.sh

Split column at delimiter in data frame

Hadley has a very elegant solution to do this inside data frames in his reshape package, using the function colsplit.

require(reshape)
> df <- data.frame(ID=11:13, FOO=c('a|b','b|c','x|y'))
> df
  ID FOO
1 11 a|b
2 12 b|c
3 13 x|y
> df = transform(df, FOO = colsplit(FOO, split = "\\|", names = c('a', 'b')))
> df
  ID FOO.a FOO.b
1 11     a     b
2 12     b     c
3 13     x     y

Python equivalent of D3.js

You could use d3py a python module that generate xml pages embedding d3.js script. For example :

import d3py
import networkx as nx

import logging
logging.basicConfig(level=logging.DEBUG)

G = nx.Graph()
G.add_edge(1,2)
G.add_edge(1,3)
G.add_edge(3,2)
G.add_edge(3,4)
G.add_edge(4,2)

# use 'with' if you are writing a script and want to serve this up forever
with d3py.NetworkXFigure(G, width=500, height=500) as p:
    p += d3py.ForceLayout()
    p.show()

Get current language in CultureInfo

This is what i used:

var culture = System.Globalization.CultureInfo.CurrentCulture;

and it's working :)

Jquery in React is not defined

Just a note: if you use arrow functions you don't need the const that = this part. It might look like this:

fetch('http://jsonplaceholder.typicode.com/posts') 
  .then((response) => { return response.json(); }) 
  .then((myJson) => { 
     this.setState({data: myJson}); // for example
});

Installing tkinter on ubuntu 14.04

To get this to work with pyenv on Ubuntu 16.04, I had to:

$ sudo apt-get install python-tk python3-tk tk-dev

Then install the version of Python I wanted via pyenv:

$ pyenv install 3.6.2

Then I could import tkinter just fine:

import tkinter

Perform debounce in React.js

If you don't like to add lodash or any other package:

import React, { useState, useRef } from "react";

function DebouncedInput() {
  const [isRefetching, setIsRefetching] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const previousSearchTermRef = useRef("");

  function setDebouncedSearchTerm(value) {
    setIsRefetching(true);
    setSearchTerm(value);
    previousSearchTermRef.current = value;
    setTimeout(async () => {
      if (previousSearchTermRef.current === value) {
        try {
          // await refetch();
        } finally {
          setIsRefetching(false);
        }
      }
    }, 500);
  }

  return (
    <input
      value={searchTerm}
      onChange={(event) => setDebouncedSearchTerm(event.target.value)}
    />
  );
}

pycharm running way slow

Regarding the freezing issue, we found this occurred when processing CSV files with at least one extremely long line.

To reproduce:

[print(x) for x in (['A' * 54790] + (['a' * 1421] * 10))]

However, it appears to have been fixed in PyCharm 4.5.4, so if you experience this, try updating your PyCharm.

Getting 400 bad request error in Jquery Ajax POST

Yes. You need to stringify the JSON data orlse 400 bad request error occurs as it cannot identify the data.

400 Bad Request

Bad Request. Your browser sent a request that this server could not understand.

Plus you need to add content type and datatype as well. If not you will encounter 415 error which says Unsupported Media Type.

415 Unsupported Media Type

Try this.

var newData =   {
                  "subject:title":"Test Name",
                  "subject:description":"Creating test subject to check POST method API",
                  "sub:tags": ["facebook:work", "facebook:likes"],
                  "sampleSize" : 10,
                  "values": ["science", "machine-learning"]
                  };

var dataJson = JSON.stringify(newData);

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: dataJson,
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

With this way you can modify the data you need with ease. It wont confuse you as it is defined outside the ajax block.

How do I update a Mongo document after inserting it?

This is an old question, but I stumbled onto this when looking for the answer so I wanted to give the update to the answer for reference.

The methods save and update are deprecated.

save(to_save, manipulate=True, check_keys=True, **kwargs)¶ Save a document in this collection.

DEPRECATED - Use insert_one() or replace_one() instead.

Changed in version 3.0: Removed the safe parameter. Pass w=0 for unacknowledged write operations.

update(spec, document, upsert=False, manipulate=False, multi=False, check_keys=True, **kwargs) Update a document(s) in this collection.

DEPRECATED - Use replace_one(), update_one(), or update_many() instead.

Changed in version 3.0: Removed the safe parameter. Pass w=0 for unacknowledged write operations.

in the OPs particular case, it's better to use replace_one.

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

The command is date

To customise the output there are a myriad of options available, see date --help for a list.

For example, date '+%A %W %Y %X' gives Tuesday 34 2013 08:04:22 which is the name of the day of the week, the week number, the year and the time.

How can I set multiple CSS styles in JavaScript?

Since strings support adding, you can easily add your new style without overriding the current:

document.getElementById("myElement").style.cssText += `
   font-size: 12px;
   left: 200px;
   top: 100px;
`;

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

ASP.NET Core Web API exception handling

There is a built-in middleware that makes it easier than writing a custom one.

Asp.Net Core 5 version:

app.UseExceptionHandler(a => a.Run(async context =>
{
    var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
    var exception = exceptionHandlerPathFeature.Error;
    
    await context.Response.WriteAsJsonAsync(new { error = exception.Message });
}));

Older versions (they did not have WriteAsJsonAsync extension):

app.UseExceptionHandler(a => a.Run(async context =>
{
    var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
    var exception = exceptionHandlerPathFeature.Error;
    
    var result = JsonConvert.SerializeObject(new { error = exception.Message });
    context.Response.ContentType = "application/json";
    await context.Response.WriteAsync(result);
}));

It should do pretty much the same, just a bit less code to write.

Important: Remember to add it before UseMvc (or UseRouting in .Net Core 3) as order is important.

MySQL "Or" Condition

try this

mysql_query("
SELECT * FROM Drinks WHERE
    email='$Email'
    AND date='$Date_Today'
    OR date='$Date_Yesterday', '$Date_TwoDaysAgo', '$Date_ThreeDaysAgo', '$Date_FourDaysAgo', '$Date_FiveDaysAgo', '$Date_SixDaysAgo', '$Date_SevenDaysAgo'"     
   );

my be like this

 OR date='$Date_Yesterday' oR '$Date_TwoDaysAgo'.........

React-Native: Module AppRegistry is not a registered callable module

For me just i linked with react native as this way : react-native link

When should an IllegalArgumentException be thrown?

Throwing runtime exceptions "sparingly" isn't really a good policy -- Effective Java recommends that you use checked exceptions when the caller can reasonably be expected to recover. (Programmer error is a specific example: if a particular case indicates programmer error, then you should throw an unchecked exception; you want the programmer to have a stack trace of where the logic problem occurred, not to try to handle it yourself.)

If there's no hope of recovery, then feel free to use unchecked exceptions; there's no point in catching them, so that's perfectly fine.

It's not 100% clear from your example which case this example is in your code, though.

Standard deviation of a list

In python 2.7 you can use NumPy's numpy.std() gives the population standard deviation.

In Python 3.4 statistics.stdev() returns the sample standard deviation. The pstdv() function is the same as numpy.std().

How to correctly implement custom iterators and const_iterators?

I don't know if Boost has anything that would help.

My preferred pattern is simple: take a template argument which is equal to value_type, either const qualified or not. If necessary, also a node type. Then, well, everything kind of falls into place.

Just remember to parameterize (template-ize) everything that needs to be, including the copy constructor and operator==. For the most part, the semantics of const will create correct behavior.

template< class ValueType, class NodeType >
struct my_iterator
 : std::iterator< std::bidirectional_iterator_tag, T > {
    ValueType &operator*() { return cur->payload; }

    template< class VT2, class NT2 >
    friend bool operator==
        ( my_iterator const &lhs, my_iterator< VT2, NT2 > const &rhs );

    // etc.

private:
    NodeType *cur;

    friend class my_container;
    my_iterator( NodeType * ); // private constructor for begin, end
};

typedef my_iterator< T, my_node< T > > iterator;
typedef my_iterator< T const, my_node< T > const > const_iterator;

What does axis in pandas mean?

axis = 0 means up to down axis = 1 means left to right

sums[key] = lang_sets[key].iloc[:,1:].sum(axis=0)

Given example is taking sum of all the data in column == key.

How to connect to a MS Access file (mdb) using C#?

Here's how to use a Jet OLEDB or Ace OLEDB Access DB:

using System.Data;
using System.Data.OleDb;

string myConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
                           "Data Source=C:\myPath\myFile.mdb;" +                                    
                           "Persist Security Info=True;" +
                           "Jet OLEDB:Database Password=myPassword;";
try
{
    // Open OleDb Connection
    OleDbConnection myConnection = new OleDbConnection();
    myConnection.ConnectionString = myConnectionString;
    myConnection.Open();

    // Execute Queries
    OleDbCommand cmd = myConnection.CreateCommand();
    cmd.CommandText = "SELECT * FROM `myTable`";
    OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); // close conn after complete

    // Load the result into a DataTable
    DataTable myDataTable = new DataTable();
    myDataTable.Load(reader);
}
catch (Exception ex)
{
    Console.WriteLine("OLEDB Connection FAILED: " + ex.Message);
}

How can I brew link a specific version?

I asked in #machomebrew and learned that you can switch between versions using brew switch.

$ brew switch libfoo mycopy 

to get version mycopy of libfoo.

Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

Here's a cleaned-up, non-eval-using version of Ram-swaroop's "works in all browsers" variety--works in all browsers!

function onReady(yourMethod) {
  var readyStateCheckInterval = setInterval(function() {
    if (document && document.readyState === 'complete') { // Or 'interactive'
      clearInterval(readyStateCheckInterval);
      yourMethod();
    }
  }, 10);
}
// use like
onReady(function() { alert('hello'); } );

It does wait an extra 10 ms to run, however, so here's a more complicated way that shouldn't:

function onReady(yourMethod) {
  if (document.readyState === 'complete') { // Or also compare to 'interactive'
    setTimeout(yourMethod, 1); // Schedule to run immediately
  }
  else {
    readyStateCheckInterval = setInterval(function() {
      if (document.readyState === 'complete') { // Or also compare to 'interactive'
        clearInterval(readyStateCheckInterval);
        yourMethod();
      }
    }, 10);
  }
}

// Use like
onReady(function() { alert('hello'); } );

// Or
onReady(functionName);

See also How to check if DOM is ready without a framework?.

How to install CocoaPods?

Are you behind a proxy? If so, pass the proxy as an argument sudo gem install --http-proxy http://user:[email protected]:80 cocoapods `

MySQL fails on: mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"

This may work

CREATE USER 'user'@'localhost' IDENTIFIED BY 'pwd';

ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';

In Javascript, how to conditionally add a member to an object?

I think your first approach to adding members conditionally is perfectly fine. I don't really agree with not wanting to have a member b of a with a value of undefined. It's simple enough to add an undefined check with usage of a for loop with the in operator. But anyways, you could easily write a function to filter out undefined members.

var filterUndefined = function(obj) {
  var ret = {};
  for (var key in obj) {
    var value = obj[key];
    if (obj.hasOwnProperty(key) && value !== undefined) {
      ret[key] = value;
    }
  }
  return ret;
};

var a = filterUndefined({
  b: (conditionB? 5 : undefined),
  c: (conditionC? 5 : undefined),
  d: (conditionD? 5 : undefined),
  e: (conditionE? 5 : undefined),
  f: (conditionF? 5 : undefined),
  g: (conditionG? 5 : undefined),
});

You could also use the delete operator to edit the object in place.

How can I use grep to show just filenames on Linux?

For a simple file search you could use grep's -l and -r options:

grep -rl "mystring"

All the search is done by grep. Of course, if you need to select files on some other parameter, find is the correct solution:

find . -iname "*.php" -execdir grep -l "mystring" {} +

The execdir option builds each grep command per each directory, and concatenates filenames into only one command (+).

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

I have faced a similar error. I checked the log in /var/log/apache2/error.log and found an UnexpectedValueException

I changed the owner to my apache user of the storage folder under the project dir.

sudo chown -R www-data:www-data ./storage

In my case apache2 process owner is www-data, so change this to yours, this can be found in apache2 config file. Hope this is useful to you.

Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

However, the code below allows spaces.

No, it doesn't. However, it will only match on input with a length of 1. For inputs with a length greater than or equal to 1, you need a + following the character class:

var regexp = /^[a-zA-Z0-9-_]+$/;
var check = "checkme";
if (check.search(regexp) === -1)
    { alert('invalid'); }
else
    { alert('valid'); }

Note that neither the - (in this instance) nor the _ need escaping.

How do I read a text file of about 2 GB?

I use UltraEdit to edit large files. The maximum size I open with UltraEdit was about 2.5 GB. Also UltraEdit has a good hex editor in comparison to Notepad++.

How to connect to my http://localhost web server from Android Emulator

Try http://10.0.2.2:8080/ where 8080 is your port number. It worked perfectly. If you just try 10.0.2.2 it won't work. You need to add port number to it. Also if Microsoft IIS has been installed try turning off that feature from control panel (if using any windows os) and then try as given above.

sql - insert into multiple tables in one query

MySQL doesn't support multi-table insertion in a single INSERT statement. Oracle is the only one I'm aware of that does, oddly...

INSERT INTO NAMES VALUES(...)
INSERT INTO PHONES VALUES(...)

JavaScript dictionary with names

The main problem I see with what you have is that it's difficult to loop through, for populating a table.

Simply use an array of arrays:

var myMappings = [
    ["Name", "10%"], // Note the quotes around "10%"
    ["Phone", "10%"],
    // etc..
];

... which simplifies access:

myMappings[0][0]; // column name
myMappings[0][1]; // column width

Alternatively:

var myMappings = {
    names: ["Name", "Phone", etc...],
    widths: ["10%", "10%", etc...]
};

And access with:

myMappings.names[0];
myMappings.widths[0];

Check if URL has certain string with PHP

$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];


if (!strpos($url,'car')) {
    echo 'Car exists.';
} else {
    echo 'No cars.';
}

This seems to work.

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

For some reason mysql on OS X gets the locations of the required socket file a bit wrong, but thankfully the solution is as simple as setting up a symbolic link.

You may have a socket (appearing as a zero length file) as /tmp/mysql.sock or /var/mysql/mysql.sock, but one or more apps is looking in the other location for it. Find out with this command:

ls -l /tmp/mysql.sock /var/mysql/mysql.sock

Rather than move the socket, edit config files, and have to remember to keep edited files local and away from servers where the paths are correct, simply create a symbolic link so your Mac finds the required socket, even when it's looking in the wrong place!

If you have /tmp/mysql.sock but no /var/mysql/mysql.sock then...

cd /var 
sudo mkdir mysql
sudo chmod 755 mysql
cd mysql
sudo ln -s /tmp/mysql.sock mysql.sock

If you have /var/mysql/mysql.sock but no /tmp/mysql.sock then...

cd /tmp
ln -s /var/mysql/mysql.sock mysql.sock

You will need permissions to create the directory and link, so just prefix the commands above with sudo if necessary.

Is there a way to check which CSS styles are being used or not used on a web page?

Without any third-party tools and any app, you can find unused CSS and javascript by using chrome dev tools in the coverage tab. read the post below from google developers. chrome coverage tab

Host binding and Host listening

@HostListener is a decorator for the callback/event handler method, so remove the ; at the end of this line:

@HostListener('click', ['$event.target']);

Here's a working plunker that I generated by copying the code from the API docs, but I put the onClick() method on the same line for clarity:

import {Component, HostListener, Directive} from 'angular2/core';

@Directive({selector: 'button[counting]'})
class CountClicks {
  numberOfClicks = 0;
  @HostListener('click', ['$event.target']) onClick(btn) {
    console.log("button", btn, "number of clicks:", this.numberOfClicks++);
  }
}
@Component({
  selector: 'my-app',
  template: `<button counting>Increment</button>`,
  directives: [CountClicks]
})
export class AppComponent {
  constructor() { console.clear(); }
}

Host binding can also be used to listen to global events:

To listen to global events, a target must be added to the event name. The target can be window, document or body (reference)

@HostListener('document:keyup', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }

Class 'DOMDocument' not found

On fedora 26:

dnf install php-dom

Fixes it !

How do I get a python program to do nothing?

The pass command is what you are looking for. Use pass for any construct that you want to "ignore". Your example uses a conditional expression but you can do the same for almost anything.

For your specific use case, perhaps you'd want to test the opposite condition and only perform an action if the condition is false:

if num2 != num5:
    make_some_changes()

This will be the same as this:

if num2 == num5:
    pass
else:
    make_some_changes()

That way you won't even have to use pass and you'll also be closer to adhering to the "Flatter is better than nested" convention in PEP20.


You can read more about the pass statement in the documentation:

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.

if condition:
    pass
try:
    make_some_changes()
except Exception:
    pass # do nothing
class Foo():
    pass # an empty class definition
def bar():
    pass # an empty function definition

How to loop through array in jQuery?

  for(var key in substr)
{
     // do something with substr[key];

} 

'xmlParseEntityRef: no name' warnings while loading xml into a php file

Try to clean the HTML first using this function:

$html = htmlspecialchars($html);

Special chars are usually represented differently in HTML and it might be confusing for the compiler. Like & becomes &amp;.

Firebase: how to generate a unique numeric ID for key?

https://firebase.google.com/docs/firestore/manage-data/transactions

Use transactions and keep a number in the database somewhere that you can increase by one. This way you can get a nice numeric and simple id.

How to display raw html code in PRE or something like it but without escaping it

xmp is the way to go, i.e.:

<xmp>
  # your code...
</xmp>

The server response was: 5.7.0 Must issue a STARTTLS command first. i16sm1806350pag.18 - gsmtp

"https://www.google.com/settings/security/lesssecureapps" use this link after log in your gmail account and click turn on.Then run your application,it will work surely.

In plain English, what does "git reset" do?

In general, git reset's function is to take the current branch and reset it to point somewhere else, and possibly bring the index and work tree along. More concretely, if your master branch (currently checked out) is like this:

- A - B - C (HEAD, master)

and you realize you want master to point to B, not C, you will use git reset B to move it there:

- A - B (HEAD, master)      # - C is still here, but there's no branch pointing to it anymore

Digression: This is different from a checkout. If you'd run git checkout B, you'd get this:

- A - B (HEAD) - C (master)

You've ended up in a detached HEAD state. HEAD, work tree, index all match B, but the master branch was left behind at C. If you make a new commit D at this point, you'll get this, which is probably not what you want:

- A - B - C (master)
       \
        D (HEAD)

Remember, reset doesn't make commits, it just updates a branch (which is a pointer to a commit) to point to a different commit. The rest is just details of what happens to your index and work tree.

Use cases

I cover many of the main use cases for git reset within my descriptions of the various options in the next section. It can really be used for a wide variety of things; the common thread is that all of them involve resetting the branch, index, and/or work tree to point to/match a given commit.

Things to be careful of

  • --hard can cause you to really lose work. It modifies your work tree.

  • git reset [options] commit can cause you to (sort of) lose commits. In the toy example above, we lost commit C. It's still in the repo, and you can find it by looking at git reflog show HEAD or git reflog show master, but it's not actually accessible from any branch anymore.

  • Git permanently deletes such commits after 30 days, but until then you can recover C by pointing a branch at it again (git checkout C; git branch <new branch name>).

Arguments

Paraphrasing the man page, most common usage is of the form git reset [<commit>] [paths...], which will reset the given paths to their state from the given commit. If the paths aren't provided, the entire tree is reset, and if the commit isn't provided, it's taken to be HEAD (the current commit). This is a common pattern across git commands (e.g. checkout, diff, log, though the exact semantics vary), so it shouldn't be too surprising.

For example, git reset other-branch path/to/foo resets everything in path/to/foo to its state in other-branch, git reset -- . resets the current directory to its state in HEAD, and a simple git reset resets everything to its state in HEAD.

The main work tree and index options

There are four main options to control what happens to your work tree and index during the reset.

Remember, the index is git's "staging area" - it's where things go when you say git add in preparation to commit.

  • --hard makes everything match the commit you've reset to. This is the easiest to understand, probably. All of your local changes get clobbered. One primary use is blowing away your work but not switching commits: git reset --hard means git reset --hard HEAD, i.e. don't change the branch but get rid of all local changes. The other is simply moving a branch from one place to another, and keeping index/work tree in sync. This is the one that can really make you lose work, because it modifies your work tree. Be very very sure you want to throw away local work before you run any reset --hard.

  • --mixed is the default, i.e. git reset means git reset --mixed. It resets the index, but not the work tree. This means all your files are intact, but any differences between the original commit and the one you reset to will show up as local modifications (or untracked files) with git status. Use this when you realize you made some bad commits, but you want to keep all the work you've done so you can fix it up and recommit. In order to commit, you'll have to add files to the index again (git add ...).

  • --soft doesn't touch the index or work tree. All your files are intact as with --mixed, but all the changes show up as changes to be committed with git status (i.e. checked in in preparation for committing). Use this when you realize you've made some bad commits, but the work's all good - all you need to do is recommit it differently. The index is untouched, so you can commit immediately if you want - the resulting commit will have all the same content as where you were before you reset.

  • --merge was added recently, and is intended to help you abort a failed merge. This is necessary because git merge will actually let you attempt a merge with a dirty work tree (one with local modifications) as long as those modifications are in files unaffected by the merge. git reset --merge resets the index (like --mixed - all changes show up as local modifications), and resets the files affected by the merge, but leaves the others alone. This will hopefully restore everything to how it was before the bad merge. You'll usually use it as git reset --merge (meaning git reset --merge HEAD) because you only want to reset away the merge, not actually move the branch. (HEAD hasn't been updated yet, since the merge failed)

    To be more concrete, suppose you've modified files A and B, and you attempt to merge in a branch which modified files C and D. The merge fails for some reason, and you decide to abort it. You use git reset --merge. It brings C and D back to how they were in HEAD, but leaves your modifications to A and B alone, since they weren't part of the attempted merge.

Want to know more?

I do think man git reset is really quite good for this - perhaps you do need a bit of a sense of the way git works for them to really sink in though. In particular, if you take the time to carefully read them, those tables detailing states of files in index and work tree for all the various options and cases are very very helpful. (But yes, they're very dense - they're conveying an awful lot of the above information in a very concise form.)

Strange notation

The "strange notation" (HEAD^ and HEAD~1) you mention is simply a shorthand for specifying commits, without having to use a hash name like 3ebe3f6. It's fully documented in the "specifying revisions" section of the man page for git-rev-parse, with lots of examples and related syntax. The caret and the tilde actually mean different things:

  • HEAD~ is short for HEAD~1 and means the commit's first parent. HEAD~2 means the commit's first parent's first parent. Think of HEAD~n as "n commits before HEAD" or "the nth generation ancestor of HEAD".
  • HEAD^ (or HEAD^1) also means the commit's first parent. HEAD^2 means the commit's second parent. Remember, a normal merge commit has two parents - the first parent is the merged-into commit, and the second parent is the commit that was merged. In general, merges can actually have arbitrarily many parents (octopus merges).
  • The ^ and ~ operators can be strung together, as in HEAD~3^2, the second parent of the third-generation ancestor of HEAD, HEAD^^2, the second parent of the first parent of HEAD, or even HEAD^^^, which is equivalent to HEAD~3.

caret and tilde

on change event for file input element

Give unique class and different id for file input

           $("#tab-content").on('change',class,function()
               {
                  var id=$(this).attr('id');
                      $("#"+id).trigger(your function); 
               //for name of file input  $("#"+id).attr("name");
               });

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

Remember to restart Visual Studio after you've done the Set-ExecutionPolicy Unrestricted in PowerShell (x86).

If that doesn't work, try Set-ExecutionPolicy RemoteSigned in PowerShell (x86) then restart Visual Studio.

How can I determine whether a 2D Point is within a Polygon?

This is a presumably slightly less optimized version of the C code from here which was sourced from this page.

My C++ version uses a std::vector<std::pair<double, double>> and two doubles as an x and y. The logic should be exactly the same as the original C code, but I find mine easier to read. I can't speak for the performance.

bool point_in_poly(std::vector<std::pair<double, double>>& verts, double point_x, double point_y)
{
    bool in_poly = false;
    auto num_verts = verts.size();
    for (int i = 0, j = num_verts - 1; i < num_verts; j = i++) {
        double x1 = verts[i].first;
        double y1 = verts[i].second;
        double x2 = verts[j].first;
        double y2 = verts[j].second;

        if (((y1 > point_y) != (y2 > point_y)) &&
            (point_x < (x2 - x1) * (point_y - y1) / (y2 - y1) + x1))
            in_poly = !in_poly;
    }
    return in_poly;
}

The original C code is

int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)
{
  int i, j, c = 0;
  for (i = 0, j = nvert-1; i < nvert; j = i++) {
    if ( ((verty[i]>testy) != (verty[j]>testy)) &&
     (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
       c = !c;
  }
  return c;
}

How to turn off caching on Firefox?

Enter "about:config" into the Firefox address bar and set:

browser.cache.disk.enable = false
browser.cache.memory.enable = false

If developing locally, or using HTML5's new manifest attribute you may have to also set the following in about:config -

browser.cache.offline.enable = false

javascript - Create Simple Dynamic Array

A little late to this game, but there is REALLY cool stuff you can do with ES6 these days.

You can now fill an array of dynamic length with random numbers in one line of code!

[...Array(10).keys()].map(() => Math.floor(Math.random() * 100))

How to make popup look at the centre of the screen?

In order to get the popup exactly centered, it's a simple matter of applying a negative top margin of half the div height, and a negative left margin of half the div width. For this example, like so:

.div {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 50%;
}

Count how many rows have the same value

FOR SPECIFIC NUM:

SELECT COUNT(1) FROM YOUR_TABLE WHERE NUM = 1

FOR ALL NUM:

SELECT NUM, COUNT(1) FROM YOUR_TABLE GROUP BY NUM

Ruby objects and JSON serialization (without Rails)

If rendering performance is critical, you might also want to look at yajl-ruby, which is a binding to the C yajl library. The serialization API for that one looks like:

require 'yajl'
Yajl::Encoder.encode({"foo" => "bar"}) #=> "{\"foo\":\"bar\"}"

How to connect html pages to mysql database?

HTML are markup languages, basically they are set of tags like <html>, <body>, which is used to present a website using , and as a whole. All these, happen in the clients system or the user you will be browsing the website.

Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.

So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like , , etc.

Now, lets see a snippet of connection using MYSQLi Extension of PHP

$db = mysqli_connect('hostname','username','password','databasename');

This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:

<?php
    $db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
    <body>
          <?php
                $query = "SELECT * FROM `mytable`;";
                $result = mysqli_query($db, $query);
                while($row = mysqli_fetch_assoc($result)) {
                      // Display your datas on the page
                }
          ?>
    </body>
</html>

In order to insert new data into the database, you can use phpMyAdmin or write a INSERT query and execute them.

Efficient way to rotate a list in python

Jon Bentley in Programming Pearls (Column 2) describes an elegant and efficient algorithm for rotating an n-element vector x left by i positions:

Let's view the problem as transforming the array ab into the array ba, but let's also assume that we have a function that reverses the elements in a specified portion of the array. Starting with ab, we reverse a to get arb, reverse b to get arbr, and then reverse the whole thing to get (arbr)r, which is exactly ba. This results in the following code for rotation:

reverse(0, i-1)
reverse(i, n-1)
reverse(0, n-1)

This can be translated to Python as follows:

def rotate(x, i):
    i %= len(x)
    x[:i] = reversed(x[:i])
    x[i:] = reversed(x[i:])
    x[:] = reversed(x)
    return x

Demo:

>>> def rotate(x, i):
...     i %= len(x)
...     x[:i] = reversed(x[:i])
...     x[i:] = reversed(x[i:])
...     x[:] = reversed(x)
...     return x
... 
>>> rotate(list('abcdefgh'), 1)
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'a']
>>> rotate(list('abcdefgh'), 3)
['d', 'e', 'f', 'g', 'h', 'a', 'b', 'c']
>>> rotate(list('abcdefgh'), 8)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> rotate(list('abcdefgh'), 9)
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'a']

How to open child forms positioned within MDI parent in VB.NET?

Try Making the Child Form's StartPosition Property set to Center Parent. This you can select from the form Properties.

Loading state button in Bootstrap 3

You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.

$("button").click(function() {
    var $btn = $(this);
    $btn.button('loading');
    // simulating a timeout
    setTimeout(function () {
        $btn.button('reset');
    }, 1000);
});

Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.

JSFIDDLE

Official Documentation

How do you remove duplicates from a list whilst preserving order?

If you routinely use pandas, and aesthetics is preferred over performance, then consider the built-in function pandas.Series.drop_duplicates:

    import pandas as pd
    import numpy as np

    uniquifier = lambda alist: pd.Series(alist).drop_duplicates().tolist()

    # from the chosen answer 
    def f7(seq):
        seen = set()
        seen_add = seen.add
        return [ x for x in seq if not (x in seen or seen_add(x))]

    alist = np.random.randint(low=0, high=1000, size=10000).tolist()

    print uniquifier(alist) == f7(alist)  # True

Timing:

    In [104]: %timeit f7(alist)
    1000 loops, best of 3: 1.3 ms per loop
    In [110]: %timeit uniquifier(alist)
    100 loops, best of 3: 4.39 ms per loop