Programs & Examples On #Proxy authentication

The remote server returned an error: (407) Proxy Authentication Required

Just add this to config

<system.net>
    <defaultProxy useDefaultCredentials="true" >
    </defaultProxy>
</system.net>

Visual Studio Error: (407: Proxy Authentication Required)

I was getting an "authenticationrequired" (407) error when clicking the [Sync] button (using the MS Git Provider), and this worked for me (VS 2013):

..\Program Files\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe.config

  <system.net>
    <defaultProxy useDefaultCredentials="true" enabled="true">
      <proxy proxyaddress="http://username:password@proxyip:port" />
    </defaultProxy>
    <settings>
      <ipv6 enabled="false"/>
      <servicePointManager expect100Continue="false"/>
    </settings>
  </system.net>

I think the magic for me was setting 'ipv6' to 'false' - not sure why (perhaps only IPv4 is supported in my case). I tried other ways as shown above, but I move the "settings" section AFTER "defaultProxy", and changed "ipv6", and it worked perfectly with my login added (every other way I tried in all other answers posted just failed for me).

Edit: Just found another work around (without changing the config file). For some reason, if I disable the windows proxy (it's a URL to a PAC file in my case), try again (it will fail), and re-enable the proxy, it works. Seems to cache something internally that gets reset when I do this (at least in my case).

how to setup ssh keys for jenkins to publish via ssh

For Windows:

  1. Install the necessary plugins for the repository (ex: GitHub install GitHub and GitHub Authentication plugins) in Jenkins.
  2. You can generate a key with Putty key generator, or by running the following command in git bash: $ ssh-keygen -t rsa -b 4096 -C [email protected]
  3. Private key must be OpenSSH. You can convert your private key to OpenSSH in putty key generator
  4. SSH keys come in pairs, public and private. Public keys are inserted in the repository to be cloned. Private keys are saved as credentials in Jenkins
  5. You need to copy the SSH URL not the HTTPS to work with ssh keys.

How to use the toString method in Java?

The toString() method returns a textual representation of an object. A basic implementation is already included in java.lang.Object and so because all objects inherit from java.lang.Object it is guaranteed that every object in Java has this method.

Overriding the method is always a good idea, especially when it comes to debugging, because debuggers often show objects by the result of the toString() method. So use a meaningful implementation but use it for technical purposes. The application logic should use getters:

public class Contact {
  private String firstName;
  private String lastName;
  public Contact (String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  public String getFirstName() {return firstName;}
  public String getLastName() {return lastName;}

  public String getContact() {
    return firstName + " " + lastName;
  }

  @Override
  public String toString() {
    return "["+getContact()+"]";
  }
}

jquery drop down menu closing by clicking outside

Stopping Event Propagation in some particular elements ma y become dangerous as it may prevent other some scripts from running. So check whether the triggering is from the excluded area from inside the function.

$(document).on('click', function(event) {
  if (!$(event.target).closest('#menucontainer').length) {
    // Hide the menus.
  }
});

Here function is initiated when clicking on document, but it excludes triggering from #menucontainer. For details https://css-tricks.com/dangers-stopping-event-propagation/

Removing all line breaks and adding them after certain text

You need to that in two steps, at least.

First, click on the ¶ symbol in the toolbar: you can see if you have CRLF line endings or just LF.

Click on the Replace button, and put \r\n or \n, depending on the kind of line ending. In the Search Mode section of the dialog, check Extended radio button (interpret \n and such). Then replace all occurrences with nothing (empty string).

You end with a big line...

Next, in the same Replace dialog, put your delimiter (</Row>) for example and in the Replace With field, put the same with a line ending (</Row>\r\n). Replace All, and you are done.

Javascript onHover event

Can you clarify your question? What is "ohHover" in this case and how does it correspond to a delay in hover time?

That said, I think what you probably want is...

var timeout;
element.onmouseover = function(e) {
    timeout = setTimeout(function() {
        // ...
    }, delayTimeMs)
};
element.onmouseout = function(e) {
    if(timeout) {
        clearTimeout(timeout);
    }
};

Or addEventListener/attachEvent or your favorite library's event abstraction method.

Android : Capturing HTTP Requests with non-rooted android device

SandroProxy seems to be better than Drony (by the same developer): You can (but do not have to) conveniently view and analyze the traffic in your PC's browser.

Should work in emulators as well.

Python and JSON - TypeError list indices must be integers not str

I solved changing

readable_json['firstName']

by

readable_json[0]['firstName']

What is the difference between require() and library()?

Another benefit of require() is that it returns a logical value by default. TRUE if the packages is loaded, FALSE if it isn't.

> test <- library("abc")
Error in library("abc") : there is no package called 'abc'
> test
Error: object 'test' not found
> test <- require("abc")
Loading required package: abc
Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called 'abc'
> test
[1] FALSE

So you can use require() in constructions like the one below. Which mainly handy if you want to distribute your code to our R installation were packages might not be installed.

if(require("lme4")){
    print("lme4 is loaded correctly")
} else {
    print("trying to install lme4")
    install.packages("lme4")
    if(require(lme4)){
        print("lme4 installed and loaded")
    } else {
        stop("could not install lme4")
    }
}

Redirecting to URL in Flask

its pretty easy if u just want to redirect to a url without any status codes or anything like that u can simple say

from flask import Flask, redirect

app = Flask(__name__)

@app.route('/')
def redirect_to_link():
    # return redirect method, NOTE: replace google.com with the link u want
    return redirect('https://google.com')

here is the link to the Flask Docs for more explanation

Multi-dimensional arrays in Bash

Independent of the shell being used (sh, ksh, bash, ...) the following approach works pretty well for n-dimensional arrays (the sample covers a 2-dimensional array).

In the sample the line-separator (1st dimension) is the space character. For introducing a field separator (2nd dimension) the standard unix tool tr is used. Additional separators for additional dimensions can be used in the same way.

Of course the performance of this approach is not very well, but if performance is not a criteria this approach is quite generic and can solve many problems:

array2d="1.1:1.2:1.3 2.1:2.2 3.1:3.2:3.3:3.4"

function process2ndDimension {
    for dimension2 in $*
    do
        echo -n $dimension2 "   "
    done
    echo
}

function process1stDimension {
    for dimension1 in $array2d
    do
        process2ndDimension `echo $dimension1 | tr : " "`
    done
}

process1stDimension

The output of that sample looks like this:

1.1     1.2     1.3     
2.1     2.2     
3.1     3.2     3.3     3.4 

Reordering Chart Data Series

Right-click any series on the chart. In the "Format Data Series" dialog, there is a "Series Order" tab, in which you can move series up and down. I find this much easier than fiddling with the last argument of the series formula.

This is in Excel 2003 in Windows. There is a similar dialog in Excel 2011 for Mac:

enter image description here

How to fast-forward a branch to head?

In your case, to fast-forward, run:

$ git merge --ff-only origin/master

This uses the --ff-only option of git merge, as the question specifically asks for "fast-forward".

Here is an excerpt from git-merge(1) that shows more fast-forward options:

--ff, --no-ff, --ff-only
    Specifies how a merge is handled when the merged-in history is already a descendant of the current history.  --ff is the default unless merging an annotated
    (and possibly signed) tag that is not stored in its natural place in the refs/tags/ hierarchy, in which case --no-ff is assumed.

    With --ff, when possible resolve the merge as a fast-forward (only update the branch pointer to match the merged branch; do not create a merge commit). When
    not possible (when the merged-in history is not a descendant of the current history), create a merge commit.

    With --no-ff, create a merge commit in all cases, even when the merge could instead be resolved as a fast-forward.

    With --ff-only, resolve the merge as a fast-forward when possible. When not possible, refuse to merge and exit with a non-zero status.

I fast-forward often enough that it warranted an alias:

$ git config --global alias.ff 'merge --ff-only @{upstream}'

Now I can run this to fast-forward:

$ git ff

Request exceeded the limit of 10 internal redirects due to probable configuration error

//Just add 

RewriteBase /
//after 
RewriteEngine On

//and you are done....

//so it should be 

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

Simple export and import of a SQLite database on Android

I use this code in the SQLiteOpenHelper in one of my applications to import a database file.

EDIT: I pasted my FileUtils.copyFile() method into the question.

SQLiteOpenHelper

public static String DB_FILEPATH = "/data/data/{package_name}/databases/database.db";

/**
 * Copies the database file at the specified location over the current
 * internal application database.
 * */
public boolean importDatabase(String dbPath) throws IOException {

    // Close the SQLiteOpenHelper so it will commit the created empty
    // database to internal storage.
    close();
    File newDb = new File(dbPath);
    File oldDb = new File(DB_FILEPATH);
    if (newDb.exists()) {
        FileUtils.copyFile(new FileInputStream(newDb), new FileOutputStream(oldDb));
        // Access the copied database so SQLiteHelper will cache it and mark
        // it as created.
        getWritableDatabase().close();
        return true;
    }
    return false;
}

FileUtils

public class FileUtils {
    /**
     * Creates the specified <code>toFile</code> as a byte for byte copy of the
     * <code>fromFile</code>. If <code>toFile</code> already exists, then it
     * will be replaced with a copy of <code>fromFile</code>. The name and path
     * of <code>toFile</code> will be that of <code>toFile</code>.<br/>
     * <br/>
     * <i> Note: <code>fromFile</code> and <code>toFile</code> will be closed by
     * this function.</i>
     * 
     * @param fromFile
     *            - FileInputStream for the file to copy from.
     * @param toFile
     *            - FileInputStream for the file to copy to.
     */
    public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
        FileChannel fromChannel = null;
        FileChannel toChannel = null;
        try {
            fromChannel = fromFile.getChannel();
            toChannel = toFile.getChannel();
            fromChannel.transferTo(0, fromChannel.size(), toChannel);
        } finally {
            try {
                if (fromChannel != null) {
                    fromChannel.close();
                }
            } finally {
                if (toChannel != null) {
                    toChannel.close();
                }
            }
        }
    }
}

Don't forget to delete the old database file if necessary.

Comparing double values in C#

double and Double are the same (double is an alias for Double) and can be used interchangeably.

The problem with comparing a double with another value is that doubles are approximate values, not exact values. So when you set x to 0.1 it may in reality be stored as 0.100000001 or something like that.

Instead of checking for equality, you should check that the difference is less than a defined minimum difference (tolerance). Something like:

if (Math.Abs(x - 0.1) < 0.0000001)
{
    ...
}

pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

I'm guessing you have two python installs, or two pip installs, one of which has been partially removed.

Why do you use sudo? Ideally you should be able to install and run everything from your user account instead of using root. If you mix root and your local account together you are more likely to run into permissions issues (e.g. see the warning it gives about "parent directory is not owned by the current user").

What do you get if you run this?

$ head -n1 /usr/local/bin/pip

This will show you which python binary pip is trying to use. If it's pointing /usr/local/opt/python/bin/python2.7, then try running this:

$ ls -al /usr/local/opt/python/bin/python2.7

If this says "No such file or directory", then pip is trying to use a python binary that has been removed.

Next, try this:

$ which python
$ which python2.7

To see the path of the python binary that's actually working.

Since it looks like pip was successfully installed somewhere, it could be that /usr/local/bin/pip is part of an older installation of pip that's higher up on the PATH. To test that, you may try moving the non-functioning pip binary out of the way like this (might require sudo):

$ mv /usr/local/bin/pip /usr/local/bin/pip.old

Then try running your pip --version command again. Hopefully it picks up the correct version and runs successfully.

How to write a multiline command?

After trying almost every key on my keyboard:

C:\Users\Tim>cd ^
Mehr? Desktop

C:\Users\Tim\Desktop>

So it seems to be the ^ key.

loop through json array jquery

you could also change from the .get() method to the .getJSON() method, jQuery will then parse the string returned as data to a javascript object and/or array that you can then reference like any other javascript object/array.

using your code above, if you changed .get to .getJSON, you should get an alert of [object Object] for each element in the array. If you changed the alert to alert(item.name) you will get the names.

JQuery: dynamic height() with window resize()

The cleanest solution - also purely CSS - would be using calc and vh.

The middle div's heigh will be calculated thusly:

#middle-div { 
height: calc(100vh - 46px); 
}

That is, 100% of the viewport height minus the 2*23px. This will ensure that the page loads properly and is dynamic(demo here).

Also remember to use box-sizing, so the paddings and borders don't make the divs outfill the viewport.

How do you cache an image in Javascript

Yes, the browser caches images for you, automatically.

You can, however, set an image cache to expire. Check out this Stack Overflow questions and answer:

Cache Expiration On Static Images

Why does configure say no C compiler found when GCC is installed?

Install GCC in Ubuntu Debian Base

sudo apt-get install build-essential

Test if number is odd or even

Check Even Or Odd Number Without Use Condition And Loop Statement.

This work for me..!

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $("#btn_even_odd").click(function(){_x000D_
        var arr = ['Even','Odd'];_x000D_
        var num_even_odd = $("#num_even_odd").val();_x000D_
        $("#ans_even_odd").html(arr[num_even_odd % 2]);_x000D_
    });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
    <title>Check Even Or Odd Number Without Use Condition And Loop Statement.</title>_x000D_
</head>_x000D_
<body>_x000D_
<h4>Check Even Or Odd Number Without Use Condition And Loop Statement.</h4>_x000D_
<table>_x000D_
    <tr>_x000D_
        <th>Enter A Number :</th>_x000D_
        <td><input type="text" name="num_even_odd" id="num_even_odd" placeholder="Enter Only Number"></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <th>Your Answer Is :</th>_x000D_
        <td id="ans_even_odd" style="font-size:15px;color:gray;font-weight:900;"></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td><input type="button" name="btn_even_odd" id="btn_even_odd" value="submit"></td>_x000D_
    </tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Certificate is trusted by PC but not by Android

I encountered this same issue under Apache 2.2 when I was trying to use multiple SSLCertificateChainFile directives for each intermediate cert; instead I needed to concatenate all three into a single file. Coming from GoDaddy where they'd done this for me as a "bundle" this extra step was new to me, but a re-reading of the Apache documentation made this apparent.

Worth noting, this directive is deprecated as of Apache 2.4.8 since you can now concatenate all the intermediates with the actual cert.

Check if enum exists in Java

If I need to do this, I sometimes build a Set<String> of the names, or even my own Map<String,MyEnum> - then you can just check that.

A couple of points worth noting:

  • Populate any such static collection in a static initializer. Don't use a variable initializer and then rely on it having been executed when the enum constructor runs - it won't have been! (The enum constructors are the first things to be executed, before the static initializer.)
  • Try to avoid using values() frequently - it has to create and populate a new array each time. To iterate over all elements, use EnumSet.allOf which is much more efficient for enums without a large number of elements.

Sample code:

import java.util.*;

enum SampleEnum {
    Foo,
    Bar;

    private static final Map<String, SampleEnum> nameToValueMap =
        new HashMap<String, SampleEnum>();

    static {
        for (SampleEnum value : EnumSet.allOf(SampleEnum.class)) {
            nameToValueMap.put(value.name(), value);
        }
    }

    public static SampleEnum forName(String name) {
        return nameToValueMap.get(name);
    }
}

public class Test {
    public static void main(String [] args)
        throws Exception { // Just for simplicity!
        System.out.println(SampleEnum.forName("Foo"));
        System.out.println(SampleEnum.forName("Bar"));
        System.out.println(SampleEnum.forName("Baz"));
    }
}

Of course, if you only have a few names this is probably overkill - an O(n) solution often wins over an O(1) solution when n is small enough. Here's another approach:

import java.util.*;

enum SampleEnum {
    Foo,
    Bar;

    // We know we'll never mutate this, so we can keep
    // a local copy.
    private static final SampleEnum[] copyOfValues = values();

    public static SampleEnum forName(String name) {
        for (SampleEnum value : copyOfValues) {
            if (value.name().equals(name)) {
                return value;
            }
        }
        return null;
    }
}

public class Test {
    public static void main(String [] args)
        throws Exception { // Just for simplicity!
        System.out.println(SampleEnum.forName("Foo"));
        System.out.println(SampleEnum.forName("Bar"));
        System.out.println(SampleEnum.forName("Baz"));
    }
}

JAVA_HOME and PATH are set but java -version still shows the old one

If you want to use JDKs downloaded from Oracle's site, what worked for me (using Mint) is using update-alternatives:

  1. I downloaded the JDK and extracted it just anywhere, for example in /home/aqeel/development/jdk/jdk1.6.0_35
  2. I ran:

    sudo update-alternatives --install /usr/bin/java java /home/aqeel/development/jdk/jdk1.6.0_35/bin/java 1
    

    Now you can execute sudo update-alternatives --config java and choose your java version.

  3. This doesn't set the JAVA_HOME variable, which I wanted configured, so I just added it to my ~/.bashrc, including an export JAVA_HOME="/home/aqeel/development/jdk/jdk1.6.0_35" statement

Now, I had two JDKs downloaded (let's say the second has been extracted to /home/aqeel/development/jdk/jdk-10.0.1).

How can we change the JAVA_HOME dynamically based on the current java being used?

My solution is not very elegant, I'm pretty sure there are better options out there, but anyway:

  1. To change the JAVA_HOME dynamically based on the chosen java alternative, I added this snippet to the ~/.bashrc:

    export JAVA_HOME=$(update-alternatives --query java | grep Value: | awk -F'Value: ' '{print $2}' | awk -F'/bin/java' '{print $1}')
    

Finally (this is out of the scope) if you have to change the java version constantly, you might want to consider:

  1. Adding an alias to your ~./bash_aliases:

    alias change-java="sudo update-alternatives --config java"
    

(You might have to create the file and maybe uncomment the section related to this in ~/.bashrc)

SQL Server: Invalid Column Name

I was getting the same error when creating a view.

Imagine a select query that executes without issue:

select id
from products

Attempting to create a view from the same query would produce an error:

create view app.foobar as
select id
from products

Msg 207, Level 16, State 1, Procedure foobar, Line 2
Invalid column name 'id'.

For me it turned out to be a scoping issue; note the view is being created in a different schema. Specifying the schema of the products table solved the issue. Ie.. using dbo.products instead of just products.

Querying Windows Active Directory server using ldapsearch from command line

You could query an LDAP server from the command line with ldap-utils: ldapsearch, ldapadd, ldapmodify

Storing a file in a database as opposed to the file system?

I agree with @ZombieSheep. Just one more thing - I generally don't think that databases actually need be portable because you miss all the features your DBMS vendor provides. I think that migrating to another database would be the last thing one would consider. Just my $.02

How do I dynamically change the content in an iframe using jquery?

<html>
  <head>
    <script type="text/javascript" src="jquery.js"></script>
    <script>
      $(document).ready(function(){
        var locations = ["http://webPage1.com", "http://webPage2.com"];
        var len = locations.length;
        var iframe = $('#frame');
        var i = 0;
        setInterval(function () {
            iframe.attr('src', locations[++i % len]);
        }, 30000);
      });
    </script>
  </head>
  <body>
    <iframe id="frame"></iframe>
  </body>
</html>

How to display custom view in ActionBar?

This is how it worked for me (from above answers it was showing both default title and my custom view also).

ActionBar.LayoutParams layout = new ActionBar.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
// actionBar.setCustomView(view); //last view item must set to android:layout_alignParentRight="true" if few views are there 
actionBar.setCustomView(view, layout); // layout param width=fill/match parent
actionBar.setDisplayShowCustomEnabled(true);//must other wise its not showing custom view.

What I noticed is that both setCustomView(view) and setCustomView(view,params) the view width=match/fill parent. setDisplayShowCustomEnabled (boolean showCustom)

Invalid date in safari

Arriving late to the party but in our case we were getting this issue in Safari & iOS when using ES6 back tick instead of String() to type cast

This was giving 'invalid date' error

const dateString = '2011-11-18';
const dateObj = new Date(`${dateString}`); 

But this works

const dateObj = new Date(String(dateString)); 

Count how many files in directory PHP

$it = new filesystemiterator(dirname("Enter directory here"));
printf("There were %d Files", iterator_count($it));
echo("<br/>");
    foreach ($it as $fileinfo) {
        echo $fileinfo->getFilename() . "<br/>\n";
    } 

This should work enter the directory in dirname. and let the magic happen.

SQL to Entity Framework Count Group-By

A useful extension is to collect the results in a Dictionary for fast lookup (e.g. in a loop):

var resultDict = _dbContext.Projects
    .Where(p => p.Status == ProjectStatus.Active)
    .GroupBy(f => f.Country)
    .Select(g => new { country = g.Key, count = g.Count() })
    .ToDictionary(k => k.country, i => i.count);

Originally found here: http://www.snippetsource.net/Snippet/140/groupby-and-count-with-ef-in-c

Check for internet connection with Swift

Create a new Swift file within your project, name it Reachability.swift. Cut & paste the following code into it to create your class.

import Foundation
import SystemConfiguration

open class Reachability {
    
    class func isConnectedToNetwork() -> Bool {
        
        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)
        
        let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
                SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
            }
        }
        
        var flags = SCNetworkReachabilityFlags()
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
            return false
        }
        let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
        let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
        return (isReachable && !needsConnection)
    }
}

you can call Reachability from anywhere of your code, just like

if Reachability.isConnectedToNetwork() {
    print("Network is connected")
} else {
    print("Network is not connected")
}

CMake unable to determine linker language with C++

I also got the error you mention:

CMake Error: CMake can not determine linker language for target:helloworld
CMake Error: Cannot determine link language for target "helloworld".

In my case this was due to having C++ files with the .cc extension.

If CMake is unable to determine the language of the code correctly you can use the following:

set_target_properties(hello PROPERTIES LINKER_LANGUAGE CXX)

The accepted answer that suggests appending the language to the project() statement simply adds more strict checking for what language is used (according to the documentation), but it wasn't helpful to me:

Optionally you can specify which languages your project supports. Example languages are CXX (i.e. C++), C, Fortran, etc. By default C and CXX are enabled. E.g. if you do not have a C++ compiler, you can disable the check for it by explicitly listing the languages you want to support, e.g. C. By using the special language "NONE" all checks for any language can be disabled. If a variable exists called CMAKE_PROJECT__INCLUDE_FILE, the file pointed to by that variable will be included as the last step of the project command.

How to get first/top row of the table in Sqlite via Sql Query

Use the following query:

SELECT * FROM SAMPLE_TABLE ORDER BY ROWID ASC LIMIT 1

Note: Sqlite's row id references are detailed here.

How to call Android contacts list?

public void onActivityResult(int requestCode, int resultCode, Intent intent) 
{
  if (requestCode == PICK_CONTACT && intent != null) //here check whether intent is null R not
  {  
  }
}

because without selecting any contact it will give an exception. so better to check this condition.

Adding a custom header to HTTP request using angular.js

You are just adding a header which server does not allow.

eg - your server is set up CORS to allow these headers only (accept,cache-control,pragma,content-type,origin)

and in your http request you are adding like this

 headers: {
        'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
        'Accept': 'application/json',
        'x-testing': 'testingValue'
    }

then the Server will reject this request since (Authorization and x-testing) are not allowed.

This is server side configuration.

And there is nothing to do with HTTP Options, it is just a preflight to server which is from different domain to check if server will allow actual call or not.

MIME types missing in IIS 7 for ASP.NET - 404.17

Fix:

I chose the "ISAPI & CGI Restrictions" after clicking the server name (not the site name) in IIS Manager, and right clicked the "ASP.NET v4.0.30319" lines and chose "Allow".

After turning on ASP.NET from "Programs and Features > Turn Windows features on or off", you must install ASP.NET from the Windows command prompt. The MIME types don't ever show up, but after doing this command, I noticed these extensions showed up under the IIS web site "Handler Mappings" section of IIS Manager.

C:\>cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>dir aspnet_reg*
 Volume in drive C is Windows
 Volume Serial Number is 8EE6-5DD0

 Directory of C:\Windows\Microsoft.NET\Framework64\v4.0.30319

03/18/2010  08:23 PM            19,296 aspnet_regbrowsers.exe
03/18/2010  08:23 PM            36,696 aspnet_regiis.exe
03/18/2010  08:23 PM           102,232 aspnet_regsql.exe
               3 File(s)        158,224 bytes
               0 Dir(s)  34,836,508,672 bytes free

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i
Start installing ASP.NET (4.0.30319).
.....
Finished installing ASP.NET (4.0.30319).

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>

However, I still got this error. But if you do what I mentioned for the "Fix", this will go away.

HTTP Error 404.2 - Not Found
The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.

No content to map due to end-of-input jackson parser

I know this is weird but when I changed GetMapping to PostMapping for both client and server side the error disappeared.

Both client and server are Spring boot projects.

How do I purge a linux mail box with huge number of emails?

On UNIX / Linux / Mac OS X you can copy and override files, can't you? So how about this solution:

cp /dev/null /var/mail/root

Go Back to Previous Page

Like this:

<?php

    if (isset($_SERVER["HTTP_REFERER"])) {
        header("Location: " . $_SERVER["HTTP_REFERER"]);
    }

?>

Hive load CSV with commas in quoted fields

ORG.APACHE.HADOOP.HIVE.SERDE2.OPENCSVSERDE Serde worked for me. My delimiter was '|' and one of the columns is enclosed in double quotes.

Query:

CREATE EXTERNAL TABLE EMAIL(MESSAGE_ID STRING, TEXT STRING, TO_ADDRS STRING, FROM_ADDRS STRING, SUBJECT STRING, DATE STRING)
ROW FORMAT SERDE 'ORG.APACHE.HADOOP.HIVE.SERDE2.OPENCSVSERDE'
WITH SERDEPROPERTIES (
     "SEPARATORCHAR" = "|",
     "QUOTECHAR"     = "\"",
     "ESCAPECHAR"    = "\""
)    
STORED AS TEXTFILE location '/user/abc/csv_folder';

Convert unix time stamp to date in java

You can use SimlpeDateFormat to format your date like this:

long unixSeconds = 1372339860;
// convert seconds to milliseconds
Date date = new java.util.Date(unixSeconds*1000L); 
// the format of your date
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); 
// give a timezone reference for formatting (see comment at the bottom)
sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4")); 
String formattedDate = sdf.format(date);
System.out.println(formattedDate);

The pattern that SimpleDateFormat takes if very flexible, you can check in the javadocs all the variations you can use to produce different formatting based on the patterns you write given a specific Date. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

  • Because a Date provides a getTime() method that returns the milliseconds since EPOC, it is required that you give to SimpleDateFormat a timezone to format the date properly acording to your timezone, otherwise it will use the default timezone of the JVM (which if well configured will anyways be right)

How to create an empty array in PHP with predefined size?

PHP Arrays don't need to be declared with a size.

An array in PHP is actually an ordered map

You also shouldn't get a warning/notice using code like the example you have shown. The common Notice people get is "Undefined offset" when reading from an array.

A way to counter this is to check with isset or array_key_exists, or to use a function such as:

function isset_or($array, $key, $default = NULL) {
    return isset($array[$key]) ? $array[$key] : $default;
}

So that you can avoid the repeated code.

Note: isset returns false if the element in the array is NULL, but has a performance gain over array_key_exists.

If you want to specify an array with a size for performance reasons, look at:

SplFixedArray in the Standard PHP Library.

ngOnInit not being called when Injectable class is Instantiated

Note: this answer applies only to Angular components and directives, NOT services.

I had this same issue when ngOnInit (and other lifecycle hooks) were not firing for my components, and most searches led me here.

The issue is that I was using the arrow function syntax (=>) like this:

class MyComponent implements OnInit {
    // Bad: do not use arrow function
    public ngOnInit = () => {
        console.log("ngOnInit");
    }
}

Apparently that does not work in Angular 6. Using non-arrow function syntax fixes the issue:

class MyComponent implements OnInit {
    public ngOnInit() {
        console.log("ngOnInit");
    }
}

Android get current Locale, not default

As per official documentation ConfigurationCompat is deprecated in support libraries

You can consider using

LocaleListCompat.getDefault()[0].toLanguageTag() 0th position will be user preferred locale

To get Default locale at 0th position would be LocaleListCompat.getAdjustedDefault()

Python: What OS am I running on?

in the same vein....

import platform
is_windows=(platform.system().lower().find("win") > -1)

if(is_windows): lv_dll=LV_dll("my_so_dll.dll")
else:           lv_dll=LV_dll("./my_so_dll.so")

Environment variable to control java.io.tmpdir?

According to the java.io.File Java Docs

The default temporary-file directory is specified by the system property java.io.tmpdir. On UNIX systems the default value of this property is typically "/tmp" or "/var/tmp"; on Microsoft Windows systems it is typically "c:\temp". A different value may be given to this system property when the Java virtual machine is invoked, but programmatic changes to this property are not guaranteed to have any effect upon the the temporary directory used by this method.

To specify the java.io.tmpdir System property, you can invoke the JVM as follows:

java -Djava.io.tmpdir=/path/to/tmpdir

By default this value should come from the TMP environment variable on Windows systems

Dynamic creation of table with DOM

You need to create new TextNodes as well as td nodes for each column, not reuse them among all of the columns as your code is doing.

Edit: Revise your code like so:

for (var i = 1; i < 4; i++)
{
   tr[i] = document.createElement('tr');   
      var td1 = document.createElement('td');
      var td2 = document.createElement('td');
      td1.appendChild(document.createTextNode('Text1'));
      td2.appendChild(document.createTextNode('Text2'));
      tr[i].appendChild(td1);
      tr[i].appendChild(td2);
  table.appendChild(tr[i]);
}

How to download a file over HTTP?

You can get the progress feedback with urlretrieve as well:

def report(blocknr, blocksize, size):
    current = blocknr*blocksize
    sys.stdout.write("\r{0:.2f}%".format(100.0*current/size))

def downloadFile(url):
    print "\n",url
    fname = url.split('/')[-1]
    print fname
    urllib.urlretrieve(url, fname, report)

html5 input for money/currency

I stumbled across this article looking for a similar answer. I read @vsync example Using javascript's Number.prototype.toLocaleString: and it appeared to work well. The only complaint I had was that if you had more than a single input type="currency" within your page it would only modify the first instance of it.

As he mentions in his comments it was only designed as an example for stackoverflow.

However, the example worked well for me and although I have little experience with JS I figured out how to modify it so that it will work with multiple input type="currency" on the page using the document.querySelectorAll rather than document.querySelector and adding a for loop.

I hope this can be useful for someone else. ( Credit for the bulk of the code is @vsync )

var currencyInput = document.querySelectorAll( 'input[type="currency"]' );

for ( var i = 0; i < currencyInput.length; i++ ) {

    var currency = 'GBP'
    onBlur( {
        target: currencyInput[ i ]
    } )

    currencyInput[ i ].addEventListener( 'focus', onFocus )
    currencyInput[ i ].addEventListener( 'blur', onBlur )

    function localStringToNumber( s ) {
        return Number( String( s ).replace( /[^0-9.-]+/g, "" ) )
    }

    function onFocus( e ) {
        var value = e.target.value;
        e.target.value = value ? localStringToNumber( value ) : ''
    }

    function onBlur( e ) {
        var value = e.target.value

        var options = {
            maximumFractionDigits: 2,
            currency: currency,
            style: "currency",
            currencyDisplay: "symbol"
        }

        e.target.value = ( value || value === 0 ) ?
            localStringToNumber( value ).toLocaleString( undefined, options ) :
            ''
    }
}

_x000D_
_x000D_
    var currencyInput = document.querySelectorAll( 'input[type="currency"]' );

    for ( var i = 0; i < currencyInput.length; i++ ) {

        var currency = 'GBP'
        onBlur( {
            target: currencyInput[ i ]
        } )

        currencyInput[ i ].addEventListener( 'focus', onFocus )
        currencyInput[ i ].addEventListener( 'blur', onBlur )

        function localStringToNumber( s ) {
            return Number( String( s ).replace( /[^0-9.-]+/g, "" ) )
        }

        function onFocus( e ) {
            var value = e.target.value;
            e.target.value = value ? localStringToNumber( value ) : ''
        }

        function onBlur( e ) {
            var value = e.target.value

            var options = {
                maximumFractionDigits: 2,
                currency: currency,
                style: "currency",
                currencyDisplay: "symbol"
            }

            e.target.value = ( value || value === 0 ) ?
                localStringToNumber( value ).toLocaleString( undefined, options ) :
                ''
        }
    }
_x000D_
.input_date {
    margin:1px 0px 50px 0px;
    font-family: 'Roboto', sans-serif;
    font-size: 18px;
    line-height: 1.5;
    color: #111;
    display: block;
    background: #ddd;
    height: 50px;
    border-radius: 5px;
    border: 2px solid #111111;
    padding: 0 20px 0 20px;
    width: 100px;
}
_x000D_
    <label for="cost_of_sale">Cost of Sale</label>
    <input class="input_date" type="currency" name="cost_of_sale" id="cost_of_sale" value="0.00">

    <label for="sales">Sales</label>
    <input class="input_date" type="currency" name="sales" id="sales" value="0.00">

     <label for="gm_pounds">GM Pounds</label>
     <input class="input_date" type="currency" name="gm_pounds" id="gm_pounds" value="0.00">
_x000D_
_x000D_
_x000D_

Update MongoDB field using value of another field

I tried the above solution but I found it unsuitable for large amounts of data. I then discovered the stream feature:

MongoClient.connect("...", function(err, db){
    var c = db.collection('yourCollection');
    var s = c.find({/* your query */}).stream();
    s.on('data', function(doc){
        c.update({_id: doc._id}, {$set: {name : doc.firstName + ' ' + doc.lastName}}, function(err, result) { /* result == true? */} }
    });
    s.on('end', function(){
        // stream can end before all your updates do if you have a lot
    })
})

How do I calculate someone's age based on a DateTime type birthday?

I think the TimeSpan has all that we need in it, without having to resort to 365.25 (or any other approximation). Expanding on Aug's example:

DateTime myBD = new DateTime(1980, 10, 10);
TimeSpan difference = DateTime.Now.Subtract(myBD);

textBox1.Text = difference.Years + " years " + difference.Months + " Months " + difference.Days + " days";

JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

For those who have a file from an input control, don't know what its orientation is, are a bit lazy and don't want to include a large library below is the code provided by @WunderBart melded with the answer he links to (https://stackoverflow.com/a/32490603) that finds the orientation.

function getDataUrl(file, callback2) {
        var callback = function (srcOrientation) {
            var reader2 = new FileReader();
            reader2.onload = function (e) {
                var srcBase64 = e.target.result;
                var img = new Image();

                img.onload = function () {
                    var width = img.width,
                        height = img.height,
                        canvas = document.createElement('canvas'),
                        ctx = canvas.getContext("2d");

                    // set proper canvas dimensions before transform & export
                    if (4 < srcOrientation && srcOrientation < 9) {
                        canvas.width = height;
                        canvas.height = width;
                    } else {
                        canvas.width = width;
                        canvas.height = height;
                    }

                    // transform context before drawing image
                    switch (srcOrientation) {
                        case 2: ctx.transform(-1, 0, 0, 1, width, 0); break;
                        case 3: ctx.transform(-1, 0, 0, -1, width, height); break;
                        case 4: ctx.transform(1, 0, 0, -1, 0, height); break;
                        case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
                        case 6: ctx.transform(0, 1, -1, 0, height, 0); break;
                        case 7: ctx.transform(0, -1, -1, 0, height, width); break;
                        case 8: ctx.transform(0, -1, 1, 0, 0, width); break;
                        default: break;
                    }

                    // draw image
                    ctx.drawImage(img, 0, 0);

                    // export base64
                    callback2(canvas.toDataURL());
                };

                img.src = srcBase64;
            }

            reader2.readAsDataURL(file);
        }

        var reader = new FileReader();
        reader.onload = function (e) {

            var view = new DataView(e.target.result);
            if (view.getUint16(0, false) != 0xFFD8) return callback(-2);
            var length = view.byteLength, offset = 2;
            while (offset < length) {
                var marker = view.getUint16(offset, false);
                offset += 2;
                if (marker == 0xFFE1) {
                    if (view.getUint32(offset += 2, false) != 0x45786966) return callback(-1);
                    var little = view.getUint16(offset += 6, false) == 0x4949;
                    offset += view.getUint32(offset + 4, little);
                    var tags = view.getUint16(offset, little);
                    offset += 2;
                    for (var i = 0; i < tags; i++)
                        if (view.getUint16(offset + (i * 12), little) == 0x0112)
                            return callback(view.getUint16(offset + (i * 12) + 8, little));
                }
                else if ((marker & 0xFF00) != 0xFF00) break;
                else offset += view.getUint16(offset, false);
            }
            return callback(-1);
        };
        reader.readAsArrayBuffer(file);
    }

which can easily be called like such

getDataUrl(input.files[0], function (imgBase64) {
      vm.user.BioPhoto = imgBase64;
});

How do I combine two data-frames based on two columns?

See the documentation on ?merge, which states:

By default the data frames are merged on the columns with names they both have, 
 but separate specifications of the columns can be given by by.x and by.y.

This clearly implies that merge will merge data frames based on more than one column. From the final example given in the documentation:

x <- data.frame(k1=c(NA,NA,3,4,5), k2=c(1,NA,NA,4,5), data=1:5)
y <- data.frame(k1=c(NA,2,NA,4,5), k2=c(NA,NA,3,4,5), data=1:5)
merge(x, y, by=c("k1","k2")) # NA's match

This example was meant to demonstrate the use of incomparables, but it illustrates merging using multiple columns as well. You can also specify separate columns in each of x and y using by.x and by.y.

Question mark and colon in statement. What does it mean?

It's a ternary operator, or the short form for if..else.

condition ? value if true : value if false

See Microsoft Docs | ?: operator (C# reference).

Different names of JSON property during serialization and deserialization

Annotating with @JsonAlias which got introduced with Jackson 2.9+, without mentioning @JsonProperty on the item to be deserialized with more than one alias(different names for a json property) works fine.

I used com.fasterxml.jackson.annotation.JsonAlias for package consistency with com.fasterxml.jackson.databind.ObjectMapper for my use-case.

For e.g.:

@Data
@Builder
public class Chair {

    @JsonAlias({"woodenChair", "steelChair"})
    private String entityType;

}


@Test
public void test1() {

   String str1 = "{\"woodenChair\":\"chair made of wood\"}";
   System.out.println( mapper.readValue(str1, Chair.class));
   String str2 = "{\"steelChair\":\"chair made of steel\"}";
   System.out.println( mapper.readValue(str2, Chair.class));

}

just works fine.

Does Python have an ordered set?

If you're using the ordered set to maintain a sorted order, consider using a sorted set implementation from PyPI. The sortedcontainers module provides a SortedSet for just this purpose. Some benefits: pure-Python, fast-as-C implementations, 100% unit test coverage, hours of stress testing.

Installing from PyPI is easy with pip:

pip install sortedcontainers

Note that if you can't pip install, simply pull down the sortedlist.py and sortedset.py files from the open-source repository.

Once installed you can simply:

from sortedcontainers import SortedSet
help(SortedSet)

The sortedcontainers module also maintains a performance comparison with several alternative implementations.

For the comment that asked about Python's bag data type, there's alternatively a SortedList data type which can be used to efficiently implement a bag.

Powershell: convert string to number

Simply divide the Variable containing Numbers as a string by 1. PowerShell automatically convert the result to an integer.

$a = 15; $b = 2; $a + $b --> 152

But if you divide it before:

$a/1 + $b/1 --> 17

Set default host and port for ng serve in config file

You can save these in a file, but you have to to put it in .ember-cli (at the moment, at least); see https://github.com/angular/angular-cli/issues/1156#issuecomment-227412924

{
"port": 4201,
"liveReload": true,
"host": "dev.domain.org",
"live-reload-port": 49153
}

edit: you can now set these in angular-cli.json as of commit https://github.com/angular/angular-cli/commit/da255b0808dcbe2f9da62086baec98dacc4b7ec9, which is in build 1.0.0-beta.30

How to change Java version used by TOMCAT?

When you open catalina.sh / catalina.bat, you can see :

Environment Variable Prequisites

JAVA_HOME Must point at your Java Development Kit installation.

So, set your environment variable JAVA_HOME to point to Java 6. Also make sure JRE_HOME is pointing to the same target, if it is set.

Update: since you are on Windows, see here for how to manage your environment variables

MySQL Update Inner Join tables query

For MySql WorkBench, Please use below :

update emp as a
inner join department b on a.department_id=b.id
set a.department_name=b.name
where a.emp_id in (10,11,12); 

Dynamic height for DIV

You should be okay to just take the height property out of the CSS.

json and empty array

The first version is a null object while the second is an Array object with zero elements.

Null may mean here for example that no location is available for that user, no location has been requested or that some restrictions apply. Hard to tell with no reference to the API.

Receiving login prompt using integrated windows authentication

I have a Windows 2008 server that I'm working on, so my answer is not completely the same as what the OP has on a Windows 2003 server.

Here is what I did (recording this here so I can find it later).

I was having this same issue:

login prompt

In my Web.config file, I had this section:

<system.web>
    <authentication mode="Windows" />
    <authorization>
        <allow users="*" />
        <deny users="?" />
    </authorization>
</system.web>

Under IIS, all of these seems to be solved under the Authentication icon.

  1. Edit Permissions: Make sure your ASP.NET account has permission. Mine was not originally added.

ASP.NET permission

Now go into the features of Authentication:

Authentication Features

Enable Anonymous Authentication with the IUSR:

Anonymous Authentication

Enable Windows Authentication, then Right-Click to set the Providers.

NTLM needs to be FIRST!

Windows Authentication

Next, check that under Advanced Settings... the Extended Protection is Accept and Enable Kernel-mode authentication is CHECKED:

Advanced Settings

Once I did this, I went back to my web application, clicked the Browse link, and logged in without having to provide my credentials again.

I hope this proves beneficial to many of you, and I hope it is useful for me later as well.

How does the class_weight parameter in scikit-learn work?

First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class. I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level) that you are interested in.

For how class_weight works: It penalizes mistakes in samples of class[i] with class_weight[i] instead of 1. So higher class-weight means you want to put more emphasis on a class. From what you say it seems class 0 is 19 times more frequent than class 1. So you should increase the class_weight of class 1 relative to class 0, say {0:.1, 1:.9}. If the class_weight doesn't sum to 1, it will basically change the regularization parameter.

For how class_weight="auto" works, you can have a look at this discussion. In the dev version you can use class_weight="balanced", which is easier to understand: it basically means replicating the smaller class until you have as many samples as in the larger one, but in an implicit way.

'"SDL.h" no such file or directory found' when compiling

For Simple Direct Media Layer 2 (SDL2), after installing it on Ubuntu 16.04 via:

sudo apt-get install libsdl2-dev

I used the header:

#include <SDL2/SDL.h>  

and the compiler linker command:

-lSDL2main -lSDL2 

Additionally, you may also want to install:

apt-get install libsdl2-image-dev  
apt-get install libsdl2-mixer-dev  
apt-get install libsdl2-ttf-dev  

With these headers:

#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_mixer.h>  

and the compiler linker commands:

-lSDL2_image 
-lSDL2_ttf 
-lSDL2_mixer

Search of table names

select name
  from DBname.sys.tables
 where name like '%xxx%'
   and is_ms_shipped = 0; -- << comment out if you really want to see them

Visual Studio 64 bit?

no, but it runs fine on win64, and can create win64 .EXEs

Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin

a number of answers; check out this one also; make sure that no instance of mysql is running, always brought by not ending your sessions well. get the super user rights with

sudo su

and type your password when prompted to (remember nothing appears when you type your password, so, don't worry just type it and press enter). Next go to your terminal and stop all mysql instances:

/etc/init.d/mysql stop

after that, go and restart the mysql services (or restart xampp as a whole). This solved my problem. All the best.

How do I validate a date string format in python?

I think the full validate function should look like this:

from datetime import datetime

def validate(date_text):
    try:
        if date_text != datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d'):
            raise ValueError
        return True
    except ValueError:
        return False

Executing just

datetime.strptime(date_text, "%Y-%m-%d") 

is not enough because strptime method doesn't check that month and day of the month are zero-padded decimal numbers. For example

datetime.strptime("2016-5-3", '%Y-%m-%d')

will be executed without errors.

Row numbers in query result using Microsoft Access

MS-Access doesn't support ROW_NUMBER(). Use TOP 1:

SELECT TOP 1 *
FROM [MyTable]
ORDER BY [MyIdentityCOlumn]

If you need the 15th row - MS-Access has no simple, built-in, way to do this. You can simulate the rownumber by using reverse nested ordering to get this:

SELECT TOP 1 *
FROM (
  SELECT TOP 15 *
  FROM [MyTable]
  ORDER BY [MyIdentityColumn] ) t
ORDER BY [MyIdentityColumn] DESC

Print an ArrayList with a for-each loop

import java.util.ArrayList;
import java.util.List;

class ArrLst{

    public static void main(String args[]){

        List l=new ArrayList();
        l.add(10);
        l.add(11);
        l.add(12);
        l.add(13);
        l.add(14);
        l.forEach((a)->System.out.println(a));
    }
}

How we can bold only the name in table td tag not the value

I would use to table header tag below for a text in a table to make it standout from the rest of the table content.

 <table>

    <tr>
     <th>Dimension:</th>
    <td>98cm x 71cm</td>
    </tr>
   </table

Parsing date string in Go

This is rather late to the party, and not really saying anything that hasn't been already said in one form or another, mostly through links above, but I wanted to give a TL;DR recap to those with less attention span:

The date and time of the go format string is very important. It's how Go knows which field is which. They are generally 1-9 left to right as follows:

  • January / Jan / january / jan / 01 / _1 (etc) are for month
  • 02 / _2 are for day of month
  • 15 / 03 / _3 / PM / P / pm /p are for hour & meridian (3pm)
  • 04 / _4 are for minutes
  • 05 / _5 are for seconds
  • 2006 / 06 are for year
  • -0700 / 07:00 / MST are for timezone
  • .999999999 / .000000000 etc are for partial seconds (I think the distinction is if trailing zeros are removed)
  • Mon / Monday are day of the week (which 01-02-2006 actually was),

So, Don't write "01-05-15" as your date format, unless you want "Month-Second-Hour"

(... again, this was basically a summary of above.)

How can I convert a comma-separated string to an array?

You can try the following snippet:

 var str = "How,are,you,doing,today?";
    var res = str.split(",");
    console.log("My Result:", res)

preventDefault() on an <a> tag

After several operations, when the page should finally go to <a href"..."> link you can do the following:

jQuery("a").click(function(e){
    var self = jQuery(this);
    var href = self.attr('href');
    e.preventDefault();
    // needed operations

    window.location = href;
});

align an image and some text on the same line without using div width?

I know this question is over 6 years old, but still, I would like to share my method using tables and this won't require any CSS.

<table><tr><td><img src="loading.gif"></td><td> Loading...</td></tr></table>

Cheers! Happy Coding

How do I get the project basepath in CodeIgniter

Obviously you mean the baseurl. If so:

base url: URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash.

Root in codeigniter specifically means that the position where you can append your controller to your url.

For example, if the root is localhost/ci_installation/index.php/, then to access the mycont controller you should go to localhost/ci_installation/index.php/mycont.

So, instead of writing such a long link you can (after loading "url" helper) , replace the term localhost/ci_installation/index.php/ by base_url() and this function will return the same string url.

NOTE: if you hadn't appended index.php/ to your base_url in your config.php, then if you use base_url(), it will return something like that localhost/ci_installation/mycont. And that will not work, because you have to access your controllers from index.php, instead of that you can place a .htaccess file to your codeigniter installation position. Cope that the below code to it:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /imguplod/index.php/$1 [L]

And it should work :)

What does "Git push non-fast-forward updates were rejected" mean?

You need to merge and resolve the conflicts locally before you push your changes to remote repo/fork.

1) pull (fetch and merge)

$ git pull remote branch 

2) Push the changes

$ git push remote branch 

Still you have a quick choice to push forcibly by using --force option but should be avoided as it may result in changes loss or affect badly on other contributors.

How to remove default chrome style for select Input?

In your CSS add this:

input {-webkit-appearance: none; box-shadow: none !important; }
:-webkit-autofill { color: #fff !important; }

Only for Chrome! :)

How to pass event as argument to an inline event handler in JavaScript?

Since inline events are executed as functions you can simply use arguments.

<p id="p" onclick="doSomething.apply(this, arguments)">

and

function doSomething(e) {
  if (!e) e = window.event;
  // 'e' is the event.
  // 'this' is the P element
}

The 'event' that is mentioned in the accepted answer is actually the name of the argument passed to the function. It has nothing to do with the global event.

How to zip a whole folder using PHP

Why not Try EFS PhP-ZiP MultiVolume Script ... I zipped and transferred hundreds of gigs and millions of files ... ssh is needed to effectively create archives.

But i belive that resulting files can be used with exec directly from php:

exec('zip -r backup-2013-03-30_0 . -i@backup-2013-03-30_0.txt');

I do not know if it works. I have not tried ...

"the secret" is that the execution time for archiving should not exceed the time allowed for execution of PHP code.

Selecting Folder Destination in Java?

Oracles Java Tutorial for File Choosers: http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

Note getSelectedFile() returns the selected folder, despite the name. getCurrentDirectory() returns the directory of the selected folder.

import javax.swing.*;

public class Example
{
    public static void main(String[] args)
    {
        JFileChooser f = new JFileChooser();
        f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 
        f.showSaveDialog(null);

        System.out.println(f.getCurrentDirectory());
        System.out.println(f.getSelectedFile());
    }      
}

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

Make sure:

<meta http-equiv="X-UA-Compatible" content="IE=edge">

is the first <meta> tag on your page, otherwise IE may not respect it.

Alternatively, the problem may be that IE is using Enterprise Mode for this website:

  • Your question mentioned that the console shows: HTML1122: Internet Explorer is running in Enterprise Mode emulating IE8.
  • If so you may need to disable enterprise mode (or like this) or turn it off for that website from the Tools menu in IE.
  • However Enterprise Mode should in theory be overridden by the X-UA-Compatible tag, but IE might have a bug...

Yarn install command error No such file or directory: 'install'

sudo npm install -g yarnpkg
npm WARN deprecated [email protected]: Please use the `yarn` package instead of `yarnpkg`

so this works for me

sudo npm install -g yarn

How to check if a table exists in MS Access for vb macros

Access has some sort of system tables You can read about it a little here you can fire the folowing query to see if it exists ( 1 = it exists, 0 = it doesnt ;))

SELECT Count([MSysObjects].[Name]) AS [Count]
FROM MSysObjects
WHERE (((MSysObjects.Name)="TblObject") AND ((MSysObjects.Type)=1));

How to change checkbox's border style in CSS?

put it in a div and add border to the div

Can a java file have more than one class?

A .java file is called a compilation unit. Each compilation unit may contain any number of top-level classes and interfaces. If there are no public top-level types then the compilation unit can be named anything.

//Multiple.java
//preceding package and import statements

class MyClass{...}
interface Service{...}
...
//No public classes or interfaces
...

There can be only one public class/interface in a compilation unit. The c.u. must be named exactly as this public top-level type.

//Test.java
//named exactly as the public class Test
public class Test{...}
//!public class Operations{...}
interface Selector{...}
...
//Other non-public classes/interfaces

Important points about the main method - part 1

Part 2

(Points regarding the number of classes and their access levels covered in part 2)

getting the ng-object selected with ng-change

_x000D_
_x000D_
//Javascript_x000D_
$scope.update = function () {_x000D_
    $scope.myItem;_x000D_
    alert('Hello');_x000D_
}
_x000D_
<!--HTML-->_x000D_
<div class="form-group">_x000D_
     <select name="name"_x000D_
             id="id" _x000D_
             ng-model="myItem" _x000D_
             ng-options="size as size.name for size in sizes"_x000D_
             class="form-control" _x000D_
             ng-change="update()"_x000D_
             multiple_x000D_
             required>_x000D_
     </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

If you want to write, name, id, class, multiple, required , You can write in this way.

How to tag an older commit in Git?

Example:

git tag -a v1.2 9fceb02 -m "Message here"

Where 9fceb02 is the beginning part of the commit id.

You can then push the tag using git push origin v1.2.

You can do git log to show all the commit id's in your current branch.

There is also a good chapter on tagging in the Pro Git book.

Warning: This creates tags with the current date (and that value is what will show on a GitHub releases page, for example). If you want the tag to be dated with the commit date, please look at another answer.

'names' attribute must be the same length as the vector

The mistake I made that coerced this error was attempting to rename a column in a loop that I was no longer selecting in my SQL. This could also be caused by trying to do the same thing in a column that you were planning to select. Make sure the column that you are trying to change actually exists.

Timeout for python requests.get entire response

In case you're using the option stream=True you can do this:

r = requests.get(
    'http://url_to_large_file',
    timeout=1,  # relevant only for underlying socket
    stream=True)

with open('/tmp/out_file.txt'), 'wb') as f:
    start_time = time.time()
    for chunk in r.iter_content(chunk_size=1024):
        if chunk:  # filter out keep-alive new chunks
            f.write(chunk)
        if time.time() - start_time > 8:
            raise Exception('Request took longer than 8s')

The solution does not need signals or multiprocessing.

What is perm space?

PermGen Space stands for memory allocation for Permanent generation All Java immutable objects come under this category, like String which is created with literals or with String.intern() methods and for loading the classes into memory. PermGen Space speeds up our String equality searching.

Cannot catch toolbar home button click event

The easiest approach we could do is change the home icon to a known icon and compare drawables (because android.R.id.home icon can differ to different api versions

so set a toolbar as actionbar SetSupportActionBar(_toolbar);

_toolbar.NavigationIcon = your_known_drawable_here;

   for (int i = 0; i < _toolbar.ChildCount; i++)
            {
                View v = _toolbar.GetChildAt(i);
                if (v is ImageButton)
                {
                    ImageButton imageButton = v as ImageButton;

                    if (imageButton.Drawable.GetConstantState().Equals(_bookMarkIcon.GetConstantState()))
                    {
                       //here v is the widget that contains the home  icon you can add your click events here 
                    }
                }
            }

How to not wrap contents of a div?

If you don't care about a minimum width for the div and really just don't want the div to expand across the whole container, you can float it left -- floated divs by default expand to support their contents, like so:

<form>
    <div style="float: left; background-color: blue">
        <input type="button" name="blah" value="lots and lots of characters"/>
        <input type="button" name="blah2" value="some characters"/>
    </div>
</form>

How to enable scrolling of content inside a modal?

In Bootstrap.css change the background attribute (position) of Modal from fixed to absolute

Javascript to stop HTML5 video playback on modal window close

I searched all over the internet for an answer for this question. none worked for me except this code. Guaranteed. It work perfectly.

$('body').on('hidden.bs.modal', '.modal', function () {
$('video').trigger('pause');
});

jQuery Ajax error handling, show custom exception messages

Although it has been many years since this question is asked, I still don't find xhr.responseText as the answer I was looking for. It returned me string in the following format:

"{"error":true,"message":"The user name or password is incorrect"}"

which I definitely don't want to show to the users. What I was looking for is something like below:

alert(xhr.responseJSON.message);

xhr.responseJSON.message gives me the exact message from the Json Object which can be shown to the users.

Java Reflection Performance

"Significant" is entirely dependent on context.

If you're using reflection to create a single handler object based on some configuration file, and then spending the rest of your time running database queries, then it's insignificant. If you're creating large numbers of objects via reflection in a tight loop, then yes, it's significant.

In general, design flexibility (where needed!) should drive your use of reflection, not performance. However, to determine whether performance is an issue, you need to profile rather than get arbitrary responses from a discussion forum.

Find out who is locking a file on a network share

If its simply a case of knowing/seeing who is in a file at any particular time (and if you're using windows) just select the file 'view' as 'details', i.e. rather than Thumbnails, tiles or icons etc. Once in 'details' view, by default you will be shown; - File name - Size - Type, and - Date modified

All you you need to do now is right click anywhere along said toolbar (file name, size, type etc...) and you will be given a list of other options that the toolbar can display.

Select 'Owner' and a new column will show the username of the person using the file or who originally created it if nobody else is using it.

This can be particularly useful when using a shared MS Access database.

maven compilation failure

Try to use:

mvn clean package install

This command should install your artifacts in you local maven repo.

PS: I see that this is an old question, but it may be helpful for somebody in the future.

How to get the sign, mantissa and exponent of a floating point number

You're &ing the wrong bits. I think you want:

s = *ptr >> 31;
e = *ptr & 0x7f800000;
e >>= 23;
m = *ptr & 0x007fffff;

Remember, when you &, you are zeroing out bits that you don't set. So in this case, you want to zero out the sign bit when you get the exponent, and you want to zero out the sign bit and the exponent when you get the mantissa.

Note that the masks come directly from your picture. So, the exponent mask will look like:

0 11111111 00000000000000000000000

and the mantissa mask will look like:

0 00000000 11111111111111111111111

Undefined reference to pow( ) in C, despite including math.h

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

How to skip to next iteration in jQuery.each() util?

What they mean by non-false is:

return true;

So this code:

_x000D_
_x000D_
var arr = ["one", "two", "three", "four", "five"];_x000D_
$.each(arr, function(i) {_x000D_
  if (arr[i] == 'three') {_x000D_
    return true;_x000D_
  }_x000D_
  console.log(arr[i]);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

will log one, two, four, five.

Excel 2010: how to use autocomplete in validation list

Building on the answer of JMax, use this formula for the dynamic named range to make the solution work for multiple rows:

=OFFSET(Sheet2!$A$1,MATCH(INDIRECT("Sheet1!"&ADDRESS(ROW(),COLUMN(),4))&"*",Sheet2!$A$1:$A$300,0)-1,0,COUNTA(Sheet2!$A:$A))

Get Client Machine Name in PHP

Try

echo getenv('COMPUTERNAME');

This will return your computername.

How to set a cookie for another domain

In case you have a.my-company.com and b.my-company.com instead of just a.com and b.com you can issue a cookie for .my-company.com domain - it will be accepted and sent to both of the domains.

How to get "their" changes in the middle of conflicting Git rebase?

You want to use:

git checkout --ours foo/bar.java
git add foo/bar.java

If you rebase a branch feature_x against main (i.e. running git rebase main while on branch feature_x), during rebasing ours refers to main and theirs to feature_x.

As pointed out in the git-rebase docs:

Note that a rebase merge works by replaying each commit from the working branch on top of the branch. Because of this, when a merge conflict happens, the side reported as ours is the so-far rebased series, starting with <upstream>, and theirs is the working branch. In other words, the sides are swapped.

For further details read this thread.

How to loop backwards in python?

All of these three solutions give the same results if the input is a string:

1.

def reverse(text):
    result = ""
    for i in range(len(text),0,-1):
        result += text[i-1]
    return (result)

2.

text[::-1]

3.

"".join(reversed(text))

What's the location of the JavaFX runtime JAR file, jfxrt.jar, on Linux?

Mine were located here on Ubuntu 18.04 when I installed JavaFX using apt install openjfx (as noted already by @jewelsea above)

/usr/share/java/openjfx/jre/lib/ext/jfxrt.jar
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/jfxrt.jar

How can I do a case insensitive string comparison?

This is not the best practice in .NET framework (4 & +) to check equality

String.Compare(x.Username, (string)drUser["Username"], 
                  StringComparison.OrdinalIgnoreCase) == 0

Use the following instead

String.Equals(x.Username, (string)drUser["Username"], 
                   StringComparison.OrdinalIgnoreCase) 

MSDN recommends:

  • Use an overload of the String.Equals method to test whether two strings are equal.
  • Use the String.Compare and String.CompareTo methods to sort strings, not to check for equality.

How to read values from properties file?

Here is an additional answer that was also great help for me to understand how it worked : http://www.javacodegeeks.com/2013/07/spring-bean-and-propertyplaceholderconfigurer.html

any BeanFactoryPostProcessor beans have to be declared with a static, modifier

@Configuration
@PropertySource("classpath:root/test.props")
public class SampleConfig {
 @Value("${test.prop}")
 private String attr;
 @Bean
 public SampleService sampleService() {
  return new SampleService(attr);
 }

 @Bean
 public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
  return new PropertySourcesPlaceholderConfigurer();
 }
}

Remove all the children DOM elements in div

node.innerHTML = "";

Non-standard, but fast and well supported.

Why do you create a View in a database?

When I want to see a snapshot of a table(s), and/or view (in a read-only way)

Angularjs error Unknown provider

Make sure you are loading those modules (myApp.services and myApp.directives) as dependencies of your main app module, like this:

angular.module('myApp', ['myApp.directives', 'myApp.services']);

plunker: http://plnkr.co/edit/wxuFx6qOMfbuwPq1HqeM?p=preview

Converting a string to JSON object

Simply use eval function.

var myJson = eval(theJsibStr);

How to overplot a line on a scatter plot in python?

You can use this tutorial by Adarsh Menon https://towardsdatascience.com/linear-regression-in-6-lines-of-python-5e1d0cd05b8d

This way is the easiest I found and it basically looks like:

import numpy as np
import matplotlib.pyplot as plt  # To visualize
import pandas as pd  # To read data
from sklearn.linear_model import LinearRegression
data = pd.read_csv('data.csv')  # load data set
X = data.iloc[:, 0].values.reshape(-1, 1)  # values converts it into a numpy array
Y = data.iloc[:, 1].values.reshape(-1, 1)  # -1 means that calculate the dimension of rows, but have 1 column
linear_regressor = LinearRegression()  # create object for the class
linear_regressor.fit(X, Y)  # perform linear regression
Y_pred = linear_regressor.predict(X)  # make predictions
plt.scatter(X, Y)
plt.plot(X, Y_pred, color='red')
plt.show()

Convert int to a bit array in .NET

Use Convert.ToString (value, 2)

so in your case

string binValue = Convert.ToString (3, 2);

What is the default text size on Android?

You can find standard sizes for everything in Google's style guide.

Here are the values they use for for buttons:

Buttons

English: Medium 14sp, all caps

Dense: Medium 15sp, all caps

Tall: Bold 15sp

Convert timestamp in milliseconds to string formatted time in Java

    long hours = TimeUnit.MILLISECONDS.toHours(timeInMilliseconds);
    long minutes = TimeUnit.MILLISECONDS.toMinutes(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours));
    long seconds = TimeUnit.MILLISECONDS
            .toSeconds(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours) - TimeUnit.MINUTES.toMillis(minutes));
    long milliseconds = timeInMilliseconds - TimeUnit.HOURS.toMillis(hours)
            - TimeUnit.MINUTES.toMillis(minutes) - TimeUnit.SECONDS.toMillis(seconds);
    return String.format("%02d:%02d:%02d:%d", hours, minutes, seconds, milliseconds);

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

According to the documentation, you can only display the __unicode__ representation of a ForeignKey:

http://docs.djangoproject.com/en/dev/ref/contrib/admin/#list-display

Seems odd that it doesn't support the 'book__author' style format which is used everywhere else in the DB API.

Turns out there's a ticket for this feature, which is marked as Won't Fix.

What's the difference between :: (double colon) and -> (arrow) in PHP?

The difference between static and instantiated methods and properties seem to be one of the biggest obstacles to those just starting out with OOP PHP in PHP 5.

The double colon operator (which is called the Paamayim Nekudotayim from Hebrew - trivia) is used when calling an object or property from a static context. This means an instance of the object has not been created yet.

The arrow operator, conversely, calls methods or properties that from a reference of an instance of the object.

Static methods can be especially useful in object models that are linked to a database for create and delete methods, since you can set the return value to the inserted table id and then use the constructor to instantiate the object by the row id.

Location of the mongodb database on mac

I have just installed mongodb 3.4 with homebrew.(brew install mongodb) It looks for /data/db by default.

https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/

Here is the output of mongod execution.

How to bind an enum to a combobox control in WPF?

Use ObjectDataProvider:

<ObjectDataProvider x:Key="enumValues"
   MethodName="GetValues" ObjectType="{x:Type System:Enum}">
      <ObjectDataProvider.MethodParameters>
           <x:Type TypeName="local:ExampleEnum"/>
      </ObjectDataProvider.MethodParameters>
 </ObjectDataProvider>

and then bind to static resource:

ItemsSource="{Binding Source={StaticResource enumValues}}"

based on this article

How to make <input type="date"> supported on all browsers? Any alternatives?

   <script>
      var datefield = document.createElement("input")
      datefield.setAttribute("type", "date")
      if (datefield.type != "date") { // if browser doesn't support input type="date", load files for jQuery UI Date Picker
         document.write('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />\n')
         document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"><\/script>\n')
         document.write('<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"><\/script>\n')
      }
   </script>

 <script>
    if (datefield.type != "date") { // if browser doesn't support input type="date", initialize date picker widget:
       jQuery(function($) { // on document.ready
           $('#birthday').datepicker();
       }); <- missing semicolon
    }
 </script>

<body>
 <form>
   <b>Date of birth:</b>
   <input type="date" id="birthday" name="birthday" size="20">
   <input type="button" value="Submit" name="B1">
 </form>
</body>

SOURCE 1 & SOURCE 2

Phone number validation Android

you can also check validation of phone number as

     /**
     * Validation of Phone Number
     */
    public final static boolean isValidPhoneNumber(CharSequence target) {
        if (target == null || target.length() < 6 || target.length() > 13) {
            return false;
        } else {
            return android.util.Patterns.PHONE.matcher(target).matches();
        }

    }

SQL query for extracting year from a date

This worked for me:

SELECT EXTRACT(YEAR FROM ASOFDATE) FROM PSASOFDATE;

How to install the JDK on Ubuntu Linux

I have successfully installed JDK 10 on Ubuntu 18.04 LTS following this video.

I am copying the excerpt from the description of the video.

Just open the terminal and give these commands :

For Java Installation (PPA)

sudo add-apt-repository ppa:linuxuprising/java
sudo apt-get update
sudo apt-get install oracle-java10-installer

For setting up environment variables (make java10 default)

sudo apt-get install oracle-java10-set-default

The same procedure can be followed on Ubuntu 16.04, Linux Mint, Debian and other related Linux systems to install JDK 10.

I get exception when using Thread.sleep(x) or wait()

You have a lot of reading ahead of you. From compiler errors through exception handling, threading and thread interruptions. But this will do what you want:

try {
    Thread.sleep(1000);                 //1000 milliseconds is one second.
} catch(InterruptedException ex) {
    Thread.currentThread().interrupt();
}

Max or Default?

Since .Net 3.5 you can use DefaultIfEmpty() passing the default value as an argument. Something like one of the followings ways:

int max = (from e in context.Table where e.Year == year select e.RecordNumber).DefaultIfEmpty(0).Max();
DateTime maxDate = (from e in context.Table where e.Year == year select e.StartDate ?? DateTime.MinValue).DefaultIfEmpty(DateTime.MinValue).Max();

The first one is allowed when you query a NOT NULL column and the second one is the way a used it to query a NULLABLE column. If you use DefaultIfEmpty() without arguments the default value will be that defined to the type of your output, as you can see in the Default Values Table .

The resulting SELECT will not be so elegant but it's acceptable.

Hope it helps.

Node.js https pem error: routines:PEM_read_bio:no start line

I removed this error by write the following code

Open Terminal

  1. openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem

  2. openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out server.crt

Now use the server.crt and key.pem file

app.js or server.js file

var https = require('https');
var https_options = {
  key: fs.readFileSync('key.pem', 'utf8'),
  cert: fs.readFileSync('server.crt', 'utf8')
};

var server = https.createServer(https_options, app).listen(PORT);
console.log('HTTPS Server listening on %s:%s', HOST, PORT);

It works but the certificate is not trusted. You can view the image in image file.

enter image description here

angular-cli server - how to specify default port

For @angular/cli v6.2.1

The project configuration file angular.json is able to handle multiple projects (workspaces) which can be individually served.

ng config projects.my-test-project.targets.serve.options.port 4201

Where the my-test-project part is the project name what you set with the ng new command just like here:

$ ng new my-test-project
$ cd my-test-project
$ ng config projects.my-test-project.targets.serve.options.port 4201
$ ng serve
** Angular Live Development Server is listening on localhost:4201, open your browser on http://localhost:4201/ **

Legacy:

I usually use the ng set command to change the Angular CLI settings for project level.

ng set defaults.serve.port=4201

It changes change your .angular.cli.json and adds the port settings as it mentioned earlier.

After this change you can use simply ng serve and it going to use the prefered port without the need of specifying it every time.

Declare a dictionary inside a static class

public static class ErrorCode
{
    public const IDictionary<string , string > m_ErrorCodeDic;

    public static ErrorCode()
    {
      m_ErrorCodeDic = new Dictionary<string, string>()
             { {"1","User name or password problem"} };             
    }
}

Probably initialise in the constructor.

What is duck typing?

Tree Traversal with duck typing technique

def traverse(t):
    try:
        t.label()
    except AttributeError:
        print(t, end=" ")
    else:
        # Now we know that t.node is defined
        print('(', t.label(), end=" ")
        for child in t:
            traverse(child)
        print(')', end=" ")

How to launch PowerShell (not a script) from the command line

The color and window sizing are defined by the shortcut LNK file. I think I found a way that will do what you need, try this:

explorer.exe "Windows PowerShell.lnk"

The LNK file is in the all user start menu which is located in different places depending whether your on XP or Windows 7. In 7 the LNK file is here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell

How to get cumulative sum

The SQL solution wich combines "ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW" and "SUM" did exactly what i wanted to achieve. Thank you so much!

If it can help anyone, here was my case. I wanted to cumulate +1 in a column whenever a maker is found as "Some Maker" (example). If not, no increment but show previous increment result.

So this piece of SQL:

SUM( CASE [rmaker] WHEN 'Some Maker' THEN  1 ELSE 0 END) 
OVER 
(PARTITION BY UserID ORDER BY UserID,[rrank] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Cumul_CNT

Allowed me to get something like this:

User 1  Rank1   MakerA      0  
User 1  Rank2   MakerB      0  
User 1  Rank3   Some Maker  1  
User 1  Rank4   Some Maker  2  
User 1  Rank5   MakerC      2
User 1  Rank6   Some Maker  3  
User 2  Rank1   MakerA      0  
User 2  Rank2   SomeMaker   1  

Explanation of above: It starts the count of "some maker" with 0, Some Maker is found and we do +1. For User 1, MakerC is found so we dont do +1 but instead vertical count of Some Maker is stuck to 2 until next row. Partitioning is by User so when we change user, cumulative count is back to zero.

I am at work, I dont want any merit on this answer, just say thank you and show my example in case someone is in the same situation. I was trying to combine SUM and PARTITION but the amazing syntax "ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW" completed the task.

Thanks! Groaker

How to fix SSL certificate error when running Npm on Windows?

TL;DR - Just run this and don't disable your security:

Replace existing certs

# Windows/MacOS/Linux 
npm config set cafile "<path to your certificate file>"

# Check the 'cafile'
npm config get cafile

or extend existing certs

Set this environment variable to extend pre-defined certs: NODE_EXTRA_CA_CERTS to "<path to certificate file>"

Full story

I've had to work with npm, pip, maven etc. behind a corporate firewall under Windows - it's not fun. I'll try and keep this platform agnostic/aware where possible.

HTTP_PROXY & HTTPS_PROXY

HTTP_PROXY & HTTPS_PROXY are environment variables used by lots of software to know where your proxy is. Under Windows, lots of software also uses your OS specified proxy which is a totally different thing. That means you can have Chrome (which uses the proxy specified in your Internet Options) connecting to the URL just fine, but npm, pip, maven etc. not working because they use HTTPS_PROXY (except when they use HTTP_PROXY - see later). Normally the environment variable would look something like:

http://proxy.example.com:3128

But you're getting a 403 which suggests you're not being authenticated against your proxy. If it is basic authentication on the proxy, you'll want to set the environment variable to something of the form:

http://user:[email protected]:3128

The dreaded NTLM

There is an HTTP status code 407 (proxy authentication required), which is the more correct way of saying it's the proxy rather than the destination server that's rejecting your request. That code plagued me for the longest time until after a lot of time on Google, I learned my proxy used NTLM authentication. HTTP basic authentication wasn't enough to satisfy whatever proxy my corporate overlords had installed. I resorted to using Cntlm on my local machine (unauthenticated), then had it handle the NTLM authentication with the upstream proxy. Then I had to tell all the programs that couldn't do NTLM to use my local machine as the proxy - which is generally as simple as setting HTTP_PROXY and HTTPS_PROXY. Otherwise, for npm use (as @Agus suggests):

npm config set proxy http://proxy.example.com:3128
npm config set https-proxy http://proxy.example.com:3128

"We need to decrypt all HTTPS traffic because viruses"

After this set-up had been humming along (clunkily) for about a year, the corporate overlords decided to change the proxy. Not only that, but it would no longer use NTLM! A brave new world to be sure. But because those writers of malicious software were now delivering malware via HTTPS, the only way they could protect we poor innocent users was to man-in-the-middle every connection to scan for threats before they even reached us. As you can imagine, I was overcome with the feeling of safety.

To cut a long story short, the self-signed certificate needs to be installed into npm to avoid SELF_SIGNED_CERT_IN_CHAIN:

npm config set cafile "<path to certificate file>"

Alternatively, the NODE_EXTRA_CA_CERTS environment variable can be set to the certificate file.

I think that's everything I know about getting npm to work behind a proxy/firewall. May someone find it useful.

Edit: It's a really common suggestion to turn off HTTPS for this problem either by using an HTTP registry or setting NODE_TLS_REJECT_UNAUTHORIZED. These are not good ideas because you're opening yourself up to further man-in-the-middle or redirection attacks. A quick spoof of your DNS records on the machine doing the package installation and you'll find yourself trusting packages from anywhere. It may seem like a lot of work to make HTTPS work, but it is highly recommended. When you're the one responsible for allowing untrusted code into the company, you'll understand why.

Edit 2: Keep in mind that setting npm config set cafile <path> causes npm to only use the certs provided in that file, instead of extending the existing ones with it.

If you want to extend the existing certs (e.g. with a company cert) using the environment variable NODE_EXTRA_CA_CERTS to link to the file is the way to go and can save you a lot of hassle. See how-to-add-custom-certificate-authority-ca-to-nodejs

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

It's really interesting case. Actually in your setup the following statement is true:

binary_crossentropy = len(class_id_index) * categorical_crossentropy

This means that up to a constant multiplication factor your losses are equivalent. The weird behaviour that you are observing during a training phase might be an example of a following phenomenon:

  1. At the beginning the most frequent class is dominating the loss - so network is learning to predict mostly this class for every example.
  2. After it learnt the most frequent pattern it starts discriminating among less frequent classes. But when you are using adam - the learning rate has a much smaller value than it had at the beginning of training (it's because of the nature of this optimizer). It makes training slower and prevents your network from e.g. leaving a poor local minimum less possible.

That's why this constant factor might help in case of binary_crossentropy. After many epochs - the learning rate value is greater than in categorical_crossentropy case. I usually restart training (and learning phase) a few times when I notice such behaviour or/and adjusting a class weights using the following pattern:

class_weight = 1 / class_frequency

This makes loss from a less frequent classes balancing the influence of a dominant class loss at the beginning of a training and in a further part of an optimization process.

EDIT:

Actually - I checked that even though in case of maths:

binary_crossentropy = len(class_id_index) * categorical_crossentropy

should hold - in case of keras it's not true, because keras is automatically normalizing all outputs to sum up to 1. This is the actual reason behind this weird behaviour as in case of multiclassification such normalization harms a training.

Reorder / reset auto increment primary key

I had the same doubts, but could not make any changes on the table, I decided doing the following having seen my ID did not exceed the maximum number setted in the variable @count:

SET @count = 40000000;
UPDATE `users` SET `users`.`id` = @count:= @count + 1;

SET @count = 0;
UPDATE `users` SET `users`.`id` = @count:= @count + 1;

ALTER TABLE `users` AUTO_INCREMENT = 1;

The solution takes, but it's safe and it was necessary because my table owned foreign keys with data in another table.

Modify the legend of pandas bar plot

To change the labels for Pandas df.plot() use ax.legend([...]):

import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
df.plot(kind='bar', ax=ax)
#ax = df.plot(kind='bar') # "same" as above
ax.legend(["AAA", "BBB"]);

enter image description here

Another approach is to do the same by plt.legend([...]):

import matplotlib.pyplot as plt
df.plot(kind='bar')
plt.legend(["AAA", "BBB"]);

enter image description here

What's the correct way to convert bytes to a hex string in Python 3?

OK, the following answer is slightly beyond-scope if you only care about Python 3, but this question is the first Google hit even if you don't specify the Python version, so here's a way that works on both Python 2 and Python 3.

I'm also interpreting the question to be about converting bytes to the str type: that is, bytes-y on Python 2, and Unicode-y on Python 3.

Given that, the best approach I know is:

import six

bytes_to_hex_str = lambda b: ' '.join('%02x' % i for i in six.iterbytes(b))

The following assertion will be true for either Python 2 or Python 3, assuming you haven't activated the unicode_literals future in Python 2:

assert bytes_to_hex_str(b'jkl') == '6a 6b 6c'

(Or you can use ''.join() to omit the space between the bytes, etc.)

What does if __name__ == "__main__": do?

PYTHON MAIN FUNCTION is a starting point of any program. When the program is run, the python interpreter runs the code sequentially. Main function is executed only when it is run as a Python program ...

def main():
     print ("i am in the function")
print ("i am out of function")

when you run script show :

i am out of function

and not the code "i am in the function" It is because we did not declare the call function "if__name__== "main". if you use from it :

def main():
     print ("i am in the function")


if __name__ == "__main__":
    main()

print ("i am out of function")

The output is equal to

i am in the function
i am out of function

In Python "if__name__== "main" allows you to run the Python files either as reusable modules or standalone programs.

When Python interpreter reads a source file, it will execute all the code found in it. When Python runs the "source file" as the main program, it sets the special variable (name) to have a value ("main").

When you execute the main function, it will then read the "if" statement and checks whether name does equal to main.

In Python "if__name__== "main" allows you to run the Python files either as reusable modules or standalone programs.

what is the difference between GROUP BY and ORDER BY in sql

  1. GROUP BY will aggregate records by the specified column which allows you to perform aggregation functions on non-grouped columns (such as SUM, COUNT, AVG, etc.). ORDER BY alters the order in which items are returned.
  2. If you do SELECT IsActive, COUNT(*) FROM Customers GROUP BY IsActive you get a count of active and inactive customers. The group by aggregated the results based on the field you specified. If you do SELECT * FROM Customers ORDER BY Name then you get the result list sorted by the customer’s name.
  3. If you GROUP, the results are not necessarily sorted; although in many cases they may come out in an intuitive order, that's not guaranteed by the GROUP clause. If you want your groups sorted, always use an explicitly ORDER BY after the GROUP BY.
  4. Grouped data cannot be filtered by WHERE clause. Order data can be filtered by WHERE clause.

python for increment inner loop

for a in range(1):

    for b in range(3):
        a = b*2
        print(a)

As per your question, you want to iterate the outer loop with help of the inner loop.

  1. In outer loop, we are iterating the inner loop 1 time.
  2. In the inner loop, we are iterating the 3 digits which are in the multiple of 2, starting from 0.

    Output:
    0
    2
    4
    

Python: Assign Value if None Exists

var1 = var1 or 4

The only issue this might have is that if var1 is a falsey value, like False or 0 or [], it will choose 4 instead. That might be an issue.

Find the number of downloads for a particular app in apple appstore

I think developers can do this for their own apps via iTunes Connect but this doesn't help you if you are looking for stats on other peoples apps.

148Apps also have some aggregate AppStore metrics on their web site that could be useful to you but, again, doesn't really give a low-level breakdown of numbers.

You could also scrape some stats from the RSS feeds generated by the iTunes Store RSS Generator but, again, this just gets currently popular apps rather than actual download numbers.

How to delete a cookie?

Here a good link on Quirksmode.

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name+'=; Max-Age=-99999999;';  
}

jQuery UI tabs. How to select a tab based on its id not based on index

Active 1st tab

$("#workflowTab").tabs({ active: 0 });

Active last tab

$("#workflowTab").tabs({ active: -1 });

Active 2nd tab

$("#workflowTab").tabs({ active: 1 });

Its work like an array

JQuery confirm dialog

You can use jQuery UI and do something like this

Html:

<button id="callConfirm">Confirm!</button>

<div id="dialog" title="Confirmation Required">
  Are you sure about this?
</div>?

Javascript:

$("#dialog").dialog({
   autoOpen: false,
   modal: true,
   buttons : {
        "Confirm" : function() {
            alert("You have confirmed!");            
        },
        "Cancel" : function() {
          $(this).dialog("close");
        }
      }
    });

$("#callConfirm").on("click", function(e) {
    e.preventDefault();
    $("#dialog").dialog("open");
});

?

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

Node: log in a file instead of the console

METHOD STDOUT AND STDERR

This approach can help you (I use something similar in my projects) and works for all methods including console.log, console.warn, console.error, console.info

This method write the bytes written in stdout and stderr to file. Is better than changing console.log, console.warn, console.error, console.info methods, because output will be exact the same as this methods output


var fs= require("fs")
var os= require("os")
var HOME= os.homedir()
var stdout_r = fs.createWriteStream(HOME + '/node.stdout.log', { flags: 'a' })
var stderr_r = fs.createWriteStream(HOME + '/node.stderr.log', { flags: 'a' })

var attachToLog= function(std, std_new){

    var originalwrite= std.write
    std.write= function(data,enc){
        try{
            var d= data
            if(!Buffer.isBuffer(d))
                d= Buffer.from(data, (typeof enc === 'string') ? enc : "utf8")
            std_new.write.apply(std_new, d)
        }catch(e){}
        return originalwrite.apply(std, arguments)
    }


}
attachToLog(process.stdout, stdout_r)
attachToLog(process.stderr, stderr_r)

// recommended catch error on stdout_r and stderr_r
// stdout_r.on("error", yourfunction)
// stderr_r.on("error", yourfunction)

How to search for a part of a word with ElasticSearch

If you want to implement autocomplete functionality, then Completion Suggester is the most neat solution. The next blog post contains a very clear description how this works.

In two words, it's an in-memory data structure called an FST which contains valid suggestions and is optimised for fast retrieval and memory usage. Essentially, it is just a graph. For instance, and FST containing the words hotel, marriot, mercure, munchen and munich would look like this:

enter image description here

Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?

There is boolean data type in SQL Server. Its values can be TRUE, FALSE or UNKNOWN. However, the boolean data type is only the result of a boolean expression containing some combination of comparison operators (e.g. =, <>, <, >=) or logical operators (e.g. AND, OR, IN, EXISTS). Boolean expressions are only allowed in a handful of places including the WHERE clause, HAVING clause, the WHEN clause of a CASE expression or the predicate of an IF or WHILE flow control statement.

For all other usages, including the data type of a column in a table, boolean is not allowed. For those other usages, the BIT data type is preferred. It behaves like a narrowed-down INTEGER which allows only the values 0, 1 and NULL, unless further restricted with a NOT NULL column constraint or a CHECK constraint.

To use a BIT column in a boolean expression it needs to be compared using a comparison operator such as =, <> or IS NULL. e.g.

SELECT
    a.answer_body
FROM answers AS a
WHERE a.is_accepted = 0;

From a formatting perspective, a bit value is typically displayed as 0 or 1 in client software. When a more user-friendly format is required, and it can't be handled at an application tier in front of the database, it can be converted "just-in-time" using a CASE expression e.g.

SELECT
    a.answer_body,
    CASE a.is_accepted WHEN 1 THEN 'TRUE' ELSE 'FALSE' END AS is_accepted
FROM answers AS a;

Storing boolean values as a character data type like char(1) or varchar(5) is also possible, but that is much less clear, has more storage/network overhead, and requires CHECK constraints on each column to restrict illegal values.

For reference, the schema of answers table would be similar to:

CREATE TABLE answers (
    ...,
    answer_body nvarchar(MAX) NOT NULL,
    is_accepted bit NOT NULL DEFAULT (0)
);

Adding close button in div to close the box

jQuery("#your_div_id").remove(); will completely remove the corresponding elements from the HTML DOM. So if you want to show the div on another event without a refresh, it will not be possible to retrieve the removed elements back unless you use AJAX.

jQuery("#your_div_id").toggle("slow"); will also could make unexpected results. As an Example when you select some element on your div which generates another div with a close button(which uses the same close functionality just as your previous div) it could make undesired behaviour.

So without using AJAX, a good solution for the close button would be as follows

HTML____________

<div id="your_div_id">
<span class="close_div" onclick="close_div(1)">&#10006</span>
</div>

JQUERY__________

function close_div(id) {
    if(id === 1) {
        jQuery("#your_div_id").hide();
    }
}

Now you can show the div, when another event occures as you wish... :-)

@RequestParam vs @PathVariable

@RequestParam annotation used for accessing the query parameter values from the request. Look at the following request URL:

http://localhost:8080/springmvc/hello/101?param1=10&param2=20

In the above URL request, the values for param1 and param2 can be accessed as below:

public String getDetails(
    @RequestParam(value="param1", required=true) String param1,
        @RequestParam(value="param2", required=false) String param2){
...
}

The following are the list of parameters supported by the @RequestParam annotation:

  • defaultValue – This is the default value as a fallback mechanism if request is not having the value or it is empty.
  • name – Name of the parameter to bind
  • required – Whether the parameter is mandatory or not. If it is true, failing to send that parameter will fail.
  • value – This is an alias for the name attribute

@PathVariable

@PathVariable identifies the pattern that is used in the URI for the incoming request. Let’s look at the below request URL:

http://localhost:8080/springmvc/hello/101?param1=10&param2=20

The above URL request can be written in your Spring MVC as below:

@RequestMapping("/hello/{id}")    public String getDetails(@PathVariable(value="id") String id,
    @RequestParam(value="param1", required=true) String param1,
    @RequestParam(value="param2", required=false) String param2){
.......
}

The @PathVariable annotation has only one attribute value for binding the request URI template. It is allowed to use the multiple @PathVariable annotation in the single method. But, ensure that no more than one method has the same pattern.

Also there is one more interesting annotation: @MatrixVariable

http://localhost:8080/spring_3_2/matrixvars/stocks;BT.A=276.70,+10.40,+3.91;AZN=236.00,+103.00,+3.29;SBRY=375.50,+7.60,+2.07

And the Controller method for it

 @RequestMapping(value = "/{stocks}", method = RequestMethod.GET)
  public String showPortfolioValues(@MatrixVariable Map<String, List<String>> matrixVars, Model model) {

    logger.info("Storing {} Values which are: {}", new Object[] { matrixVars.size(), matrixVars });

    List<List<String>> outlist = map2List(matrixVars);
    model.addAttribute("stocks", outlist);

    return "stocks";
  }

But you must enable:

<mvc:annotation-driven enableMatrixVariables="true" >

Java resource as file

A reliable way to construct a File instance on a resource retrieved from a jar is it to copy the resource as a stream into a temporary File (the temp file will be deleted when the JVM exits):

public static File getResourceAsFile(String resourcePath) {
    try {
        InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
        if (in == null) {
            return null;
        }

        File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
        tempFile.deleteOnExit();

        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            //copy stream
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
        return tempFile;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

Installing SciPy with pip

The answer is yes, there is.

First you can easily install numpy use commands:

pip install numpy

Then you should install mkl, which is required by Scipy, and you can download it here

After download the file_name.whl you install it

C:\Users\****\Desktop\a> pip install mkl_service-1.1.2-cp35-cp35m-win32.whl
Processing c:\users\****\desktop\a\mkl_service-1.1.2-cp35-cp35m-win32.whl 
Installing collected packages: mkl-service    
Successfully installed mkl-service-1.1.2

Then at the same website you can download scipy-0.18.1-cp35-cp35m-win32.whl

Note:You should download the file_name.whl according to you python version, if you python version is 32bit python3.5 you should download this one, and the "win32" is about your python version, not your operating system version.

Then install file_name.whl like this:

C:\Users\****\Desktop\a>pip install scipy-0.18.1-cp35-cp35m-win32.whl
Processing c:\users\****\desktop\a\scipy-0.18.1-cp35-cp35m-win32.whl
Installing collected packages: scipy
Successfully installed scipy-0.18.1

Then there is only one more thing to do: comment out a specfic line or there will be error messages when you imput command "import scipy".

So comment out this line

from numpy._distributor_init import NUMPY_MKL  # requires numpy+mkl

in this file: your_own_path\lib\site-packages\scipy__init__.py

Then you can use SciPy :)

Here tells you more about the last step.

Here is a similar anwser to a similar question.

How can I split a shell command over multiple lines when using an IF statement?

The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:

$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
   --forward-agent \
   --disable-known-hosts deploy:$target; then
     echo failed
else
     echo succeeded
fi

$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed

Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.

[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr option that you can set to make it carriage-return-tolerant.

Alternative to header("Content-type: text/xml");

Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.

Take this

<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&#39;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'type="' . $row['type'] . '" ';
  echo '/>';
}
// End XML file
echo '</markers>';
?>

and place it in phpsqlajax_genxml.php so your javascript can download the XML file. You are trying to do too many things in the same file.

Spring Boot and how to configure connection details to MongoDB?

spring.data.mongodb.host and spring.data.mongodb.port are not supported if you’re using the Mongo 3.0 Java driver. In such cases, spring.data.mongodb.uri should be used to provide all of the configuration, like this:

spring.data.mongodb.uri=mongodb://user:[email protected]:12345

Creating folders inside a GitHub repository without using Git

After searching a lot I find out that it is possible to create a new folder from the web interface, but it would require you to have at least one file within the folder when creating it.

When using the normal way of creating new files through the web interface, you can type in the folder into the file name to create the file within that new directory.

For example, if I would like to create the file filename.md in a series of sub-folders, I can do this (taken from the GitHub blog):

Enter image description here

C++ Best way to get integer division and remainder

All else being equal, the best solution is one that clearly expresses your intent. So:

int totalSeconds = 453;
int minutes = totalSeconds / 60;
int remainingSeconds = totalSeconds % 60;

is probably the best of the three options you presented. As noted in other answers however, the div method will calculate both values for you at once.

Is there a way to make AngularJS load partials in the beginning and not at when needed?

Another method is to use HTML5's Application Cache to download all files once and keep them in the browser's cache. The above link contains much more information. The following information is from the article:

Change your <html> tag to include a manifest attribute:

<html manifest="http://www.example.com/example.mf">

A manifest file must be served with the mime-type text/cache-manifest.

A simple manifest looks something like this:

CACHE MANIFEST
index.html
stylesheet.css
images/logo.png
scripts/main.js
http://cdn.example.com/scripts/main.js

Once an application is offline it remains cached until one of the following happens:

  1. The user clears their browser's data storage for your site.
  2. The manifest file is modified. Note: updating a file listed in the manifest doesn't mean the browser will re-cache that resource. The manifest file itself must be altered.

Returning http status code from Web Api controller

I don't like having to change my signature to use the HttpCreateResponse type, so I came up with a little bit of an extended solution to hide that.

public class HttpActionResult : IHttpActionResult
{
    public HttpActionResult(HttpRequestMessage request) : this(request, HttpStatusCode.OK)
    {
    }

    public HttpActionResult(HttpRequestMessage request, HttpStatusCode code) : this(request, code, null)
    {
    }

    public HttpActionResult(HttpRequestMessage request, HttpStatusCode code, object result)
    {
        Request = request;
        Code = code;
        Result = result;
    }

    public HttpRequestMessage Request { get; }
    public HttpStatusCode Code { get; }
    public object Result { get; }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult(Request.CreateResponse(Code, Result));
    }
}

You can then add a method to your ApiController (or better your base controller) like this:

protected IHttpActionResult CustomResult(HttpStatusCode code, object data) 
{
    // Request here is the property on the controller.
    return new HttpActionResult(Request, code, data);
}

Then you can return it just like any of the built in methods:

[HttpPost]
public IHttpActionResult Post(Model model)
{
    return model.Id == 1 ?
                Ok() :
                CustomResult(HttpStatusCode.NotAcceptable, new { 
                    data = model, 
                    error = "The ID needs to be 1." 
                });
}

Can an interface extend multiple interfaces in Java?

You can extend multiple Interfaces but you cannot extend multiple classes.

The reason that it is not possible in Java to extending multiple classes, is the bad experience from C++ where this is possible.

The alternative for multipe inheritance is that a class can implement multiple interfaces (or an Interface can extend multiple Interfaces)

How to check if $? is not equal to zero in unix shell scripting?

if [ $var1 != $var2 ] 
then 
echo "$var1"
else 
echo "$var2"
fi

Set SSH connection timeout

The problem may be that ssh is trying to connect to all the different IPs that www.google.com resolves to. For example on my machine:

# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out

If I run it with a specific IP, it returns much faster.

EDIT: I've timed it (with time) and the results are:

  • www.google.com - 5.086 seconds
  • 173.94.43.16 - 1.054 seconds

Check if my SSL Certificate is SHA1 or SHA2

Use the Linux Command Line

Use the command line, as described in this related question: How do I check if my SSL Certificate is SHA1 or SHA2 on the commandline.

Command

Here's the command. Replace www.yoursite.com:443 to fit your needs. Default SSL port is 443:

openssl s_client -connect www.yoursite.com:443 < /dev/null 2>/dev/null \
    | openssl x509 -text -in /dev/stdin | grep "Signature Algorithm"

Results

This should return something like this for the sha1:

Signature Algorithm: sha1WithRSAEncryption

or this for the newer version:

Signature Algorithm: sha256WithRSAEncryption

References

The article Why Google is Hurrying the Web to Kill SHA-1 describes exactly what you would expect and has a pretty graphic, too.

Counting the number of elements with the values of x in a vector

The most direct way is sum(numbers == x).

numbers == x creates a logical vector which is TRUE at every location that x occurs, and when suming, the logical vector is coerced to numeric which converts TRUE to 1 and FALSE to 0.

However, note that for floating point numbers it's better to use something like: sum(abs(numbers - x) < 1e-6).

String's Maximum length in Java - calling length() method

java.io.DataInput.readUTF() and java.io.DataOutput.writeUTF(String) say that a String object is represented by two bytes of length information and the modified UTF-8 representation of every character in the string. This concludes that the length of String is limited by the number of bytes of the modified UTF-8 representation of the string when used with DataInput and DataOutput.

In addition, The specification of CONSTANT_Utf8_info found in the Java virtual machine specification defines the structure as follows.

CONSTANT_Utf8_info {
    u1 tag;
    u2 length;
    u1 bytes[length];
}

You can find that the size of 'length' is two bytes.

That the return type of a certain method (e.g. String.length()) is int does not always mean that its allowed maximum value is Integer.MAX_VALUE. Instead, in most cases, int is chosen just for performance reasons. The Java language specification says that integers whose size is smaller than that of int are converted to int before calculation (if my memory serves me correctly) and it is one reason to choose int when there is no special reason.

The maximum length at compilation time is at most 65536. Note again that the length is the number of bytes of the modified UTF-8 representation, not the number of characters in a String object.

String objects may be able to have much more characters at runtime. However, if you want to use String objects with DataInput and DataOutput interfaces, it is better to avoid using too long String objects. I found this limitation when I implemented Objective-C equivalents of DataInput.readUTF() and DataOutput.writeUTF(String).

HTTPS connections over proxy servers

Here is my complete Java code that supports both HTTP and HTTPS requests using SOCKS proxy.

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

import org.apache.http.HttpHost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;

/**
 * How to send a HTTP or HTTPS request via SOCKS proxy.
 */
public class ClientExecuteSOCKS {

    public static void main(String[] args) throws Exception {
        Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new MyHTTPConnectionSocketFactory())
            .register("https", new MyHTTPSConnectionSocketFactory(SSLContexts.createSystemDefault
                ()))
            .build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);
        try (CloseableHttpClient httpclient = HttpClients.custom()
            .setConnectionManager(cm)
            .build()) {
            InetSocketAddress socksaddr = new InetSocketAddress("mysockshost", 1234);
            HttpClientContext context = HttpClientContext.create();
            context.setAttribute("socks.address", socksaddr);

            HttpHost target = new HttpHost("www.example.com/", 80, "http");
            HttpGet request = new HttpGet("/");

            System.out.println("Executing request " + request + " to " + target + " via SOCKS " +
                "proxy " + socksaddr);
            try (CloseableHttpResponse response = httpclient.execute(target, request, context)) {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                System.out.println(EntityUtils.toString(response.getEntity(), StandardCharsets
                    .UTF_8));
            }
        }
    }

    static class MyHTTPConnectionSocketFactory extends PlainConnectionSocketFactory {
        @Override
        public Socket createSocket(final HttpContext context) throws IOException {
            InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("socks.address");
            Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
            return new Socket(proxy);
        }
    }

    static class MyHTTPSConnectionSocketFactory extends SSLConnectionSocketFactory {
        public MyHTTPSConnectionSocketFactory(final SSLContext sslContext) {
            super(sslContext);
        }

        @Override
        public Socket createSocket(final HttpContext context) throws IOException {
            InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("socks.address");
            Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
            return new Socket(proxy);
        }
    }
}

Shrinking navigation bar when scrolling down (bootstrap3)

If you are using AngularJS, and you are using Angular Bootstrap : https://angular-ui.github.io/bootstrap/

You can do this so nice like this :

HTML:

<nav id="header-navbar" class="navbar navbar-default" ng-class="{'navbar-fixed-top':scrollDown}" role="navigation" scroll-nav>
    <div class="container-fluid top-header">
        <!--- Rest of code --->
    </div>
</nav>

CSS: (Note here I use padding as bigger nav to shrink without padding you can modify as you want)

nav.navbar {
  -webkit-transition: all 0.4s ease;
  transition: all 0.4s ease;

  background-color: white;
  margin-bottom: 0;
  padding: 25px;
}

.navbar-fixed-top {
  padding: 0;
}

And then add your directive

Directive: (Note you may need to change this.pageYOffset >= 50 from 50 to more or less to fulfill your needs)

angular.module('app')
.directive('scrollNav', function ($window) {
  return function(scope, element, attrs) {
    angular.element($window).bind("scroll", function() {
      if (this.pageYOffset >= 50) {
        scope.scrollDown = true;
      } else {
        scope.scrollDown = false;
      }
      scope.$apply();
    });
  };
});

This will do the job nicely, animated and cool way.

Open page in new window without popup blocking

A browser will only open a tab/popup without the popup blocker warning if the command to open the tab/popup comes from a trusted event. That means the user has to actively click somewhere to open a popup.

In your case, the user performs a click so you have the trusted event. You do lose that trusted context, however, by performing the Ajax request. Your success handler does not have that event anymore. The only way to circumvent this is to perform a synchronous Ajax request which will block your browser while it runs, but will preserve the event context.

In jQuery this should do the trick:

$.ajax({
 url: 'http://yourserver/',
 data: 'your image',
 success: function(){window.open(someUrl);},
 async: false
});

Here is your answer: Open new tab without popup blocker after ajax call on user click

SSRS expression to format two decimal places does not show zeros

Please try the following code snippet,

IIF(Round(Avg(Fields!Vision_Score.Value)) = Avg(Fields!Vision_Score.Value), 
Format(Avg(Fields!Vision_Score.Value)), 
FORMAT(Avg(Fields!Vision_Score.Value),"##.##"))

hope it will help, Thank-you.

Running Python on Windows for Node.js dependencies

Here is a guide that resolved a lot of these issues for me.

http://www.steveworkman.com/node-js/2012/installing-jsdom-on-windows/

I remember in particular the python version as important. Make sure you install 2.7.3 instead of 3's.

How to config Tomcat to serve images from an external folder outside webapps?

This is very simple and straight forward to server the static content from outside webapps folder in tomcat.

Simply edit the server.xml under $CATALINA_HOME/config/server.xml as below and restart the tomcat.

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

        **<Context docBase="C:\Ankur\testFiles"  path="/companyLogo" />**

       <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

</Host>

Add the context element inside the host element with two attribute docBase and path.

1) docBase: represents the hard drive directory 2) path: represents the uri on which you want to serve the static content.

For example:If you have 7.png inside the C:\Ankur\testFiles directory then you can access the 7.png file like below:

http://localhost:8081/companyLogo/7.png

For more details, check the blog

Printing an array in C++?

Besides the for-loop based solutions, you can also use an ostream_iterator<>. Here's an example that leverages the sample code in the (now retired) SGI STL reference:

#include <iostream>
#include <iterator>
#include <algorithm>

int main()
{
  short foo[] = { 1, 3, 5, 7 };

  using namespace std;
  copy(foo,
       foo + sizeof(foo) / sizeof(foo[0]),
       ostream_iterator<short>(cout, "\n"));
}

This generates the following:

 ./a.out 
1
3
5
7

However, this may be overkill for your needs. A straight for-loop is probably all that you need, although litb's template sugar is quite nice, too.

Edit: Forgot the "printing in reverse" requirement. Here's one way to do it:

#include <iostream>
#include <iterator>
#include <algorithm>

int main()
{
  short foo[] = { 1, 3, 5, 7 };

  using namespace std;

  reverse_iterator<short *> begin(foo + sizeof(foo) / sizeof(foo[0]));
  reverse_iterator<short *> end(foo);

  copy(begin,
       end,
       ostream_iterator<short>(cout, "\n"));
}

and the output:

$ ./a.out 
7
5
3
1

Edit: C++14 update that simplifies the above code snippets using array iterator functions like std::begin() and std::rbegin():

#include <iostream>
#include <iterator>
#include <algorithm>

int main()
{
    short foo[] = { 1, 3, 5, 7 };

    // Generate array iterators using C++14 std::{r}begin()
    // and std::{r}end().

    // Forward
    std::copy(std::begin(foo),
              std::end(foo),
              std::ostream_iterator<short>(std::cout, "\n"));

    // Reverse
    std::copy(std::rbegin(foo),
              std::rend(foo),
              std::ostream_iterator<short>(std::cout, "\n"));
}

A select query selecting a select statement

I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:

SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;

Thanks for answering, it helped my train of thought.

How can I test that a variable is more than eight characters in PowerShell?

Use the length property of the [String] type:

if ($dbUserName.length -gt 8) {
    Write-Output "Please enter more than 8 characters."
    $dbUserName = Read-Host "Re-enter database username"
}

Please note that you have to use -gt instead of > in your if condition. PowerShell uses the following comparison operators to compare values and test conditions:

  • -eq = equals
  • -ne = not equals
  • -lt = less than
  • -gt = greater than
  • -le = less than or equals
  • -ge = greater than or equals

How much faster is C++ than C#?

It really depends on what you're trying to accomplish in your code. I've heard that it's just stuff of urban legend that there is any performance difference between VB.NET, C# and managed C++. However, I've found, at least in string comparisons, that managed C++ beats the pants off of C#, which in turn beats the pants off of VB.NET.

I've by no means done any exhaustive comparisons in algorithmic complexity between the languages. I'm also just using the default settings in each of the languages. In VB.NET I'm using settings to require declaration of variables, etc. Here is the code I'm using for managed C++: (As you can see, this code is quite simple). I'm running the same in the other languages in Visual Studio 2013 with .NET 4.6.2.

#include "stdafx.h"

using namespace System;
using namespace System::Diagnostics;

bool EqualMe(String^ first, String^ second)
{
    return first->Equals(second);
}
int main(array<String ^> ^args)
{
    Stopwatch^ sw = gcnew Stopwatch();
    sw->Start();
    for (int i = 0; i < 100000; i++)
    {
        EqualMe(L"one", L"two");
    }
    sw->Stop();
    Console::WriteLine(sw->ElapsedTicks);
    return 0;
}

Excel VBA, error 438 "object doesn't support this property or method

The Error is here

lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1

wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this

lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
          wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1

Similarly

wsPOR.Range("A2:G" & lastrow).Select

should be

wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select

How to customize the background/border colors of a grouped table view cell?

This task can be easily done using PrettyKit by adding about 5 lines of code. If you use nib files or storyboard, also do not forget to apply this little hack . When you use this approach, you should subclass your cell from PrettyTableViewCell:

#import <PrettyKit/PrettyKit.h>

@class RRSearchHistoryItem;

@interface RRSearchHistoryCell : PrettyTableViewCell

This is example of my cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *cellIdentifier = @"RRSearchHistoryCell";

  RRSearchHistoryCell *cell = (RRSearchHistoryCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

  if ( cell == nil ) {

    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"RRSearchHistoryCell" owner:self options:nil];
    cell = topLevelObjects[0];
    cell.gradientStartColor = RGB(0xffffff);
    cell.gradientEndColor = RGB(0xf3f3f3);

  }

  RRSearchHistoryItem *item = _historyTableData[indexPath.row];
  [cell setHistoryItem:item];


  [cell prepareForTableView:tableView indexPath:indexPath];

  return cell;
}

How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime

A small work around I used many times

_x000D_
_x000D_
Promise.resolve(data).then(() => {
    console.log( "! changement de la date du composant !" );
    this.dateNow = new Date();
    this.cdRef.detectChanges();
});
_x000D_
_x000D_
_x000D_

How to get a complete list of ticker symbols from Yahoo Finance?

I had same problem, but I think I have simple solution(code is from my RoR app): Extract industry ids from yahoo.finance.sectors and add it to db:

    select = "select * from yahoo.finance.sectors"
    generate_query select
    @data.each do |data|
      data["industry"].each do |ind|
        unless ind.kind_of?(Array)
          unless ind["id"].nil?
            id = ind["id"].to_i
            if id > 0
              Industry.where(id: id).first_or_create(name: ind["name"]).update_attribute(:name, ind["name"])
            end
          end
        end
      end
    end

Extract all comanies with their symbols with industry ids:

    ids = Industry.all.map{|ind| "'#{ind.id.to_s}'" }.join(",")
    select = "select * from yahoo.finance.industry where id in"
    generate_query select, ids
    @data.each do |ts|
      unless ts.kind_of?(Array) || ts["company"].nil?
        if ts["company"].count == 2 && ts["company"].first[0] == "name"
          t = ts["company"]
          Ticket.find_or_create_by_symbol(symbol: t["symbol"], name: t["name"] ).update_attribute(:name, t["name"])
        else
          ts["company"].each do |t|
            Ticket.find_or_create_by_symbol(symbol: t["symbol"], name: t["name"] ).update_attribute(:name, t["name"])
          end
        end
      end
    end
  end

Connection hellper:

def generate_query(select, ids = nil)
    if params[:form] || params[:action] == "sectors" || params[:controller] == "tickets"
      if params[:action] == "sectors" || params[:controller] == "tickets"
        if ids.nil?
          query= select
        else
          query= "#{select} (#{ids})"
        end
      else
        if params[:form][:ids]
          @conditions = params_parse params[:form][:ids]
          query = "#{select} (#{@conditions})"
        end
      end
      yql_execut(query)
    end
  end

  def yql_execut(query)
    # TODO: OAuth ACCESS (http://developer.yahoo.com/yql/guide/authorization.html)
    base_url = "http://query.yahooapis.com/v1/public/yql?&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&q="
    dirty_data = JSON.parse(HTTParty.get(base_url +  URI.encode(query)).body)
    if dirty_data["query"]["results"] == nil
      @data, @count, @table_head = nil
    else
      @data = dirty_data["query"]["results"].to_a[0][1].to_a
      @count = dirty_data["query"]["count"]
      if @count == 1
        @table_head = @data.map{|h| h[0].capitalize}
      else
        @table_head = @data.to_a.first.to_a.map{|h| h[0].capitalize}
      end
    end
  end

Sorry for mess, but this is first testing version for my project and I needed it very fast. There are some helpers variabels and other things for my app, sorry for it. But I have question: Have many symbols do you have? I have 5500.

How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

You can get all keys in the Request.Form and then compare and get your desired values.

Your method body will look like this: -

List<int> listValues = new List<int>();
foreach (string key in Request.Form.AllKeys)
{
    if (key.StartsWith("List"))
    {
        listValues.Add(Convert.ToInt32(Request.Form[key]));
    }
}

Change default icon

you should put your icon on the project folder, before build it

Printing newlines with print() in R

An alternative to cat() is writeLines():

> writeLines("File not supplied.\nUsage: ./program F=filename")
File not supplied.
Usage: ./program F=filename
>

An advantage is that you don't have to remember to append a "\n" to the string passed to cat() to get a newline after your message. E.g. compare the above to the same cat() output:

> cat("File not supplied.\nUsage: ./program F=filename")
File not supplied.
Usage: ./program F=filename>

and

> cat("File not supplied.\nUsage: ./program F=filename","\n")
File not supplied.
Usage: ./program F=filename
>

The reason print() doesn't do what you want is that print() shows you a version of the object from the R level - in this case it is a character string. You need to use other functions like cat() and writeLines() to display the string. I say "a version" because precision may be reduced in printed numerics, and the printed object may be augmented with extra information, for example.

Call multiple functions onClick ReactJS

Wrap your two+ function calls in another function/method. Here are a couple variants of that idea:

1) Separate method

var Test = React.createClass({
   onClick: function(event){
      func1();
      func2();
   },
   render: function(){
      return (
         <a href="#" onClick={this.onClick}>Test Link</a>
      );
   }
});

or with ES6 classes:

class Test extends React.Component {
   onClick(event) {
      func1();
      func2();
   }
   render() {
      return (
         <a href="#" onClick={this.onClick}>Test Link</a>
      );
   }
}

2) Inline

<a href="#" onClick={function(event){ func1(); func2()}}>Test Link</a>

or ES6 equivalent:

<a href="#" onClick={() => { func1(); func2();}}>Test Link</a>

Codeigniter displays a blank page instead of error messages

If you're using CI 2.0 or newer, you could change ENVIRONMENT type in your index.php to define('ENVIRONMENT', 'testing');.
Alternatively, you could add php_flag display_errors on to your .htaccess file.

How to list all methods for an object in Ruby?

The following will list the methods that the User class has that the base Object class does not have...

>> User.methods - Object.methods
=> ["field_types", "maximum", "create!", "active_connections", "to_dropdown",
    "content_columns", "su_pw?", "default_timezone", "encode_quoted_value", 
    "reloadable?", "update", "reset_sequence_name", "default_timezone=", 
    "validate_find_options", "find_on_conditions_without_deprecation", 
    "validates_size_of", "execute_simple_calculation", "attr_protected", 
    "reflections", "table_name_prefix", ...

Note that methods is a method for Classes and for Class instances.

Here's the methods that my User class has that are not in the ActiveRecord base class:

>> User.methods - ActiveRecord::Base.methods
=> ["field_types", "su_pw?", "set_login_attr", "create_user_and_conf_user", 
    "original_table_name", "field_type", "authenticate", "set_default_order",
    "id_name?", "id_name_column", "original_locking_column", "default_order",
    "subclass_associations",  ... 
# I ran the statements in the console.

Note that the methods created as a result of the (many) has_many relationships defined in the User class are not in the results of the methods call.

Added Note that :has_many does not add methods directly. Instead, the ActiveRecord machinery uses the Ruby method_missing and responds_to techniques to handle method calls on the fly. As a result, the methods are not listed in the methods method result.

Removing items from a list

You cannot do it because you are already looping on it.

Inorder to avoid this situation use Iterator,which guarentees you to remove the element from list safely ...

List<Object> objs;
Iterator<Object> i = objs.iterator();
while (i.hasNext()) {
   Object o = i.next();
  //some condition
    i.remove();
}

How do I remove accents from characters in a PHP string?

UTF-8 friendly version of the simple function posted above by Gino:

function stripAccents($str) {
    return strtr(utf8_decode($str), utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'), 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
}

Had to come to this because my php document was UTF-8 encoded.

Hope it helps.

javascript find and remove object in array based on key value

here is a solution if you are not using jquery:

myArray = myArray.filter(function( obj ) {
  return obj.id !== id;
});

How can I go back/route-back on vue-router?

You can use Programmatic Navigation.In order to go back, you use this:

router.go(n) 

Where n can be positive or negative (to go back). This is the same as history.back().So you can have your element like this:

<a @click="$router.go(-1)">back</a>

How to open my files in data_folder with pandas using relative path?

You can always point to your home directory using ~ then you can refer to your data folder.

import pandas as pd
df = pd.read_csv("~/mydata/data.csv")

For your case, it should be like this

import pandas as pd
df = pd.read_csv("~/folder/folder2/data_folder/data.csv")

You can also set your data directory as a prefix

import pandas as pd
DATA_DIR = "~/folder/folder2/data_folder/"
df = pd.read_csv(DATA_DIR+"data.csv")

You can take advantage of f-strings as @nikos-tavoularis said

import pandas as pd
DATA_DIR = "~/folder/folder2/data_folder/"
FILE_NAME = "data.csv"
df = pd.read_csv(f"{DATA_DIR}{FILE_NAME}")