Programs & Examples On #Fileloadexception

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

None of these options worked for me, in the end it was;

Test > Test Settings > *.testrunconfig

I had to add a new line

<DeploymentItem filename="packages\Newtonsoft.Json.4.5.8\lib\net40\Newtonsoft.Json.dll" />

Make sure the path and version is correct for your setup.

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

Normally adding the binding redirect should solve this problem, but it was not working for me. After a few hours of banging my head against the wall, I realized that there was an xmlns attribute causing problems in my web.config. After removing the xmlns attribute from the configuration node in Web.config, the binding redirects worked as expected.

http://www.davepaquette.com/archive/2014/10/02/could-not-load-file-or-assembly-newtonsoft-json-version4-5-0-0.aspx

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

In my case this error appeared when I asigned to both dynamic created controls (combobox), same created control from other class.

//dynamic created controls
ComboBox combobox1 = ManagerControls.myCombobox1;
...some events

ComboBox combobox2 = ManagerControl.myComboBox2;
...some events

.

//method in constructor
public static void InitializeDynamicControls()
{
     ComboBox cb = new ComboBox();
     cb.Background = new SolidColorBrush(Colors.Blue);
     ...
     cb.Width = 100;
     cb.Text = "Select window";
        
     ManagerControls.myCombobox1 = cb;
     ManagerControls.myComboBox2 = cb; // <-- error here
}

Solution: create another ComboBox cb2 and assign it to ManagerControls.myComboBox2.

I hope I helped someone.

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

If you are still looking for an answer, try checking this question thread. It helped me resolve a similar problem.

edit: The solution that helped me was to run Update-Package Microsoft.AspNet.WebApi -reinstall from the NugGet package manager, as suggested by Pathoschild. I then had to delete my .suo file and restart VS, as suggested by Sergey Osypchuk in this thread.

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

I had the same problem with System.Web.Http.WebHost, Version=5.2.6.0 being referenced but the latest NuGet package was 5.2.7.0. I edited the web.config files, re-installed the NuGet package, then edited the visual studio project files for all of my projects to make sure no references to 5.2.6.0 persisted. Even after all this, the problem persisted.

Then I looked in the bin folder for the project that was throwing the exception, where I found a DLL for one of my other projects that is not a dependency and should never have been there. I deleted the offending DLL (which had been compiled using the 5.2.6.0 version of System.Web.Http.WebHost), rebuilt the troublesome project, and now it is working.

Could not load file or assembly 'EntityFramework' after downgrading EF 5.0.0.0 --> 4.3.1.0

I had similar issue with selenium: I downgraded my selenium using NuGet and got the same error message. My solution was to remove the newer version lines from the app.config file.

Could not load file or assembly or one of its dependencies. Access is denied. The issue is random, but after it happens once, it continues

If you still facing the issue try this:

Open your IIS Manager -> Application Pools -> select your app pool -> Advance Setting -> Under 'Process Model' set 'Load User Profile' setting as True

enter image description here

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

This problem started when I did 'Remove Unused References'. The website still worked on my local machine, but did not worked on the server after publishing.

Remove unused references

I fixed this problem by doing the following,

  1. Open 'Package Manager Console' in Visual Studio
  2. Uninstall-Package Microsoft.AspNet.Mvc
  3. Install-Package Microsoft.AspNet.Mvc

The located assembly's manifest definition does not match the assembly reference

This question is quite old, and I had the same error message recently with Azure DevOps Yaml pipelines and Dotnet Core 3.1. The problem was somewhat different than the other answers try to solve, so I will share my solution.

I had a solution with many projects for my own nuget packages. I had by accident added version-tag in the *.csproj files like this:

  <Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <Version>1.0.0</Version>
  </PropertyGroup>

I packed the nuget packages for all projects using Yaml with a DotnetCoreCLI@2 task:

 - task: DotNetCoreCLI@2
   displayName: 'pack'
   inputs:
     command: pack
     nobuild: true
     configurationToPack: 'Release'
     includesource: true
     includesymbols: true
     packagesToPack: 'MyNugetProject1.csproj;**/MyNugetProject2.csproj'
     versioningScheme: 'byEnvVar'
     versionEnvVar: 'GitVersion.SemVer'

The problem was that the version in the *.csproj files didn't match the version in the environment variable GitVersion.SemVer (specified by input-"versionEnvVar").

After removing all <Version>1.0.0</Version>-tags in the *.csproj files the assembly/fileversion for dll was automatically assigned by the environment-variable and both nuget and dll (assembly/fileversion) would have the same version and problem was solved.

How do I Validate the File Type of a File Upload?

Ensure that you always check for the file extension in server-side to ensure that no one can upload a malicious file such as .aspx, .asp etc.

How can I indent multiple lines in Xcode?

The keyboard shortcuts are ?+] for indent and ?+[ for un-indent.

  • In Xcode's preferences window, click the Key Bindings toolbar button. The Key Bindings section is where you customize keyboard shortcuts.

Fastest way to copy a file in Node.js

Improvement of one other answer.

Features:

  • If the dst folders do not exist, it will automatically create it. The other answer will only throw errors.
  • It returns a promise, which makes it easier to use in a larger project.
  • It allows you to copy multiple files, and the promise will be done when all of them are copied.

Usage:

var onePromise = copyFilePromise("src.txt", "dst.txt");
var anotherPromise = copyMultiFilePromise(new Array(new Array("src1.txt", "dst1.txt"), new Array("src2.txt", "dst2.txt")));

Code:

function copyFile(source, target, cb) {
    console.log("CopyFile", source, target);

    var ensureDirectoryExistence = function (filePath) {
        var dirname = path.dirname(filePath);
        if (fs.existsSync(dirname)) {
            return true;
        }
        ensureDirectoryExistence(dirname);
        fs.mkdirSync(dirname);
    }
    ensureDirectoryExistence(target);

    var cbCalled = false;
    var rd = fs.createReadStream(source);
    rd.on("error", function (err) {
        done(err);
    });
    var wr = fs.createWriteStream(target);
    wr.on("error", function (err) {
        done(err);
    });
    wr.on("close", function (ex) {
        done();
    });
    rd.pipe(wr);
    function done(err) {
        if (!cbCalled) {
            cb(err);
            cbCalled = true;
        }
    }
}

function copyFilePromise(source, target) {
    return new Promise(function (accept, reject) {
        copyFile(source, target, function (data) {
            if (data === undefined) {
                accept();
            } else {
                reject(data);
            }
        });
    });
}

function copyMultiFilePromise(srcTgtPairArr) {
    var copyFilePromiseArr = new Array();
    srcTgtPairArr.forEach(function (srcTgtPair) {
        copyFilePromiseArr.push(copyFilePromise(srcTgtPair[0], srcTgtPair[1]));
    });
    return Promise.all(copyFilePromiseArr);
}

What are carriage return, linefeed, and form feed?

In Short :

Carriage_return(\r or 0xD): To take control at starting of same line.

Line_Feed(\n or 0xA): To Take control at starting of next line.

form_feed(\f or 0xC): To take control at starting of next page.

Am I trying to connect to a TLS-enabled daemon without TLS?

In my case (Linux Mint 17) I did various things, and I'm not sure about which of them are totally necessary.

I included missing Ubuntu packages:

$ sudo apt-get install apparmor lxc cgroup-lite

A user was added to group docker:

$ sudo usermod -aG docker ${USER}

Started daemon (openSUSE just needs this)

$ sudo docker -d

Thanks\Attribution


Thanks Usman Ismail, because maybe it was just that last thing...

Stupid question but have you started the docker daemon? – Usman Ismail Dec 17 '14 at 15:04


Thanks also to github@MichaelJCole for the solution that worked for me, because I didn't check for the daemon when I read Usman's comment.

GitHub comment:

sudo apt-get install apparmor lxc cgroup-lite
sudo apt-get  install docker.io
# If you installed docker.io first, you'll have to start it manually
sudo docker -d
sudo docker run -i -t ubuntu /bin/bash

Thanks to fredjean.net post for noticing the missing packages and forget about the default Ubuntu installation instructions and google about other ways

It turns out that the cgroup-lite and the lxc packages are not installed by default on Linux Mint. Installing both then allowed me to run bash in the base image and then build and run my image.


Thanks to brettof86's comment about openSUSE

Sorting using Comparator- Descending order (User defined classes)

The java.util.Collections class has a sort method that takes a list and a custom Comparator. You can define your own Comparator to sort your Person object however you like.

C# listView, how do I add items to columns 2, 3 and 4 etc?

For your problem use like this:

ListViewItem row = new ListViewItem(); 
row.SubItems.Add(value.ToString()); 
listview1.Items.Add(row);

How to show image using ImageView in Android

shoud be @drawable/image where image could have any extension like: image.png, image.xml, image.gif. Android will automatically create a reference in R class with its name, so you cannot have in any drawable folder image.png and image.gif.

Horizontal scroll css?

Just set your width to auto:

#myWorkContent{
    width: auto;
    height:210px;
    border: 13px solid #bed5cd;
    overflow-x: scroll;
    overflow-y: hidden;
    white-space: nowrap;
}

This way your div can be as wide as possible, so you can add as many kitty images as possible ;3

Your div's width will expand based on the child elements it contains.

jsFiddle

Vue is not defined

Sometimes the problem may be if you import that like this:

const Vue = window.vue;

this may overwrite the original Vue reference.

What is output buffering?

UPDATE 2019. If you have dedicated server and SSD or better NVM, 3.5GHZ. You shouldn't use buffering to make faster loaded website in 100ms-150ms.

Becouse network is slowly than proccesing script in the 2019 with performance servers (severs,memory,disk) and with turn on APC PHP :) To generated script sometimes need only 70ms another time is only network takes time, from 10ms up to 150ms from located user-server.

so if you want be fast 150ms, buffering make slowl, becouse need extra collection buffer data it make extra cost. 10 years ago when server make 1s script, it was usefull.

Please becareful output_buffering have limit if you would like using jpg to loading it can flush automate and crash sending.

Cheers.

You can make fast river or You can make safely tama :)

Sending emails with Javascript

The way I'm doing it now is basically like this:

The HTML:

<textarea id="myText">
    Lorem ipsum...
</textarea>
<button onclick="sendMail(); return false">Send</button>

The Javascript:

function sendMail() {
    var link = "mailto:[email protected]"
             + "[email protected]"
             + "&subject=" + encodeURIComponent("This is my subject")
             + "&body=" + encodeURIComponent(document.getElementById('myText').value)
    ;
    
    window.location.href = link;
}

This, surprisingly, works rather well. The only problem is that if the body is particularly long (somewhere over 2000 characters), then it just opens a new email but there's no information in it. I suspect that it'd be to do with the maximum length of the URL being exceeded.

How can I create a correlation matrix in R?

Have a look at qtlcharts. It allows you to create interactive correlation matrices:

library(qtlcharts)
data(iris)
iris$Species <- NULL
iplotCorr(iris, reorder=TRUE)

enter image description here

It's more impressive when you correlate more variables, like in the package's vignette: enter image description here

How to create a JavaScript callback for knowing when an image is loaded?

Image.onload() will often work.

To use it, you'll need to be sure to bind the event handler before you set the src attribute.

Related Links:

Example Usage:

_x000D_
_x000D_
    window.onload = function () {_x000D_
_x000D_
        var logo = document.getElementById('sologo');_x000D_
_x000D_
        logo.onload = function () {_x000D_
            alert ("The image has loaded!");  _x000D_
        };_x000D_
_x000D_
        setTimeout(function(){_x000D_
            logo.src = 'https://edmullen.net/test/rc.jpg';         _x000D_
        }, 5000);_x000D_
    };
_x000D_
 <html>_x000D_
    <head>_x000D_
    <title>Image onload()</title>_x000D_
    </head>_x000D_
    <body>_x000D_
_x000D_
    <img src="#" alt="This image is going to load" id="sologo"/>_x000D_
_x000D_
    <script type="text/javascript">_x000D_
_x000D_
    </script>_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Powershell Error "The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function..."

Instead of Windows PowerShell, find the item in the Start Menu called SharePoint 2013 Management Shell:

enter image description here

Does not contain a static 'main' method suitable for an entry point

I was looking at this issue as well, and in my case the solution was too easy. I added a new empty project to the solution. The newly added project is automatically set as a console application. But since the project added was a 'empty' project, no Program.cs existed in that new project. (As expected)

All I needed to do was change the output type of the project properties to Class library

C# event with custom arguments

public enum MyEvents
{
    Event1
}

public class CustomEventArgs : EventArgs
{
    public MyEvents MyEvents { get; set; }
}


private EventHandler<CustomEventArgs> onTrigger;

public event EventHandler<CustomEventArgs> Trigger
{
    add
    {
        onTrigger += value;
    }
    remove
    {
        onTrigger -= value;
    }
}

protected void OnTrigger(CustomEventArgs e)
{
    if (onTrigger != null)
    {
        onTrigger(this, e);
    }
}

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

As the docs say, this can be achieved just by using set instead if push.

As the docs say, it is not recommended (due to possible overwrite by other user at the "same" time).

But in some cases it's helpful to have control over the feed's content including keys.

As an example of webapp in js, 193 being your id generated elsewhere, simply:

 firebase.initializeApp(firebaseConfig);
  var data={
      "name":"Prague"
  };
  firebase.database().ref().child('areas').child("193").set(data);

This will overwrite any area labeled 193 or create one if it's not existing yet.

WordPress: get author info from post id

I figured it out.

<?php $author_id=$post->post_author; ?>
<img src="<?php the_author_meta( 'avatar' , $author_id ); ?> " width="140" height="140" class="avatar" alt="<?php echo the_author_meta( 'display_name' , $author_id ); ?>" />
<?php the_author_meta( 'user_nicename' , $author_id ); ?> 

jQuery hyperlinks - href value?

<a href="#nogo">My Link</a>

CreateProcess error=2, The system cannot find the file specified

Assuming that winrar.exe is in the PATH, then Runtime.exec is capable of finding it, if it is not, you will need to supply the fully qualified path to it, for example, assuming winrar.exe is installed in C:/Program Files/WinRAR you would need to use something like...

p=r.exec("C:/Program Files/WinRAR/winrar x h:\\myjar.jar *.* h:\\new");

Personally, I would recommend that you use ProcessBuilder as it has some additional configuration abilities amongst other things. Where possible, you should also separate your command and parameters into separate String elements, it deals with things like spaces much better then a single String variable, for example...

ProcessBuilder pb = new ProcessBuilder(
    "C:/Program Files/WinRAR/winrar",
    "x",
    "myjar.jar",
    "*.*",
    "new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);

Process p = pb.start();

Don't forget to read the contents of the InputStream from the process, as failing to do so may stall the process

Bootstrap 3 - 100% height of custom div inside column

My solution was to make all the parents 100% and set a specific percentage for each row:

html, body,div[class^="container"] ,.column {
    height: 100%;
}

.row0 {height: 10%;}
.row1 {height: 40%;}
.row2 {height: 50%;}

Installing PIL with pip

I got the answer from a discussion here:

I tried

pip install --no-index -f http://dist.plone.org/thirdparty/ -U PIL

and it worked.

how to remove only one style property with jquery

The documentation for css() says that setting the style property to the empty string will remove that property if it does not reside in a stylesheet:

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <style> element.

Since your styles are inline, you can write:

$(selector).css("-moz-user-select", "");

Compare object instances for equality by their attributes

You should implement the method __eq__:

 class MyClass:
      def __init__(self, foo, bar, name):
           self.foo = foo
           self.bar = bar
           self.name = name

      def __eq__(self,other):
           if not isinstance(other,MyClass):
                return NotImplemented
           else:
                #string lists of all method names and properties of each of these objects
                prop_names1 = list(self.__dict__)
                prop_names2 = list(other.__dict__)

                n = len(prop_names1) #number of properties
                for i in range(n):
                     if getattr(self,prop_names1[i]) != getattr(other,prop_names2[i]):
                          return False

                return True

How to calculate the width of a text string of a specific font and font-size?

Swift 4

extension String {
    func SizeOf(_ font: UIFont) -> CGSize {
        return self.size(withAttributes: [NSAttributedStringKey.font: font])
    }
}

Get first day of week in PHP?

I found this quite frustrating given that my timezone is Australian and that strtotime() hates UK dates.

If the current day is a Sunday, then strtotime("monday this week") will return the day after.

To overcome this:

Caution: This is only valid for Australian/UK dates

$startOfWeek = (date('l') == 'Monday') ? date('d/m/Y 00:00') : date('d/m/Y', strtotime("last monday 00:00"));
$endOfWeek = (date('l') == 'Sunday') ? date('d/m/Y 23:59:59') : date('d/m/Y', strtotime("sunday 23:59:59"));

How to get the index of an element in an IEnumerable?

The best way to catch the position is by FindIndex This function is available only for List<>

Example

int id = listMyObject.FindIndex(x => x.Id == 15); 

If you have enumerator or array use this way

int id = myEnumerator.ToList().FindIndex(x => x.Id == 15); 

or

 int id = myArray.ToList().FindIndex(x => x.Id == 15); 

How to set focus on input field?

Just throwing in some coffee.

app.directive 'ngAltFocus', ->
    restrict: 'A'
    scope: ngAltFocus: '='
    link: (scope, el, attrs) ->
        scope.$watch 'ngAltFocus', (nv) -> el[0].focus() if nv

Pass arguments into C program from command line

Consider using getopt_long(). It allows both short and long options in any combination.

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>

/* Flag set by `--verbose'. */
static int verbose_flag;

int
main (int argc, char *argv[])
{
  while (1)
    {
      static struct option long_options[] =
    {
      /* This option set a flag. */
      {"verbose", no_argument,       &verbose_flag, 1},
      /* These options don't set a flag.
         We distinguish them by their indices. */
      {"blip",    no_argument,       0, 'b'},
      {"slip",    no_argument,       0, 's'},
      {0,         0,                 0,  0}
    };
      /* getopt_long stores the option index here. */
      int option_index = 0;

      int c = getopt_long (argc, argv, "bs",
               long_options, &option_index);

      /* Detect the end of the options. */
      if (c == -1)
    break;

      switch (c)
    {
    case 0:
      /* If this option set a flag, do nothing else now. */
      if (long_options[option_index].flag != 0)
        break;
      printf ("option %s", long_options[option_index].name);
      if (optarg)
        printf (" with arg %s", optarg);
      printf ("\n");
      break;
    case 'b':
      puts ("option -b\n");
      break;
    case 's':
      puts ("option -s\n");
      break;
    case '?':
      /* getopt_long already printed an error message. */
      break;

    default:
      abort ();
    }
    }

  if (verbose_flag)
    puts ("verbose flag is set");

  /* Print any remaining command line arguments (not options). */
  if (optind < argc)
    {
      printf ("non-option ARGV-elements: ");
      while (optind < argc)
    printf ("%s ", argv[optind++]);
      putchar ('\n');
    }

  return 0;
}

Related:

'^M' character at end of lines

Try using dos2unix to strip off the ^M.

Get raw POST body in Python Flask regardless of Content-Type header

I created a WSGI middleware that stores the raw body from the environ['wsgi.input'] stream. I saved the value in the WSGI environ so I could access it from request.environ['body_copy'] within my app.

This isn't necessary in Werkzeug or Flask, as request.get_data() will get the raw data regardless of content type, but with better handling of HTTP and WSGI behavior.

This reads the entire body into memory, which will be an issue if for example a large file is posted. This won't read anything if the Content-Length header is missing, so it won't handle streaming requests.

from io import BytesIO

class WSGICopyBody(object):
    def __init__(self, application):
        self.application = application

    def __call__(self, environ, start_response):
        length = int(environ.get('CONTENT_LENGTH') or 0)
        body = environ['wsgi.input'].read(length)
        environ['body_copy'] = body
        # replace the stream since it was exhausted by read()
        environ['wsgi.input'] = BytesIO(body)
        return self.application(environ, start_response)

app.wsgi_app = WSGICopyBody(app.wsgi_app)
request.environ['body_copy']

How to parse a String containing XML in Java and retrieve the value of the root node?

You could also use tools provided by the base JRE:

String msg = "<message>HELLO!</message>";
DocumentBuilder newDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document parse = newDocumentBuilder.parse(new ByteArrayInputStream(msg.getBytes()));
System.out.println(parse.getFirstChild().getTextContent());

Open local folder from link

Solution: Launching a Downloadable Link

The following works in all browsers, but as always there are caveats.

Background:

"URL Shortcuts" are OS dependent. The following solution is for MS Windows due to a lack of standards between environments.

If you require linux support for the solution below, please see this article.
* I have no connection to the article, YMMV.

URL shortcuts come in two forms:

  1. Files with .URL extensions are text based. Can be dynamically generated.

    [InternetShortcut]
    URL=file:///D:/

  2. Files with .LNK extension are binary. They can be generated dynamically, but require iShelLinkInterface implementer. This is complicated by default OS restrictions, which rightfully prevent an IIS process from reaching Shell.

.URL is the recommended solution, as dynamic generation is viable across Web Languages/Frameworks and allows for a KISS implementation.


Overview/Recap:

  1. Security restrictions will not allow you to open a path/launch explorer directly from the page (as stated by @Pekka).
  2. Sites hosted externally (not on your local computer) will not allow file:///... uri's under default security permissions.

Solution:

Provide a downloadable link (.URL or .LNK) to the resource. Browser behavior will be explained at end of post.

Option 1: Produce a .lnk file and save it to the server. Due to the binary nature of the .LNK file, this is not the recommended solution, but a pre-generated file should be viable.

Option 2: Produce a .url file and either save it to the server or dynamically generate it. In my situation, I am dynamically creating the .URL file.


Solution Details (.URL):

  1. Add .url to the available MIME types in your web server.

    For IIS open the site, choose MIME Types, and add the following:

    File name Extension= .url
    MIME type: application/internet-shortcut

    Per @cremax ... For Webkit Browsers like Chrome on Apache Servers add this code to .htaccess or http.config:

    SetEnvIf Request_URI ".url$" requested_url=url Header add Content-Disposition "attachment" env=requested_url

  2. The .url file is a text file formatted as follows (again, this can be dynamically generated).

    File Contents:

    [InternetShortcut]
    URL=file:///D:

  3. Provide a link to the script that generates the .url file, or to the file itself.

    If you've simply uploaded a .url file to your server, add the following to your HTML:

    <a href="URIShortcut.url">Round-About Linking</a>


Browser Dependent Behavior

Chrome: Download/Save file.url then open
In Chrome, this behavior can be augmented by choosing the "Always open files of this type" option.

FireFox: Download/Save file.url then open

Internet Explorer: Click “Open” and go straight to directory (no need to save shortcut)

Internet Explorer has the preferred behavior, but Chrome and Firefox are at least serviceable.

Java: Date from unix timestamp

If you are converting a timestamp value on a different machine, you should also check the timezone of that machine. For example;

The above decriptions will result different Date values, if you run with EST or UTC timezones.

To set the timezone; aka to UTC, you can simply rewrite;

    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    java.util.Date time= new java.util.Date((Long.parseLong(timestamp)*1000));

Split string based on regex

You could use a lookahead:

re.split(r'[ ](?=[A-Z]+\b)', input)

This will split at every space that is followed by a string of upper-case letters which end in a word-boundary.

Note that the square brackets are only for readability and could as well be omitted.

If it is enough that the first letter of a word is upper case (so if you would want to split in front of Hello as well) it gets even easier:

re.split(r'[ ](?=[A-Z])', input)

Now this splits at every space followed by any upper-case letter.

Pad a number with leading zeros in JavaScript

For fun, instead of using a loop to create the extra zeros:

function zeroPad(n,length){
  var s=n+"",needed=length-s.length;
  if (needed>0) s=(Math.pow(10,needed)+"").slice(1)+s;
  return s;
}

Regular Expression to get all characters before "-"

You could just use another non-regex based method. Someone gave the suggestion of using Substring, but you could also use Split:

string testString = "my-string";
string[] splitString = testString.Split("-");
string resultingString = splitString[0]; //my

See http://msdn.microsoft.com/en-US/library/ms228388%28v=VS.80%29.aspx for another good example.

OR, AND Operator

Logical OR is ||, logical AND is &&. If you need the negation NOT, prefix your expression with !.

Example:

X = (A && B) || C || !D;

Then X will be true when either A and B are true or if C is true or if D is not true (i.e. false).

If you wanted bit-wise AND/OR/NOT, you would use &, | and ~. But if you are dealing with boolean/truth values, you do not want to use those. They do not provide short-circuit evaluation for example due to the way a bitwise operation works.

Member '<method>' cannot be accessed with an instance reference

I got here googling for C# compiler error CS0176, through (duplicate) question Static member instance reference issue.

In my case, the error happened because I had a static method and an extension method with the same name. For that, see Static method and extension method with same name.

[May be this should have been a comment. Sorry that I don't have enough reputation yet.]

How to Convert double to int in C?

This is the notorious floating point rounding issue. Just add a very small number, to correct the issue.

double a;
a=3669.0;
int b;
b=a+ 1e-9;

What is the difference between null and System.DBNull.Value?

Null is similar to zero pointer in C++. So it is a reference which not pointing to any value.

DBNull.Value is completely different and is a constant which is returned when a field value contains NULL.

Add centered text to the middle of a <hr/>-like line

I made a fiddle that uses FlexBox and will also give you different styles of HR (double line, symbols in the center of the line, drop shadow, inset, dashed, etc).

CSS

button {
    padding: 8px;
    border-radius: 4px;
    background-color: #fff;
    border: 1px solid #ccc;
    margin: 2px;
  }

  button:hover {
    cursor: pointer;
  }

  button.active {
    background-color: rgb(34, 179, 247);
    color: #fff;
  }

  .codeBlock {
    display: none;
  }

  .htmlCode, .cssCode {
    background-color: rgba(34, 179, 247, 0.5); 
    width: 100%;
    padding: 10px;
  }

  .divider {
    display: flex;
    flex-direction: row;
    flex-flow: row;
    width: 100%;
  }

  .divider.fixed {
    width: 400px;
  }

  .divider > label {
    align-self: baseline;
    flex-grow: 2;
    white-space: nowrap;
  }

  .divider > hr {
    margin-top: 10px;
    width: 100%;
    border: 0;
    height: 1px;
    background: #666;
  }

  .divider.left > label {
    order: 1;
    padding-right: 5px;
  }

  .divider.left > hr {
    order: 2
  }

  .divider.right > label {
    padding-left: 5px;
  }
  /* hr bars with centered text */
  /* first HR in a centered version */

  .divider.center >:first-child {
    margin-right: 5px;
  }
  /* second HR in a centered version */

  .divider.center >:last-child {
    margin-left: 5px;
  }
  /** HR style variations **/

  hr.gradient {
    background: transparent;
    background-image: linear-gradient(to right, #f00, #333, #f00);
  }

  hr.gradient2 {
    background: transparent;
    background-image: linear-gradient(to right, rgba(0, 0, 0, 0), rgba(255, 0, 0, 0.5), rgba(0, 0, 0, 0));
  }

  hr.dashed {
    background: transparent;
    border: 0;
    border-top: 1px dashed #666;
  }

  hr.dropshadow {
    background: transparent;
    height: 12px;
    border: 0;
    box-shadow: inset 0 12px 12px -12px rgba(0, 0, 0, 0.5);
  }

  hr.blur {
    background: transparent;
    border: 0;
    height: 0;
    /* Firefox... */
    box-shadow: 0 0 10px 1px black;
  }

  hr.blur:after {
    background: transparent;
    /* Not really supposed to work, but does */
    content: "\00a0";
    /* Prevent margin collapse */
  }

  hr.inset {
    background: transparent;
    border: 0;
    height: 0;
    border-top: 1px solid rgba(0, 0, 0, 0.1);
    border-bottom: 1px solid rgba(255, 255, 255, 0.3);
  }

  hr.flared {
    background: transparent;
    overflow: visible;
    /* For IE */
    height: 30px;
    border-style: solid;
    border-color: black;
    border-width: 1px 0 0 0;
    border-radius: 20px;
  }

  hr.flared:before {
    background: transparent;
    display: block;
    content: "";
    height: 30px;
    margin-top: -31px;
    border-style: solid;
    border-color: black;
    border-width: 0 0 1px 0;
    border-radius: 20px;
  }

  hr.double {
    background: transparent;
    overflow: visible;
    /* For IE */
    padding: 0;
    border: none;
    border-top: medium double #333;
    color: #333;
    text-align: center;
  }

  hr.double:after {
    background: transparent;
    content: "§";
    display: inline-block;
    position: relative;
    top: -0.7em;
    font-size: 1.5em;
    padding: 0 0.25em;
  }

HTML

<div class="divider left">
  <hr />
  <label>Welcome!</label>
</div>
<p>&nbsp;</p>
<div class="divider right">
  <hr />
  <label>Welcome!</label>
</div>
<p>&nbsp;</p>
<div class="divider center">
  <hr />
  <label>Welcome!</label>
  <hr />
</div>
<p>&nbsp;</p>
<div class="divider left fixed">
  <hr />
  <label>Welcome!</label>
</div>
<p>&nbsp;</p>
<div class="divider right fixed">
  <hr />
  <label>Welcome!</label>
</div>
<p>&nbsp;</p>
<div class="divider center fixed">
  <hr />
  <label>Welcome!</label>
  <hr />
</div>

Or here's an interactive Fiddle: http://jsfiddle.net/mpyszenj/439/

What is the difference between aggregation, composition and dependency?

Aggregation - separable part to whole. The part has a identity of its own, separate from what it is part of. You could pick that part and move it to another object. (real world examples: wheel -> car, bloodcell -> body)

Composition - non-separable part of the whole. You cannot move the part to another object. more like a property. (real world examples: curve -> road, personality -> person, max_speed -> car, property of object -> object )

Note that a relation that is an aggregate in one design can be a composition in another. Its all about how the relation is to be used in that specific design.

dependency - sensitive to change. (amount of rain -> weather, headposition -> bodyposition)

Note: "Bloodcell" -> Blood" could be "Composition" as Blood Cells can not exist without the entity called Blood. "Blood" -> Body" could be "Aggregation" as Blood can exist without the entity called Body.

How do I list / export private keys from a keystore?

This question came up on stackexchange security, one of the suggestions was to use Keystore explorer

https://security.stackexchange.com/questions/3779/how-can-i-export-my-private-key-from-a-java-keytool-keystore

Having just tried it, it works really well and I strongly recommend it.

VMware Workstation and Device/Credential Guard are not compatible

I don't know why but version 3.6 of DG_Readiness_Tool didn't work for me. After I restarted my laptop problem still persisted. I was looking for solution and finally I came across version 3.7 of the tool and this time problem went away. Here you can find latest powershell script:

DG_Readiness_Tool_v3.7

How to cin to a vector

These were two methods I tried. Both are fine to use.

int main() {
       
        int size,temp;
        cin>>size;
        vector<int> ar(size);
    //method 1 
      for(auto i=0;i<size;i++)
          {   cin>>temp;
              ar.insert(ar.begin()+i,temp);
          }
          for (auto i:ar) 
            cout <<i<<" "; 
            
     //method 2
     for(int i=0;i<size;i++)
     {
        cin>>ar[i];
     }
     
     for (auto i:ar) 
            cout <<i<<" "; 
        return 0;
    }

data.frame Group By column

This is a common question. In base, the option you're looking for is aggregate. Assuming your data.frame is called "mydf", you can use the following.

> aggregate(B ~ A, mydf, sum)
  A  B
1 1  5
2 2  3
3 3 11

I would also recommend looking into the "data.table" package.

> library(data.table)
> DT <- data.table(mydf)
> DT[, sum(B), by = A]
   A V1
1: 1  5
2: 2  3
3: 3 11

Visual Studio Code: Auto-refresh file changes

VSCode will never refresh the file if you have changes in that file that are not saved to disk. However, if the file is open and does not have changes, it will replace with the changes on disk, that is true.

There is currently no way to disable this behaviour.

What is an undefined reference/unresolved external symbol error and how do I fix it?

Even though this is a pretty old questions with multiple accepted answers, I'd like to share how to resolve an obscure "undefined reference to" error.

Different versions of libraries

I was using an alias to refer to std::filesystem::path: filesystem is in the standard library since C++17 but my program needed to also compile in C++14 so I decided to use a variable alias:

#if (defined _GLIBCXX_EXPERIMENTAL_FILESYSTEM) //is the included filesystem library experimental? (C++14 and newer: <experimental/filesystem>)
using path_t = std::experimental::filesystem::path;
#elif (defined _GLIBCXX_FILESYSTEM) //not experimental (C++17 and newer: <filesystem>)
using path_t = std::filesystem::path;
#endif

Let's say I have three files: main.cpp, file.h, file.cpp:

  • file.h #include's <experimental::filesystem> and contains the code above
  • file.cpp, the implementation of file.h, #include's "file.h"
  • main.cpp #include's <filesystem> and "file.h"

Note the different libraries used in main.cpp and file.h. Since main.cpp #include'd "file.h" after <filesystem>, the version of filesystem used there was the C++17 one. I used to compile the program with the following commands:

$ g++ -g -std=c++17 -c main.cpp -> compiles main.cpp to main.o
$ g++ -g -std=c++17 -c file.cpp -> compiles file.cpp and file.h to file.o
$ g++ -g -std=c++17 -o executable main.o file.o -lstdc++fs -> links main.o and file.o

This way any function contained in file.o and used in main.o that required path_t gave "undefined reference" errors because main.o referred to std::filesystem::path but file.o to std::experimental::filesystem::path.

Resolution

To fix this I just needed to change <experimental::filesystem> in file.h to <filesystem>.

Pointer to incomplete class type is not allowed

One thing to check for...

If your class is defined as a typedef:

typedef struct myclass { };

Then you try to refer to it as struct myclass anywhere else, you'll get Incomplete Type errors left and right. It's sometimes a mistake to forget the class/struct was typedef'ed. If that's the case, remove "struct" from:

typedef struct mystruct {}...

struct mystruct *myvar = value;

Instead use...

mystruct *myvar = value;

Common mistake.

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

Keep in mind that it's the user that is running the oracle database that must have write permissions to the /defaultdir directory, not the user logged into oracle. Typically you're running the database as the user "Oracle". It's not the same user (necessarily) that you created the external table with.

Check your directory permissions, too.

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

Remove the FormsModule from Declaration:[] and Add the FormsModule in imports:[]

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Twitter Bootstrap dropdown menu

I had a similar problem and it was the version of bootstrap.js included in my visual studio project. I linked to here and it worked great

 <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>

Convenient C++ struct initialisation

What about this syntax?

typedef struct
{
    int a;
    short b;
}
ABCD;

ABCD abc = { abc.a = 5, abc.b = 7 };

Just tested on a Microsoft Visual C++ 2015 and on g++ 6.0.2. Working OK.
You can make a specific macro also if you want to avoid duplicating variable name.

I need to convert an int variable to double

Converting to double can be done by casting an int to a double:

You can convert an int to a double by using this mechnism like so:

int i = 3; // i is 3
double d = (double) i; // d = 3.0

Alternative (using Java's automatic type recognition):

double d = 1.0 * i; // d = 3.0

Implementing this in your code would be something like:

double firstSolution = ((double)(b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21));
double secondSolution = ((double)(b2 * a11 - b1 * a21) / (double)(a11 * a22 - a12 * a21));

Alternatively you can use a hard-parameter of type double (1.0) to have java to the work for you, like so:

double firstSolution = ((1.0 * (b1 * a22 - b2 * a12)) / (1.0 * (a11 * a22 - a12 * a21)));
double secondSolution = ((1.0 * (b2 * a11 - b1 * a21)) / (1.0 * (a11 * a22 - a12 * a21)));

Good luck.

How to extract filename.tar.gz file

If file filename.tar.gz gives this message: POSIX tar archive, the archive is a tar, not a GZip archive.

Unpack a tar without the z, it is for gzipped (compressed), only:

mv filename.tar.gz filename.tar # optional
tar xvf filename.tar

Or try a generic Unpacker like unp (https://packages.qa.debian.org/u/unp.html), a script for unpacking a wide variety of archive formats.

determine the file type:

$ file ~/Downloads/filename.tbz2
/User/Name/Downloads/filename.tbz2: bzip2 compressed data, block size = 400k

What's the difference between Instant and LocalDateTime?

Instant corresponds to time on the prime meridian (Greenwich).

Whereas LocalDateTime relative to OS time zone settings, and

cannot represent an instant without additional information such as an offset or time-zone.

what is the size of an enum type data in C++?

With my now ageing Borland C++ Builder compiler enums can be 1,2 or 4 bytes, although it does have a flag you can flip to force it to use ints.

I guess it's compiler specific.

Pass all variables from one shell script to another?

Fatal Error gave a straightforward possibility: source your second script! if you're worried that this second script may alter some of your precious variables, you can always source it in a subshell:

( . ./test2.sh )

The parentheses will make the source happen in a subshell, so that the parent shell will not see the modifications test2.sh could perform.


There's another possibility that should definitely be referenced here: use set -a.

From the POSIX set reference:

-a: When this option is on, the export attribute shall be set for each variable to which an assignment is performed; see the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.21, Variable Assignment. If the assignment precedes a utility name in a command, the export attribute shall not persist in the current execution environment after the utility completes, with the exception that preceding one of the special built-in utilities causes the export attribute to persist after the built-in has completed. If the assignment does not precede a utility name in the command, or if the assignment is a result of the operation of the getopts or read utilities, the export attribute shall persist until the variable is unset.

From the Bash Manual:

-a: Mark variables and function which are modified or created for export to the environment of subsequent commands.

So in your case:

set -a
TESTVARIABLE=hellohelloheloo
# ...
# Here put all the variables that will be marked for export
# and that will be available from within test2 (and all other commands).
# If test2 modifies the variables, the modifications will never be
# seen in the present script!
set +a

./test2.sh

 # Here, even if test2 modifies TESTVARIABLE, you'll still have
 # TESTVARIABLE=hellohelloheloo

Observe that the specs only specify that with set -a the variable is marked for export. That is:

set -a
a=b
set +a
a=c
bash -c 'echo "$a"'

will echo c and not an empty line nor b (that is, set +a doesn't unmark for export, nor does it “save” the value of the assignment only for the exported environment). This is, of course, the most natural behavior.

Conclusion: using set -a/set +a can be less tedious than exporting manually all the variables. It is superior to sourcing the second script, as it will work for any command, not only the ones written in the same shell language.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

You need to decode data from input string into unicode, before using it, to avoid encoding problems.

field.text = data.decode("utf8")

Char array in a struct - incompatible assignment?

sara is the struct itself, not a pointer (i.e. the variable representing location on the stack where actual struct data is stored). Therefore, *sara is meaningless and won't compile.

Mysql - How to quit/exit from stored procedure

MainLabel:BEGIN

IF (<condition>) IS NOT NULL THEN
    LEAVE MainLabel;
END IF; 

....code

i.e.
IF (@skipMe) IS NOT NULL THEN /* @skipMe returns Null if never set or set to NULL */
     LEAVE MainLabel;
END IF;

Can't include C++ headers like vector in Android NDK

In android NDK go to android-ndk-r9b>/sources/cxx-stl/gnu-libstdc++/4.X/include in linux machines

I've found solution from the below link http://osdir.com/ml/android-ndk/2011-09/msg00336.html

In c++ what does a tilde "~" before a function name signify?

It's the destructor, it destroys the instance, frees up memory, etc. etc.

Here's a description from ibm.com:

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.

See https://www.ibm.com/support/knowledgecenter/en/ssw_ibm_i_74/rzarg/cplr380.htm

How to set the margin or padding as percentage of height of parent container?

The fix is that yes, vertical padding and margin are relative to width, but top and bottom aren't.

So just place a div inside another, and in the inner div, use something like top:50% (remember position matters if it still doesn't work)

Export MySQL database using PHP only

<?php
 $dbhost = 'localhost:3036';
 $dbuser = 'root';
 $dbpass = 'rootpassword';

 $conn = mysql_connect($dbhost, $dbuser, $dbpass);

 if(! $conn ) {
  die('Could not connect: ' . mysql_error());
 }

 $table_name = "employee";
 $backup_file  = "/tmp/employee.sql";
 $sql = "SELECT * INTO OUTFILE '$backup_file' FROM $table_name";

 mysql_select_db('test_db');
 $retval = mysql_query( $sql, $conn );

 if(! $retval ) {
  die('Could not take data backup: ' . mysql_error());
 }

 echo "Backedup  data successfully\n";

 mysql_close($conn);
?>

How to get datas from List<Object> (Java)?

Thanks All for your responses. Good solution was to use 'brain`s' method:

List<Object> list = getHouseInfo();
for (int i=0; i<list.size; i++){
Object[] row = (Object[]) list.get(i);
System.out.println("Element "+i+Arrays.toString(row));
}

Problem solved. Thanks again.

Transform only one axis to log10 scale with ggplot2

I had a similar problem and this scale worked for me like a charm:

breaks = 10**(1:10)
scale_y_log10(breaks = breaks, labels = comma(breaks))

as you want the intermediate levels, too (10^3.5), you need to tweak the formatting:

breaks = 10**(1:10 * 0.5)
m <- ggplot(diamonds, aes(y = price, x = color)) + geom_boxplot()
m + scale_y_log10(breaks = breaks, labels = comma(breaks, digits = 1))

After executing::

enter image description here

What Java FTP client library should I use?

Check out Apache commons-net, which contains FTP utilities. Off the top of my head I'm not sure if it meets all of your requirements, but it's certainly free!

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

This error is currently being fixed: https://chromium-review.googlesource.com/c/chromium/src/+/2001234

But it helped me, changing nginx settings:

  • turning on gzip;
  • add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
  • expires off;

In my case, Nginx acts as a reverse proxy for Node.js application.

Error inflating when extending a class

I think I figured out why this wasn't working. I was only providing a constructor for the case of one parameter 'context' when I should have provided a constructor for the two parameter 'Context, AttributeSet' case. I also needed to give the constructor(s) public access. Here's my fix:

public class GhostSurfaceCameraView extends SurfaceView implements SurfaceHolder.Callback {
        SurfaceHolder mHolder;
        Camera mCamera;

        public GhostSurfaceCameraView(Context context)
        {
            super(context);
            init();
        }
        public GhostSurfaceCameraView(Context context, AttributeSet attrs)
        {
            super(context, attrs);
            init();
        }
        public GhostSurfaceCameraView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init();
        }

How to import jquery using ES6 syntax?

If you are using Webpack 4, the answer is to use the ProvidePlugin. Their documentation specifically covers angular.js with jquery use case:

new webpack.ProvidePlugin({
  'window.jQuery': 'jquery'
});

The issue is that when using import syntax angular.js and jquery will always be imported before you have a chance to assign jquery to window.jQuery (import statements will always run first no matter where they are in the code!). This means that angular will always see window.jQuery as undefined until you use ProvidePlugin.

PermGen elimination in JDK 8

Because the PermGen space was removed. Memory management has changed a bit.

java-8-permgen-metaspace

How to list active connections on PostgreSQL?

SELECT * FROM pg_stat_activity WHERE datname = 'dbname' and state = 'active';

Since pg_stat_activity contains connection statistics of all databases having any state, either idle or active, database name and connection state should be included in the query to get the desired output.

Python 3: UnboundLocalError: local variable referenced before assignment

This is because, even though Var1 exists, you're also using an assignment statement on the name Var1 inside of the function (Var1 -= 1 at the bottom line). Naturally, this creates a variable inside the function's scope called Var1 (truthfully, a -= or += will only update (reassign) an existing variable, but for reasons unknown (likely consistency in this context), Python treats it as an assignment). The Python interpreter sees this at module load time and decides (correctly so) that the global scope's Var1 should not be used inside the local scope, which leads to a problem when you try to reference the variable before it is locally assigned.

Using global variables, outside of necessity, is usually frowned upon by Python developers, because it leads to confusing and problematic code. However, if you'd like to use them to accomplish what your code is implying, you can simply add:

global Var1, Var2

inside the top of your function. This will tell Python that you don't intend to define a Var1 or Var2 variable inside the function's local scope. The Python interpreter sees this at module load time and decides (correctly so) to look up any references to the aforementioned variables in the global scope.

Some Resources

  • the Python website has a great explanation for this common issue.
  • Python 3 offers a related nonlocal statement - check that out as well.

Find stored procedure by name

You can use this query:

SELECT 
    ROUTINE_CATALOG AS DatabaseName ,
    ROUTINE_SCHEMA AS SchemaName,
    SPECIFIC_NAME AS SPName ,
    ROUTINE_DEFINITION AS SPBody ,
    CREATED AS CreatedDate,
    LAST_ALTERED AS LastModificationDate
FROM INFORMATION_SCHEMA.ROUTINES
WHERE 
    (ROUTINE_DEFINITION LIKE '%%')
    AND 
    (ROUTINE_TYPE='PROCEDURE')
    AND
    (SPECIFIC_NAME LIKE '%AssessmentToolDegreeDel')

As you can see, you can do search inside the body of Stored Procedure also.

Get the position of a spinner in Android

The way to get the selection of the spinner is:

  spinner1.getSelectedItemPosition();

Documentation reference: http://developer.android.com/reference/android/widget/AdapterView.html#getSelectedItemPosition()

However, in your code, the one place you are referencing it is within your setOnItemSelectedListener(). It is not necessary to poll the spinner, because the onItemSelected method gets passed the position as the "position" variable.

So you could change that line to:

TestProjectActivity.this.number = position + 1;

If that does not fix the problem, please post the error message generated when your app crashes.

Run a command over SSH with JSch

This is a shameless plug, but I'm just now writing some extensive Javadoc for JSch.

Also, there is now a Manual in the JSch Wiki (written mainly by me).


About the original question, there is not really an example for handling the streams. Reading/writing a stream is done as always.

But there simply can't be a sure way to know when one command in a shell has finished just from reading the shell's output (this is independent of the SSH protocol).

If the shell is interactive, i.e. it has a terminal attached, it will usually print a prompt, which you could try to recognize. But at least theoretically this prompt string could also occur in normal output from a command. If you want to be sure, open individual exec channels for each command instead of using a shell channel. The shell channel is mainly used for interactive use by a human user, I think.

Pandas Merging 101

This post aims to give readers a primer on SQL-flavored merging with pandas, how to use it, and when not to use it.

In particular, here's what this post will go through:

  • The basics - types of joins (LEFT, RIGHT, OUTER, INNER)

    • merging with different column names
    • merging with multiple columns
    • avoiding duplicate merge key column in output

What this post (and other posts by me on this thread) will not go through:

  • Performance-related discussions and timings (for now). Mostly notable mentions of better alternatives, wherever appropriate.
  • Handling suffixes, removing extra columns, renaming outputs, and other specific use cases. There are other (read: better) posts that deal with that, so figure it out!

Note
Most examples default to INNER JOIN operations while demonstrating various features, unless otherwise specified.

Furthermore, all the DataFrames here can be copied and replicated so you can play with them. Also, see this post on how to read DataFrames from your clipboard.

Lastly, all visual representation of JOIN operations have been hand-drawn using Google Drawings. Inspiration from here.



Enough Talk, just show me how to use merge!

Setup & Basics

np.random.seed(0)
left = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'value': np.random.randn(4)})    
right = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'value': np.random.randn(4)})
  
left

  key     value
0   A  1.764052
1   B  0.400157
2   C  0.978738
3   D  2.240893

right

  key     value
0   B  1.867558
1   D -0.977278
2   E  0.950088
3   F -0.151357

For the sake of simplicity, the key column has the same name (for now).

An INNER JOIN is represented by

Note
This, along with the forthcoming figures all follow this convention:

  • blue indicates rows that are present in the merge result
  • red indicates rows that are excluded from the result (i.e., removed)
  • green indicates missing values that are replaced with NaNs in the result

To perform an INNER JOIN, call merge on the left DataFrame, specifying the right DataFrame and the join key (at the very least) as arguments.

left.merge(right, on='key')
# Or, if you want to be explicit
# left.merge(right, on='key', how='inner')

  key   value_x   value_y
0   B  0.400157  1.867558
1   D  2.240893 -0.977278

This returns only rows from left and right which share a common key (in this example, "B" and "D).

A LEFT OUTER JOIN, or LEFT JOIN is represented by

This can be performed by specifying how='left'.

left.merge(right, on='key', how='left')

  key   value_x   value_y
0   A  1.764052       NaN
1   B  0.400157  1.867558
2   C  0.978738       NaN
3   D  2.240893 -0.977278

Carefully note the placement of NaNs here. If you specify how='left', then only keys from left are used, and missing data from right is replaced by NaN.

And similarly, for a RIGHT OUTER JOIN, or RIGHT JOIN which is...

...specify how='right':

left.merge(right, on='key', how='right')

  key   value_x   value_y
0   B  0.400157  1.867558
1   D  2.240893 -0.977278
2   E       NaN  0.950088
3   F       NaN -0.151357

Here, keys from right are used, and missing data from left is replaced by NaN.

Finally, for the FULL OUTER JOIN, given by

specify how='outer'.

left.merge(right, on='key', how='outer')

  key   value_x   value_y
0   A  1.764052       NaN
1   B  0.400157  1.867558
2   C  0.978738       NaN
3   D  2.240893 -0.977278
4   E       NaN  0.950088
5   F       NaN -0.151357

This uses the keys from both frames, and NaNs are inserted for missing rows in both.

The documentation summarizes these various merges nicely:

enter image description here


Other JOINs - LEFT-Excluding, RIGHT-Excluding, and FULL-Excluding/ANTI JOINs

If you need LEFT-Excluding JOINs and RIGHT-Excluding JOINs in two steps.

For LEFT-Excluding JOIN, represented as

Start by performing a LEFT OUTER JOIN and then filtering (excluding!) rows coming from left only,

(left.merge(right, on='key', how='left', indicator=True)
     .query('_merge == "left_only"')
     .drop('_merge', 1))

  key   value_x  value_y
0   A  1.764052      NaN
2   C  0.978738      NaN

Where,

left.merge(right, on='key', how='left', indicator=True)

  key   value_x   value_y     _merge
0   A  1.764052       NaN  left_only
1   B  0.400157  1.867558       both
2   C  0.978738       NaN  left_only
3   D  2.240893 -0.977278       both

And similarly, for a RIGHT-Excluding JOIN,

(left.merge(right, on='key', how='right', indicator=True)
     .query('_merge == "right_only"')
     .drop('_merge', 1))

  key  value_x   value_y
2   E      NaN  0.950088
3   F      NaN -0.151357

Lastly, if you are required to do a merge that only retains keys from the left or right, but not both (IOW, performing an ANTI-JOIN),

You can do this in similar fashion—

(left.merge(right, on='key', how='outer', indicator=True)
     .query('_merge != "both"')
     .drop('_merge', 1))

  key   value_x   value_y
0   A  1.764052       NaN
2   C  0.978738       NaN
4   E       NaN  0.950088
5   F       NaN -0.151357

Different names for key columns

If the key columns are named differently—for example, left has keyLeft, and right has keyRight instead of key—then you will have to specify left_on and right_on as arguments instead of on:

left2 = left.rename({'key':'keyLeft'}, axis=1)
right2 = right.rename({'key':'keyRight'}, axis=1)

left2
 
  keyLeft     value
0       A  1.764052
1       B  0.400157
2       C  0.978738
3       D  2.240893

right2

  keyRight     value
0        B  1.867558
1        D -0.977278
2        E  0.950088
3        F -0.151357
left2.merge(right2, left_on='keyLeft', right_on='keyRight', how='inner')

  keyLeft   value_x keyRight   value_y
0       B  0.400157        B  1.867558
1       D  2.240893        D -0.977278

Avoiding duplicate key column in output

When merging on keyLeft from left and keyRight from right, if you only want either of the keyLeft or keyRight (but not both) in the output, you can start by setting the index as a preliminary step.

left3 = left2.set_index('keyLeft')
left3.merge(right2, left_index=True, right_on='keyRight')
    
    value_x keyRight   value_y
0  0.400157        B  1.867558
1  2.240893        D -0.977278

Contrast this with the output of the command just before (that is, the output of left2.merge(right2, left_on='keyLeft', right_on='keyRight', how='inner')), you'll notice keyLeft is missing. You can figure out what column to keep based on which frame's index is set as the key. This may matter when, say, performing some OUTER JOIN operation.


Merging only a single column from one of the DataFrames

For example, consider

right3 = right.assign(newcol=np.arange(len(right)))
right3
  key     value  newcol
0   B  1.867558       0
1   D -0.977278       1
2   E  0.950088       2
3   F -0.151357       3

If you are required to merge only "new_val" (without any of the other columns), you can usually just subset columns before merging:

left.merge(right3[['key', 'newcol']], on='key')

  key     value  newcol
0   B  0.400157       0
1   D  2.240893       1

If you're doing a LEFT OUTER JOIN, a more performant solution would involve map:

# left['newcol'] = left['key'].map(right3.set_index('key')['newcol']))
left.assign(newcol=left['key'].map(right3.set_index('key')['newcol']))

  key     value  newcol
0   A  1.764052     NaN
1   B  0.400157     0.0
2   C  0.978738     NaN
3   D  2.240893     1.0

As mentioned, this is similar to, but faster than

left.merge(right3[['key', 'newcol']], on='key', how='left')

  key     value  newcol
0   A  1.764052     NaN
1   B  0.400157     0.0
2   C  0.978738     NaN
3   D  2.240893     1.0

Merging on multiple columns

To join on more than one column, specify a list for on (or left_on and right_on, as appropriate).

left.merge(right, on=['key1', 'key2'] ...)

Or, in the event the names are different,

left.merge(right, left_on=['lkey1', 'lkey2'], right_on=['rkey1', 'rkey2'])

Other useful merge* operations and functions

This section only covers the very basics, and is designed to only whet your appetite. For more examples and cases, see the documentation on merge, join, and concat as well as the links to the function specs.



Continue Reading

Jump to other topics in Pandas Merging 101 to continue learning:

* you are here

Differences between ConstraintLayout and RelativeLayout

Following are the differences/advantages:

  1. Constraint Layout has dual power of both Relative Layout as well as Linear layout: Set relative positions of views ( like Relative layout ) and also set weights for dynamic UI (which was only possible in Linear Layout).

  2. A very powerful use is grouping of elements by forming a chain. This way we can form a group of views which as a whole can be placed in a desired way without adding another layer of hierarchy just to form another group of views.

  3. In addition to weights, we can apply horizontal and vertical bias which is nothing but the percentage of displacement from the centre. ( bias of 0.5 means centrally aligned. Any value less or more means corresponding movement in the respective direction ) .

  4. Another very important feature is that it respects and provides the functionality to handle the GONE views so that layouts do not break if some view is set to GONE through java code. More can be found here: https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html#VisibilityBehavior

  5. Provides power of automatic constraint applying by the use of Blue print and Visual Editor tool which makes it easy to design a page.

All these features lead to flattening of the view hierarchy which improves performance and also helps in making responsive and dynamic UI which can more easily adapt to different screen size and density.

Here is the best place to learn quickly: https://codelabs.developers.google.com/codelabs/constraint-layout/#0

Disabling Strict Standards in PHP 5.4

As the commenters have stated the best option is to fix the errors, but with limited time or knowledge, that's not always possible. In your php.ini change

error_reporting = E_ALL

to

error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT

If you don't have access to the php.ini, you can potentially put this in your .htaccess file:

php_value error_reporting 30711

This is the E_ALL value (32767) and the removing the E_STRICT (2048) and E_NOTICE (8) values.

If you don't have access to the .htaccess file or it's not enabled, you'll probably need to put this at the top of the PHP section of any script that gets loaded from a browser call:

error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);

One of those should help you be able to use the software. The notices and strict stuff are indicators of problems or potential problems though and you may find some of the code is not working correctly in PHP 5.4.

Getting values from query string in an url using AngularJS $location

My fix is more simple, create a factory, and implement as one variable. For example

_x000D_
_x000D_
angular.module('myApp', [])_x000D_
_x000D_
// This a searchCustom factory. Copy the factory and implement in the controller_x000D_
.factory("searchCustom", function($http,$log){    _x000D_
    return {_x000D_
        valuesParams : function(params){_x000D_
            paramsResult = [];_x000D_
            params = params.replace('(', '').replace(')','').split("&");_x000D_
            _x000D_
            for(x in params){_x000D_
                paramsKeyTmp = params[x].split("=");_x000D_
                _x000D_
                // Si el parametro esta disponible anexamos al vector paramResult_x000D_
                if (paramsKeyTmp[1] !== '' && paramsKeyTmp[1] !== ' ' && _x000D_
                    paramsKeyTmp[1] !== null){          _x000D_
                    _x000D_
                    paramsResult.push(params[x]);_x000D_
                }_x000D_
            }_x000D_
            _x000D_
            return paramsResult;_x000D_
        }_x000D_
    }_x000D_
})_x000D_
_x000D_
.controller("SearchController", function($scope, $http,$routeParams,$log,searchCustom){_x000D_
    $ctrl = this;_x000D_
    _x000D_
    var valueParams = searchCustom.valuesParams($routeParams.value);_x000D_
    valueParams = valueParams.join('&');_x000D_
_x000D_
    $http({_x000D_
        method : "GET",_x000D_
        url: webservice+"q?"+valueParams_x000D_
    }).then( function successCallback(response){_x000D_
        data = response.data;_x000D_
        $scope.cantEncontrados = data.length; _x000D_
        $scope.dataSearch = data;_x000D_
        _x000D_
    } , function errorCallback(response){_x000D_
        console.log(response.statusText);_x000D_
    })_x000D_
      _x000D_
})
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body ng-app="myApp">_x000D_
<div ng-controller="SearchController">_x000D_
<form action="#" >_x000D_
                          _x000D_
                            _x000D_
                            <input ng-model="param1" _x000D_
                                   placeholder="param1" />_x000D_
                            _x000D_
                            <input  ng-model="param2" _x000D_
                                    placeholder="param2"/>_x000D_
                        _x000D_
<!-- Implement in the html code _x000D_
(param1={{param1}}&param2={{param2}}) -> this is a one variable, the factory searchCustom split and restructure in the array params_x000D_
-->          _x000D_
                        <a href="#seach/(param1={{param1}}&param2={{param2}})">_x000D_
                            <buttom ng-click="searchData()" >Busqueda</buttom>_x000D_
                        </a>_x000D_
                    </form> _x000D_
</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Detecting user leaving page with react-router

Using history.listen

For example like below:

In your component,

componentWillMount() {
    this.props.history.listen(() => {
      // Detecting, user has changed URL
      console.info(this.props.history.location.pathname);
    });
}

How to convert/parse from String to char in java?

An Essay way :

public class CharToInt{  
public static void main(String[] poo){  
String ss="toyota";
for(int i=0;i<ss.length();i++)
  {
     char c = ss.charAt(i); 
    // int a=c;  
     System.out.println(c); } } 
} 

For Output see this link: Click here

Thanks :-)

string in namespace std does not name a type

You need to add:

#include <string>

In your header file.

How to check whether an object has certain method/property?

Wouldn't it be better to not use any dynamic types for this, and let your class implement an interface. Then, you can check at runtime wether an object implements that interface, and thus, has the expected method (or property).

public interface IMyInterface
{
   void Somemethod();
}


IMyInterface x = anyObject as IMyInterface;
if( x != null )
{
   x.Somemethod();
}

I think this is the only correct way.

The thing you're referring to is duck-typing, which is useful in scenarios where you already know that the object has the method, but the compiler cannot check for that. This is useful in COM interop scenarios for instance. (check this article)

If you want to combine duck-typing with reflection for instance, then I think you're missing the goal of duck-typing.

How to change the docker image installation directory?

Copy-and-paste version of the winner answer :)

Create this file with only this content:

$ sudo vi /etc/docker/daemon.json

  {
      "graph": "/my-docker-images"
  }

Tested on Ubuntu 16.04.2 LTS in docker 1.12.6

How are "mvn clean package" and "mvn clean install" different?

package will generate Jar/war as per POM file. install will install generated jar file to the local repository for other dependencies if any.

install phase comes after package phase

Python date string to date object

If you are lazy and don't want to fight with string literals, you can just go with the parser module.

from dateutil import parser
dt = parser.parse("Jun 1 2005  1:33PM")
print(dt.year, dt.month, dt.day,dt.hour, dt.minute, dt.second)
>2005 6 1 13 33 0

Just a side note, as we are trying to match any string representation, it is 10x slower than strptime

Allow scroll but hide scrollbar

I know this is an oldie but here is a quick way to hide the scroll bar with pure CSS.

Just add

::-webkit-scrollbar {display:none;}

To your id or class of the div you're using the scroll bar with.

Here is a helpful link Custom Scroll Bar in Webkit

When should I use nil and NULL in Objective-C?

They both are just typecast zero's. Functionally, there's no difference between them. ie.,

#define NULL ((void*)0)
#define nil ((id)0)

There is a difference, but only to yourself and other humans that read the code, the compiler doesn't care.

One more thing nil is an object value while NULL is a generic pointer value.

github markdown colspan

Adding break resolves your issue. You can store more than a record in a cell as markdown doesn't support much features.

Dictionary of dictionaries in Python?

dictionary's setdefault is a good way to update an existing dict entry if it's there, or create a new one if it's not all in one go:

Looping style:

# This is our sample data
data = [("Milter", "Miller", 4), ("Milter", "Miler", 4), ("Milter", "Malter", 2)]

# dictionary we want for the result
dictionary = {}

# loop that makes it work
for realName, falseName, position in data:
    dictionary.setdefault(realName, {})[falseName] = position

dictionary now equals:

{'Milter': {'Malter': 2, 'Miler': 4, 'Miller': 4}}

Convert a date format in PHP

Note: Because this post's answer sometimes gets upvoted, I came back here to kindly ask people not to upvote it anymore. My answer is ancient, not technically correct, and there are several better approaches right here. I'm only keeping it here for historical purposes.

Although the documentation poorly describes the strtotime function, @rjmunro correctly addressed the issue in his comment: it's in ISO format date "YYYY-MM-DD".

Also, even though my Date_Converter function might still work, I'd like to warn that there may be imprecise statements below, so please do disregard them.

The most voted answer is actually incorrect!

The PHP strtotime manual here states that "The function expects to be given a string containing an English date format". What it actually means is that it expects an American US date format, such as "m-d-Y" or "m/d/Y".

That means that a date provided as "Y-m-d" may get misinterpreted by strtotime. You should provide the date in the expected format.

I wrote a little function to return dates in several formats. Use and modify at will. If anyone does turn that into a class, I'd be glad if that would be shared.

function Date_Converter($date, $locale = "br") {

    # Exception
    if (is_null($date))
        $date = date("m/d/Y H:i:s");

    # Let's go ahead and get a string date in case we've
    # been given a Unix Time Stamp
    if ($locale == "unix")
        $date = date("m/d/Y H:i:s", $date);

    # Separate Date from Time
    $date = explode(" ", $date);

    if ($locale == "br") {
        # Separate d/m/Y from Date
        $date[0] = explode("/", $date[0]);
        # Rearrange Date into m/d/Y
        $date[0] = $date[0][1] . "/" . $date[0][0] . "/" . $date[0][2];
    }

    # Return date in all formats
        # US
        $Return["datetime"]["us"] = implode(" ", $date);
        $Return["date"]["us"]     = $date[0];

        # Universal
        $Return["time"]           = $date[1];
        $Return["unix_datetime"]  = strtotime($Return["datetime"]["us"]);
        $Return["unix_date"]      = strtotime($Return["date"]["us"]);
        $Return["getdate"]        = getdate($Return["unix_datetime"]);

        # BR
        $Return["datetime"]["br"] = date("d/m/Y H:i:s", $Return["unix_datetime"]);
        $Return["date"]["br"]     = date("d/m/Y", $Return["unix_date"]);

    # Return
    return $Return;

} # End Function

Read Content from Files which are inside Zip file

As of Java 7, the NIO Api provides a better and more generic way of accessing the contents of Zip or Jar files. Actually, it is now a unified API which allows you to treat Zip files exactly like normal files.

In order to extract all of the files contained inside of a zip file in this API, you'd do this:

In Java 8:

private void extractAll(URI fromZip, Path toDirectory) throws IOException{
    FileSystems.newFileSystem(fromZip, Collections.emptyMap())
            .getRootDirectories()
            .forEach(root -> {
                // in a full implementation, you'd have to
                // handle directories 
                Files.walk(root).forEach(path -> Files.copy(path, toDirectory));
            });
}

In java 7:

private void extractAll(URI fromZip, Path toDirectory) throws IOException{
    FileSystem zipFs = FileSystems.newFileSystem(fromZip, Collections.emptyMap());

    for(Path root : zipFs.getRootDirectories()) {
        Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) 
                    throws IOException {
                // You can do anything you want with the path here
                Files.copy(file, toDirectory);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) 
                    throws IOException {
                // In a full implementation, you'd need to create each 
                // sub-directory of the destination directory before 
                // copying files into it
                return super.preVisitDirectory(dir, attrs);
            }
        });
    }
}

How do you force a makefile to rebuild a target

As per Miller's Recursive Make Considered Harmful you should avoid calling $(MAKE)! In the case you show, it's harmless, because this isn't really a makefile, just a wrapper script, that might just as well have been written in Shell. But you say you continue like that at deeper recursion levels, so you've probably encountered the problems shown in that eye-opening essay.

Of course with GNU make it's cumbersome to avoid. And even though they are aware of this problem, it's their documented way of doing things.

OTOH, makepp was created as a solution for this problem. You can write your makefiles on a per directory level, yet they all get drawn together into a full view of your project.

But legacy makefiles are written recursively. So there's a workaround where $(MAKE) does nothing but channel the subrequests back to the main makepp process. Only if you do redundant or, worse, contradictory things between your submakes, you must request --traditional-recursive-make (which of course breaks this advantage of makepp). I don't know your other makefiles, but if they're cleanly written, with makepp necessary rebuilds should happen automatically, without the need for any hacks suggested here by others.

Invalid http_host header

settings.py

ALLOWED_HOSTS = ['*']

Generate random int value from 3 to 6

Lamak's answer as a function:

-- Create RANDBETWEEN function
-- Usage: SELECT dbo.RANDBETWEEN(0,9,RAND(CHECKSUM(NEWID())))
CREATE FUNCTION dbo.RANDBETWEEN(@minval TINYINT, @maxval TINYINT, @random NUMERIC(18,10))
RETURNS TINYINT
AS
BEGIN
  RETURN (SELECT CAST(((@maxval + 1) - @minval) * @random + @minval AS TINYINT))
END
GO

How to create .pfx file from certificate and private key?

https://msdn.microsoft.com/en-us/library/ff699202.aspx

(( relevant quotes from the article are below ))

Next, you have to create the .pfx file that you will use to sign your deployments. Open a Command Prompt window, and type the following command:

PVK2PFX –pvk yourprivatekeyfile.pvk –spc yourcertfile.cer –pfx yourpfxfile.pfx –po yourpfxpassword

where:

  • pvk - yourprivatekeyfile.pvk is the private key file that you created in step 4.
  • spc - yourcertfile.cer is the certificate file you created in step 4.
  • pfx - yourpfxfile.pfx is the name of the .pfx file that will be creating.
  • po - yourpfxpassword is the password that you want to assign to the .pfx file. You will be prompted for this password when you add the .pfx file to a project in Visual Studio for the first time.

(Optionally (and not for the OP, but for future readers), you can create the .cer and .pvk file from scratch) (you would do this BEFORE the above). Note the mm/dd/yyyy are placeholders for start and end dates. see msdn article for full documentation.

makecert -sv yourprivatekeyfile.pvk -n "CN=My Certificate Name" yourcertfile.cer -b mm/dd/yyyy -e mm/dd/yyyy -r

Find the directory part (minus the filename) of a full path in access 97

If you are confident in your input parameters, you can use this single line of code which uses the native Split and Join functions and Excel native Application.pathSeparator.

Split(Join(Split(strPath, "."), Application.pathSeparator), Application.pathSeparator)

If you want a more extensive function, the code below is tested in Windows and should also work on Mac (though not tested). Be sure to also copy the supporting function GetPathSeparator, or modify the code to use Application.pathSeparator. Note, this is a first draft; I should really refactor it to be more concise.

Private Sub ParsePath2Test()
    'ParsePath2(DrivePathFileExt, -2) returns a multi-line string for debugging.
    Dim p As String, n As Integer

    Debug.Print String(2, vbCrLf)

    If True Then
        Debug.Print String(2, vbCrLf)
        Debug.Print ParsePath2("", -2)
        Debug.Print ParsePath2("C:", -2)
        Debug.Print ParsePath2("C:\", -2)
        Debug.Print ParsePath2("C:\Windows", -2)
        Debug.Print ParsePath2("C:\Windows\notepad.exe", -2)
        Debug.Print ParsePath2("C:\Windows\SysWOW64", -2)
        Debug.Print ParsePath2("C:\Windows\SysWOW64\", -2)
        Debug.Print ParsePath2("C:\Windows\SysWOW64\AcLayers.dll", -2)
        Debug.Print ParsePath2("C:\Windows\SysWOW64\.fakedir", -2)
        Debug.Print ParsePath2("C:\Windows\SysWOW64\fakefile.ext", -2)
    End If

    If True Then
        Debug.Print String(1, vbCrLf)
        Debug.Print ParsePath2("\Windows", -2)
        Debug.Print ParsePath2("\Windows\notepad.exe", -2)
        Debug.Print ParsePath2("\Windows\SysWOW64", -2)
        Debug.Print ParsePath2("\Windows\SysWOW64\", -2)
        Debug.Print ParsePath2("\Windows\SysWOW64\AcLayers.dll", -2)
        Debug.Print ParsePath2("\Windows\SysWOW64\.fakedir", -2)
        Debug.Print ParsePath2("\Windows\SysWOW64\fakefile.ext", -2)
    End If

    If True Then
        Debug.Print String(1, vbCrLf)
        Debug.Print ParsePath2("Windows\notepad.exe", -2)
        Debug.Print ParsePath2("Windows\SysWOW64", -2)
        Debug.Print ParsePath2("Windows\SysWOW64\", -2)
        Debug.Print ParsePath2("Windows\SysWOW64\AcLayers.dll", -2)
        Debug.Print ParsePath2("Windows\SysWOW64\.fakedir", -2)
        Debug.Print ParsePath2("Windows\SysWOW64\fakefile.ext", -2)
        Debug.Print ParsePath2(".fakedir", -2)
        Debug.Print ParsePath2("fakefile.txt", -2)
        Debug.Print ParsePath2("fakefile.onenote", -2)
        Debug.Print ParsePath2("C:\Personal\Workspace\Code\PythonVenvs\xlwings_test\.idea", -2)
        Debug.Print ParsePath2("Windows", -2)   ' Expected to raise error 52
    End If

    If True Then
        Debug.Print String(2, vbCrLf)
        Debug.Print "ParsePath2 ""\Windows\SysWOW64\fakefile.ext"" with different ReturnType values"
        Debug.Print , "{empty}", "D", ParsePath2("Windows\SysWOW64\fakefile.ext")(1)
        Debug.Print , "0", "D", ParsePath2("Windows\SysWOW64\fakefile.ext", 0)(1)
        Debug.Print , "1", "ext", ParsePath2("Windows\SysWOW64\fakefile.ext", 1)
        Debug.Print , "10", "file", ParsePath2("Windows\SysWOW64\fakefile.ext", 10)
        Debug.Print , "11", "file.ext", ParsePath2("Windows\SysWOW64\fakefile.ext", 11)
        Debug.Print , "100", "path", ParsePath2("Windows\SysWOW64\fakefile.ext", 100)
        Debug.Print , "110", "path\file", ParsePath2("Windows\SysWOW64\fakefile.ext", 110)
        Debug.Print , "111", "path\file.ext", ParsePath2("Windows\SysWOW64\fakefile.ext", 111)
        Debug.Print , "1000", "D", ParsePath2("Windows\SysWOW64\fakefile.ext", 1000)
        Debug.Print , "1100", "D:\path", ParsePath2("Windows\SysWOW64\fakefile.ext", 1100)
        Debug.Print , "1110", "D:\p\file", ParsePath2("Windows\SysWOW64\fakefile.ext", 1110)
        Debug.Print , "1111", "D:\p\f.ext", ParsePath2("Windows\SysWOW64\fakefile.ext", 1111)
        On Error GoTo EH:
        ' This is expected to presetn an error:
        p = "Windows\SysWOW64\fakefile.ext"
        n = 1010
        Debug.Print "1010", "D:\p\file.ext", ParsePath2("Windows\SysWOW64\fakefile.ext", 1010)
        On Error GoTo 0
    End If
Exit Sub
EH:
    Debug.Print , CStr(n), "Error: "; Err.Number, Err.Description
    Resume Next
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Public Function ParsePath2(ByVal DrivePathFileExt As String _
                         , Optional ReturnType As Integer = 0)
' Writen by Chris Advena.  You may modify and use this code provided you leave
' this credit in the code.
' Parses the input DrivePathFileExt string into individual components (drive
' letter, folders, filename and extension) and returns the portions you wish
' based on ReturnType.
' Returns either an array of strings (ReturnType = 0) or an individual string
' (all other defined ReturnType values).
'
' Parameters:
'   DrivePathFileExt: The full drive letter, path, filename and extension
'   ReturnType: -2 or a string up of to 4 ones with leading or lagging zeros
'              (e.g., 0001)
'      -2: special code for debugging use in ParsePath2Test().
'          Results in printing verbose information to the Immediate window.
'       0: default: Array(driveStr, pathStr, fileStr, extStr)
'       1: extension
'      10: filename stripped of extension
'      11: filename.extension, excluding drive and folders
'     100: folders, excluding drive letter filename and extension
'     111: folders\filename.extension, excluding drive letter
'    1000: drive leter only
'    1100: drive:\folders,  excluding filename and extension
'    1110: drive:\folders\filename, excluding extension
'    1010, 0101, 1001: invalid ReturnTypes.  Will result raise error 380, Value
'          is not valid.

    Dim driveStr As String, pathStr As String
    Dim fileStr As String, extStr As String
    Dim drivePathStr As String
    Dim pathFileExtStr As String, fileExtStr As String
    Dim s As String, cnt As Integer
    Dim i As Integer, slashStr As String
    Dim dotLoc As Integer, slashLoc As Integer, colonLoc As Integer
    Dim extLen As Integer, fileLen As Integer, pathLen As Integer
    Dim errStr As String

    DrivePathFileExt = Trim(DrivePathFileExt)

    If DrivePathFileExt = "" Then
        fileStr = ""
        extStr = ""
        fileExtStr = ""
        pathStr = ""
        pathFileExtStr = ""
        drivePathStr = ""
        GoTo ReturnResults
    End If

    ' Determine if Dos(/) or UNIX(\) slash is used
    slashStr = GetPathSeparator(DrivePathFileExt)

' Find location of colon, rightmost slash and dot.
    ' COLON: colonLoc and driveStr
    colonLoc = 0
    driveStr = ""
    If Mid(DrivePathFileExt, 2, 1) = ":" Then
        colonLoc = 2
        driveStr = Left(DrivePathFileExt, 1)
    End If
    #If Mac Then
        pathFileExtStr = DrivePathFileExt
    #Else ' Windows
        pathFileExtStr = ""
        If Len(DrivePathFileExt) > colonLoc _
        Then pathFileExtStr = Mid(DrivePathFileExt, colonLoc + 1)
    #End If

    ' SLASH: slashLoc, fileExtStr and fileStr
    ' Find the rightmost path separator (Win backslash or Mac Fwdslash).
    slashLoc = InStrRev(DrivePathFileExt, slashStr, -1, vbBinaryCompare)

    ' DOT: dotLoc and extStr
    ' Find rightmost dot.  If that dot is not part of a relative reference,
    ' then set dotLoc.  dotLoc is meant to apply to the dot before an extension,
    ' NOT relative path reference dots.  REl ref dots appear as "." or ".." at
    ' the very leftmost of the path string.
    dotLoc = InStrRev(DrivePathFileExt, ".", -1, vbTextCompare)
    If Left(DrivePathFileExt, 1) = "." And dotLoc <= 2 Then dotLoc = 0
    If slashLoc + 1 = dotLoc Then
        dotLoc = 0
        If Len(extStr) = 0 And Right(pathFileExtStr, 1) <> slashStr _
        Then pathFileExtStr = pathFileExtStr & slashStr
    End If
    #If Not Mac Then
        ' In windows, filenames cannot end with a dot (".").
        If dotLoc = Len(DrivePathFileExt) Then
            s = "Error in FileManagementMod.ParsePath2 function.  " _
                & "DrivePathFileExt " & DrivePathFileExt _
                & " cannot end iwth a dot ('.')."
            Err.Raise 52, "FileManagementMod.ParsePath2", s
        End If
    #End If

    ' extStr
    extStr = ""
    If dotLoc > 0 And (dotLoc < Len(DrivePathFileExt)) _
    Then extStr = Mid(DrivePathFileExt, dotLoc + 1)

    ' fileExtStr
    fileExtStr = ""
    If slashLoc > 0 _
    And slashLoc < Len(DrivePathFileExt) _
    And dotLoc > slashLoc Then
        fileExtStr = Mid(DrivePathFileExt, slashLoc + 1)
    End If


' Validate the input: DrivePathFileExt
    s = ""
    #If Mac Then
        If InStr(1, DrivePathFileExt, ":") > 0 Then
            s = "DrivePathFileExt ('" & DrivePathFileExt _
                & "')has invalid format.  " _
                & "UNIX/Mac filenames cannot contain a colon ('.')."
        End If
    #End If
    If Not colonLoc = 0 And slashLoc = 0 And dotLoc = 0 _
    And Left(DrivePathFileExt, 1) <> slashStr _
    And Left(DrivePathFileExt, 1) <> "." Then
        s = "DrivePathFileExt ('" & DrivePathFileExt _
            & "') has invalid format.  " _
            & "Good example: 'C:\folder\file.txt'"
    ElseIf colonLoc <> 0 And colonLoc <> 2 Then
        ' We are on Windows and there is a colon; it can only be
        ' in position 2.
        s = "DrivePathFileExt ('" & DrivePathFileExt _
            & "') has invalid format.  " _
            & "In the  Windows operating system, " _
            & "a colon (':') can only be the second character '" _
            & "of a valid file path. "
    ElseIf Left(DrivePathFileExt, 1) = ":" _
    Or InStr(3, DrivePathFileExt, ":", vbTextCompare) > 0 Then
        'If path contains a drive letter, it must contain at least one slash.
        s = "DrivePathFileExt ('" & DrivePathFileExt _
            & "') has invalid format.  " _
            & "Colon can only appear in the second character position." _
            & slashStr & "')."
    ElseIf colonLoc > 0 And slashLoc = 0 _
    And Len(DrivePathFileExt) > 2 Then
        'If path contains a drive letter, it must contain at least one slash.
        s = "DrivePathFileExt ('" & DrivePathFileExt _
            & "') has invalid format.  " _
            & "The last dot ('.') cannot be before the last file separator '" _
            & slashStr & "')."
    ElseIf colonLoc = 2 _
    And InStr(1, DrivePathFileExt, slashStr, vbTextCompare) = 0 _
    And Len(DrivePathFileExt) > 2 Then
        ' There is a colon, but no file separator (slash).  This is invalid.
        s = "DrivePathFileExt ('" & DrivePathFileExt _
            & "') has invalid format.  " _
            & "If a drive letter is included, then there must be at " _
            & "least one file separator character ('" & slashStr & "')."
    ElseIf Len(driveStr) > 0 And Len(DrivePathFileExt) > 2 And slashLoc = 0 Then
        ' If path contains a drive letter and is more than 2 character long
        ' (e.g., 'C:'), it must contain at least one slash.
        s = "DrivePathFileExt cannot contain a drive letter but no path separator."
    End If
    If Len(s) > 0 Then
    End If



' Determine if DrivePathFileExt = DrivePath
' or  = Path (with no fileStr or extStr components).
    If Right(DrivePathFileExt, 1) = slashStr _
    Or slashLoc = 0 _
    Or dotLoc = 0 _
    Or (dotLoc > 0 And dotLoc <= slashLoc + 1) Then
        ' If rightmost character is the slashStr, then no fileExt exists, just drivePath
        ' If no dot found, then no extension.  Assume a folder is after the last slashstr,
        ' not a filename.
        ' If a dot is found (extension exists),
        ' If a rightmost dot appears one-char to the right of the rightmost slash
        '    or anywhere before (left) of that, it is not a file/ext separator. Exmaple:
        '    'C:\folder1\.folder2' Then
        ' If no slashes, then no fileExt exists.  It must just be a driveletter.
        ' DrivePathFileExt contains no file or ext name.
        fileStr = ""
        extStr = ""
        fileExtStr = ""
        pathStr = pathFileExtStr
        drivePathStr = DrivePathFileExt
        GoTo ReturnResults
    Else
        ' fileStr
        fileStr = ""
        If slashLoc > 0 Then
            If Len(extStr) = 0 Then
                fileStr = fileExtStr
            Else
                ' length of filename excluding dot and extension.
                i = Len(fileExtStr) - Len(extStr) - 1
                fileStr = Left(fileExtStr, i)
            End If
        Else
                s = "Error in FileManagementMod.ParsePath2 function. " _
                    & "*** Unhandled scenario: find fileStr when slashLoc = 0. *** "
                Err.Raise 52, "FileManagementMod.ParsePath2", s
        End If

        ' pathStr
        pathStr = ""
        ' length of pathFileExtStr excluding fileExt.
        i = Len(pathFileExtStr) - Len(fileExtStr)
        pathStr = Left(pathFileExtStr, i)

        ' drivePathStr
        drivePathStr = ""
        ' length of DrivePathFileExt excluding dot and extension.
        i = Len(DrivePathFileExt) - Len(fileExtStr)
        drivePathStr = Left(DrivePathFileExt, i)
    End If

ReturnResults:
    ' ReturnType uses a 4-digit binary code: dpfe = drive path file extension,
    ' where 1 = return in array and 0 = do not return in array
    ' -2, and 0 are special cases that do not follow the code.

    ' Note: pathstr is determined with the tailing slashstr
    If Len(drivePathStr) > 0 And Right(drivePathStr, 1) <> slashStr _
    Then drivePathStr = drivePathStr & slashStr
    If Len(pathStr) > 0 And Right(pathStr, 1) <> slashStr _
    Then pathStr = pathStr & slashStr
    #If Not Mac Then
        ' Including this code add a slash to the beginnning where missing.
        ' the downside is that it would create an absolute path where a
        ' sub-path of the current folder is intended.
        'If colonLoc = 0 Then
        '    If Len(drivePathStr) > 0 And Not IsIn(Left(drivePathStr, 1), slashStr, ".") _
             Then drivePathStr = slashStr & drivePathStr
        '    If Len(pathStr) > 0 And Not IsIn(Left(pathStr, 1), slashStr, ".") _
             Then pathStr = slashStr & pathStr
        '    If Len(pathFileExtStr) > 0 And Not IsIn(Left(pathFileExtStr, 1), slashStr, ".") _
             Then pathFileExtStr = slashStr & pathFileExtStr
        'End If
    #End If
    Select Case ReturnType
        Case -2  ' used for ParsePath2Test() only.
            ParsePath2 = "DrivePathFileExt          " _
                        & CStr(Nz(DrivePathFileExt, "{empty string}")) _
                        & vbCrLf & "        " _
                        & "--------------    -----------------------------------------" _
                        & vbCrLf & "        " & "D:\Path\          " & drivePathStr _
                        & vbCrLf & "        " & "\path[\file.ext]  " & pathFileExtStr _
                        & vbCrLf & "        " & "\path\            " & pathStr _
                        & vbCrLf & "        " & "file.ext          " & fileExtStr _
                        & vbCrLf & "        " & "file              " & fileStr _
                        & vbCrLf & "        " & "ext               " & extStr _
                        & vbCrLf & "        " & "D                 " & driveStr _
                        & vbCrLf & vbCrLf
            ' My custom debug printer prints to Immediate winodw and log file.
            ' Dbg.Prnt 2, ParsePath2
            Debug.Print ParsePath2
        Case 1      '0001: ext
            ParsePath2 = extStr
        Case 10     '0010: file
            ParsePath2 = fileStr
        Case 11     '0011: file.ext
            ParsePath2 = fileExtStr
        Case 100    '0100: path
            ParsePath2 = pathStr
        Case 110    '0110: (path, file)
            ParsePath2 = pathStr & fileStr
        Case 111    '0111:
            ParsePath2 = pathFileExtStr
        Case 1000
            ParsePath2 = driveStr
        Case 1100
            ParsePath2 = drivePathStr
        Case 1110
            ParsePath2 = drivePathStr & fileStr
        Case 1111
            ParsePath2 = DrivePathFileExt
        Case 1010, 101, 1001
            s = "Error in FileManagementMod.ParsePath2 function.  " _
                & "Value of Paramter (ReturnType = " _
                & CStr(ReturnType) & ") is not valid."
            Err.Raise 380, "FileManagementMod.ParsePath2", s
        Case Else   '   default: 0
            ParsePath2 = Array(driveStr, pathStr, fileStr, extStr)
    End Select

End Function

Supporting function GetPathSeparatorTest extends the native Application.pathSeparator (or bypasses when needed) to work on Mac and Win. It can also takes an optional path string and will try to determine the path separator used in the string (favoring the OS native path separator).

Private Sub GetPathSeparatorTest()
    Dim s As String
    Debug.Print "GetPathSeparator(s):"
    Debug.Print "s not provided: ", GetPathSeparator
    s = "C:\folder1\folder2\file.ext"
    Debug.Print "s = "; s, GetPathSeparator(DrivePathFileExt:=s)
    s = "C:/folder1/folder2/file.ext"
    Debug.Print "s = "; s, GetPathSeparator(DrivePathFileExt:=s)
End Sub
Function GetPathSeparator(Optional DrivePathFileExt As String = "") As String
' by Chris Advena
' Finds the path separator from a string, DrivePathFileExt.
' If DrivePathFileExt is not provided, return the operating system path separator
' (Windows = backslash, Mac = forwardslash).
' Mac/Win compatible.

    ' Initialize
    Dim retStr As String: retStr = ""
    Dim OSSlash As String: OSSlash = ""
    Dim OSOppositeSlash As String: OSOppositeSlash = ""
        Dim PathFileExtSlash As String

    GetPathSeparator = ""
    retStr = ""

    ' Determine if OS expects fwd or back slash ("/" or "\").
    On Error GoTo EH
    OSSlash = Application.pathSeparator

    If DrivePathFileExt = "" Then
    ' Input parameter DrivePathFileExt is empty, so use OS file separator.
        retStr = OSSlash
    Else
    ' Input parameter DrivePathFileExt provided.  See if it contains / or \.
        ' Set OSOppositeSlash to the opposite slash the OS expects.
        OSOppositeSlash = "\"
        If OSSlash = "\" Then OSOppositeSlash = "/"

        ' If DrivePathFileExt does NOT contain OSSlash
        ' and DOES contain OSOppositeSlash, return OSOppositeSlash.
        ' Otherwise, assume OSSlash is correct.
        retStr = OSSlash
        If InStr(1, DrivePathFileExt, OSSlash, vbTextCompare) = 0 _
        And InStr(1, DrivePathFileExt, OSOppositeSlash, vbTextCompare) > 0 Then
            retStr = OSOppositeSlash
        End If
    End If

    GetPathSeparator = retStr
Exit Function
EH:
    ' Application.PathSeparator property does not exist in Access,
    ' so get it the slightly less easy way.
    #If Mac Then ' Application.PathSeparator doesn't seem to exist in Access...
        OSSlash = "/"
    #Else
        OSSlash = "\"
    #End If
    Resume Next
End Function

Supporting function (actually commented out, so you can skip this if you don't plan to use it).

Sub IsInTest()
' IsIn2 is case insensitive
    Dim StrToFind As String, arr As Variant
    arr = Array("Me", "You", "Dog", "Boo")

    StrToFind = "doG"
    Debug.Print "Is '" & CStr(StrToFind) & "' in list (expect True): " _
                , IsIn(StrToFind, "Me", "You", "Dog", "Boo")

    StrToFind = "Porcupine"
    Debug.Print "Is '" & CStr(StrToFind) & "' in list (expect False): " _
                , IsIn(StrToFind, "Me", "You", "Dog", "Boo")
End Sub
Function IsIn(ByVal StrToFind, ParamArray StringArgs() As Variant) As Boolean
' StrToFind: the string to find in the list of StringArgs()
' StringArgs: 1-dimensional array containing string values.
' Built for Strings, but actually works with other data types.
    Dim arr As Variant
    arr = StringArgs
    IsIn = Not IsError(Application.Match(StrToFind, arr, False))
End Function

How to filter Pandas dataframe using 'in' and 'not in' like in SQL

How to implement 'in' and 'not in' for a pandas DataFrame?

Pandas offers two methods: Series.isin and DataFrame.isin for Series and DataFrames, respectively.


Filter DataFrame Based on ONE Column (also applies to Series)

The most common scenario is applying an isin condition on a specific column to filter rows in a DataFrame.

df = pd.DataFrame({'countries': ['US', 'UK', 'Germany', np.nan, 'China']})
df
  countries
0        US
1        UK
2   Germany
3     China

c1 = ['UK', 'China']             # list
c2 = {'Germany'}                 # set
c3 = pd.Series(['China', 'US'])  # Series
c4 = np.array(['US', 'UK'])      # array

Series.isin accepts various types as inputs. The following are all valid ways of getting what you want:

df['countries'].isin(c1)

0    False
1     True
2    False
3    False
4     True
Name: countries, dtype: bool

# `in` operation
df[df['countries'].isin(c1)]

  countries
1        UK
4     China

# `not in` operation
df[~df['countries'].isin(c1)]

  countries
0        US
2   Germany
3       NaN

# Filter with `set` (tuples work too)
df[df['countries'].isin(c2)]

  countries
2   Germany

# Filter with another Series
df[df['countries'].isin(c3)]

  countries
0        US
4     China

# Filter with array
df[df['countries'].isin(c4)]

  countries
0        US
1        UK

Filter on MANY Columns

Sometimes, you will want to apply an 'in' membership check with some search terms over multiple columns,

df2 = pd.DataFrame({
    'A': ['x', 'y', 'z', 'q'], 'B': ['w', 'a', np.nan, 'x'], 'C': np.arange(4)})
df2

   A    B  C
0  x    w  0
1  y    a  1
2  z  NaN  2
3  q    x  3

c1 = ['x', 'w', 'p']

To apply the isin condition to both columns "A" and "B", use DataFrame.isin:

df2[['A', 'B']].isin(c1)

      A      B
0   True   True
1  False  False
2  False  False
3  False   True

From this, to retain rows where at least one column is True, we can use any along the first axis:

df2[['A', 'B']].isin(c1).any(axis=1)

0     True
1    False
2    False
3     True
dtype: bool

df2[df2[['A', 'B']].isin(c1).any(axis=1)]

   A  B  C
0  x  w  0
3  q  x  3

Note that if you want to search every column, you'd just omit the column selection step and do

df2.isin(c1).any(axis=1)

Similarly, to retain rows where ALL columns are True, use all in the same manner as before.

df2[df2[['A', 'B']].isin(c1).all(axis=1)]

   A  B  C
0  x  w  0

Notable Mentions: numpy.isin, query, list comprehensions (string data)

In addition to the methods described above, you can also use the numpy equivalent: numpy.isin.

# `in` operation
df[np.isin(df['countries'], c1)]

  countries
1        UK
4     China

# `not in` operation
df[np.isin(df['countries'], c1, invert=True)]

  countries
0        US
2   Germany
3       NaN

Why is it worth considering? NumPy functions are usually a bit faster than their pandas equivalents because of lower overhead. Since this is an elementwise operation that does not depend on index alignment, there are very few situations where this method is not an appropriate replacement for pandas' isin.

Pandas routines are usually iterative when working with strings, because string operations are hard to vectorise. There is a lot of evidence to suggest that list comprehensions will be faster here.. We resort to an in check now.

c1_set = set(c1) # Using `in` with `sets` is a constant time operation... 
                 # This doesn't matter for pandas because the implementation differs.
# `in` operation
df[[x in c1_set for x in df['countries']]]

  countries
1        UK
4     China

# `not in` operation
df[[x not in c1_set for x in df['countries']]]

  countries
0        US
2   Germany
3       NaN

It is a lot more unwieldy to specify, however, so don't use it unless you know what you're doing.

Lastly, there's also DataFrame.query which has been covered in this answer. numexpr FTW!

Value of type 'T' cannot be converted to

Change this line:

if (typeof(T) == typeof(string))

For this line:

if (t.GetType() == typeof(string))

How do I clone a subdirectory only of a Git repository?

If you never plan to interact with the repository from which you cloned, you can do a full git clone and rewrite your repository using git filter-branch --subdirectory-filter. This way, at least the history will be preserved.

Array inside a JavaScript Object?

Kill the braces.

var defaults = {
 backgroundcolor: '#000',
 color: '#fff',
 weekdays: ['sun','mon','tue','wed','thu','fri','sat']
};

Standard deviation of a list

In Python 2.7.1, you may calculate standard deviation using numpy.std() for:

  • Population std: Just use numpy.std() with no additional arguments besides to your data list.
  • Sample std: You need to pass ddof (i.e. Delta Degrees of Freedom) set to 1, as in the following example:

numpy.std(< your-list >, ddof=1)

The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

It calculates sample std rather than population std.

EF Migrations: Rollback last applied migration?

I realised there aren't any good solutions utilizing the CLI dotnet command so here's one:

dotnet ef migrations list
dotnet ef database update NameOfYourMigration

In the place of NameOfYourMigration enter the name of the migration you want to revert to.

Apache won't run in xampp

Find out which other service uses port 80.

I have heard skype uses port 80. Check it there isn't another server or database running in the background on port 80.

Two good alternatives to xampp are wamp and easyphp. Out of that, wamp is the most user friendly and it also has a built in tool for checking if port 80 is in use and which service is currently using it.

Or disable iis. It has been known to use port 80 by default.

Getting vertical gridlines to appear in line plot in matplotlib

Short answer (read below for more info):

ax.grid(axis='both', which='both')

enter image description here

What you do is correct and it should work.

However, since the X axis in your example is a DateTime axis the Major tick-marks (most probably) are appearing only at the both ends of the X axis. The other visible tick-marks are Minor tick-marks.

The ax.grid() method, by default, draws grid lines on Major tick-marks. Therefore, nothing appears in your plot.

Use the code below to highlight the tick-marks. Majors will be Blue while Minors are Red.

ax.tick_params(which='both', width=3)
ax.tick_params(which='major', length=20, color='b')
ax.tick_params(which='minor', length=10, color='r')

Now to force the grid lines to be appear also on the Minor tick-marks, pass the which='minor' to the method:

ax.grid(b=True, which='minor', axis='x', color='#000000', linestyle='--')

or simply use which='both' to draw both Major and Minor grid lines. And this a more elegant grid line:

ax.grid(b=True, which='minor', axis='both', color='#888888', linestyle='--')
ax.grid(b=True, which='major', axis='both', color='#000000', linestyle='-')

Numpy: Checking if a value is NaT

This approach avoids the warnings while preserving the array-oriented evaluation.

import numpy as np
def isnat(x):
    """ 
    datetime64 analog to isnan.
    doesn't yet exist in numpy - other ways give warnings
    and are likely to change.  
    """
    return x.astype('i8') == np.datetime64('NaT').astype('i8')

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

What is happening here is that database route does not accept any url methods.

I would try putting the url methods in the app route just like you have in the entry_page function:

@app.route('/entry', methods=['GET', 'POST'])
def entry_page():
    if request.method == 'POST':
        date = request.form['date']
        title = request.form['blog_title']
        post = request.form['blog_main']
        post_entry = models.BlogPost(date = date, title = title, post = post)
        db.session.add(post_entry)
        db.session.commit()
        return redirect(url_for('database'))
    else:
        return render_template('entry.html')

@app.route('/database', methods=['GET', 'POST'])        
def database():
    query = []
    for i in session.query(models.BlogPost):
        query.append((i.title, i.post, i.date))
    return render_template('database.html', query = query)

Include another JSP file

You can use Include Directives

<%
 if(request.getParameter("p")!=null)
 { 
   String p = request.getParameter("p");
%>    

<%@include file="<%="includes/" + p +".jsp"%>"%>

<% 
 }
%>

or JSP Include Action

<%
 if(request.getParameter("p")!=null)
 { 
   String p = request.getParameter("p");
%>    

<jsp:include page="<%="includes/"+p+".jsp"%>"/>

<% 
 }
%>

the different is include directive includes a file during the translation phase. while JSP Include Action includes a file at the time the page is requested

I recommend Spring MVC Framework as your controller to manipulate things. use url pattern instead of parameter.

example:

www.yourwebsite.com/products

instead of

www.yourwebsite.com/?p=products

Watch this video Spring MVC Framework

How to define a default value for "input type=text" without using attribute 'value'?

The value is there. The source is not updated as the values on the form change. The source is from when the page initially loaded.

How can I disable the UITableView selection?

I am using this, which works for me.

cell?.selectionStyle = UITableViewCellSelectionStyle.None

Decrementing for loops

for i in range(10,0,-1):
    print i,

The range() function will include the first value and exclude the second.

How to install pip with Python 3?

If you use several different versions of python try using virtualenv http://www.virtualenv.org/en/latest/virtualenv.html#installation

With the advantage of pip for each local environment.

Then install a local environment in the current directory by:

virtualenv -p /usr/local/bin/python3.3 ENV --verbose

Note that you specify the path to a python binary you have installed on your system.

Then there are now an local pythonenvironment in that folder. ./ENV

Now there should be ./ENV/pip-3.3

use ./ENV/pip-3.3 freeze to list the local installed libraries.

use ./ENV/pip-3.3 install packagename to install at the local environment.

use ./ENV/python3.3 pythonfile.py to run your python script.

How to get the employees with their managers

Perhaps your subquery (SELECT ename FROM EMP WHERE empno = mgr) thinks, give me the employee records that are their own managers! (i.e., where the empno of a row is the same as the mgr of the same row.)

have you considered perhaps rewriting this to use an inner (self) join? (I'm asking, becuase i'm not even sure if the following will work or not.)

SELECT t1.ename, t1.empno, t2.ename as MANAGER, t1.mgr
from emp as t1
inner join emp t2 ON t1.mgr = t2.empno
order by t1.empno;

Creating SolidColorBrush from hex color value

I've been using:

new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffaacc"));

Java ArrayList Index

In order to store Strings in an dynamic array (add-method) you can't define it as an array of integers ( int[3] ). You should declare it like this:

ArrayList<String> alist = new ArrayList<String>();
alist.add("apple"); 
alist.add("banana"); 
alist.add("orange"); 

System.out.println( alist.get(1) );

How to send control+c from a bash script?

You can get the PID of a particular process like MySQL by using following commands: ps -e | pgrep mysql

This command will give you the PID of MySQL rocess. e.g, 13954 Now, type following command on terminal. kill -9 13954 This will kill the process of MySQL.

Decimal to Hexadecimal Converter in Java

Here's mine

public static String dec2Hex(int num)
{
    String hex = "";

    while (num != 0)
    {
        if (num % 16 < 10)
            hex = Integer.toString(num % 16) + hex;
        else
            hex = (char)((num % 16)+55) + hex;
        num = num / 16;
    }

    return hex;
}

Activity transition in Android

Yes. You can tell the OS what kind of transition you want to have for your activity.

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    getWindow().setWindowAnimations(ANIMATION);

    ...

}

Where ANIMATION is an integer referring to a built in animation in the OS.

.htaccess file to allow access to images folder to view pictures?

Create a .htaccess file in the images folder and add this

<IfModule mod_rewrite.c>
RewriteEngine On
# directory browsing
Options All +Indexes
</IfModule>

you can put this Options All -Indexes in the project file .htaccess ,file to deny direct access to other folders.

This does what you want

SQL Server 2008 - Case / If statements in SELECT Clause

The most obvious solutions are already listed. Depending on where the query is sat (i.e. in application code) you can't always use IF statements and the inline CASE statements can get painful where lots of columns become conditional. Assuming Col1 + Col3 + Col7 are the same type, and likewise Col2, Col4 + Col8 you can do this:

SELECT Col1, Col2 FROM tbl WHERE @Var LIKE 'xyz'
UNION ALL
SELECT Col3, Col4 FROM tbl WHERE @Var LIKE 'zyx'
UNION ALL
SELECT Col7, Col8 FROM tbl WHERE @Var NOT LIKE 'xyz' AND @Var NOT LIKE 'zyx'

As this is a single command there are several performance benefits with regard to plan caching. Also the Query Optimiser will quickly eliminate those statements where @Var doesn't match the appropriate value without touching the storage engine.

Remove empty elements from an array in Javascript

The best way to remove empty elements, is to use Array.prototype.filter(), as already mentioned in other answers.

Unfortunately, Array.prototype.filter() is not supported by IE<9. If you still need to support IE8 or an even older version of IE, you could use the following polyfill to add support for Array.prototype.filter() in these browsers :

if (!Array.prototype.filter) {
  Array.prototype.filter = function(fun/*, thisArg*/) {
    'use strict';
    if (this === void 0 || this === null) {
      throw new TypeError();
    }
    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== 'function') {
      throw new TypeError();
    }
    var res = [];
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++) {
      if (i in t) {
        var val = t[i];
        if (fun.call(thisArg, val, i, t)) {
          res.push(val);
        }
      }
    }
    return res;
  };
}

How to convert a string to ASCII

You can do it by using LINQ-expression.

  public static List<int> StringToAscii(string value)
  {
        if (string.IsNullOrEmpty(value))
            throw new ArgumentException("Value cannot be null or empty.", nameof(value));

        return value.Select(System.Convert.ToInt32).ToList();
  } 

How do I get the XML root node with C#?

Root node is the DocumentElement property of XmlDocument

XmlElement root = xmlDoc.DocumentElement

If you only have the node, you can get the root node by

XmlElement root = xmlNode.OwnerDocument.DocumentElement

Searching word in vim?

like this:

/\<word\>

\< means beginning of a word, and \> means the end of a word,

Adding @Roe's comment:
VIM provides a shortcut for this. If you already have word on screen and you want to find other instances of it, you can put the cursor on the word and press '*' to search forward in the file or '#' to search backwards.

Force table column widths to always be fixed regardless of contents

You can also use percentages, and/or specify in the column headers:

<table width="300">  
  <tr>
    <th width="20%">Column 1</th>
    <th width="20%">Column 2</th>
    <th width="20%">Column 3</th>
    <th width="20%">Column 4</th>
    <th width="20%">Column 5</th>
  </tr>
  <tr>
    <!--- row data -->
  </tr>
</table>

The bonus with percentages is lower code maintenance: you can change your table width without having to re-specify the column widths.

Caveat: It is my understanding that table width specified in pixels isn't supported in HTML 5; you need to use CSS instead.

mySQL convert varchar to date

As gratitude to the timely help I got from here - a minor update to above.

$query = "UPDATE `db`.`table` SET `fieldname`=  str_to_date(  fieldname, '%d/%m/%Y')";

WAMP shows error 'MSVCR100.dll' is missing when install

I solved this problem by installing this one : http://www.microsoft.com/en-sg/download/details.aspx?id=30679

Be sure to remove wampserver and reinstall it again

Note: I'm using Windows 7 32 bits

How can I preview a merge in git?

git log currentbranch..otherbranch will give you the list of commits that will go into the current branch if you do a merge. The usual arguments to log which give details on the commits will give you more information.

git diff currentbranch otherbranch will give you the diff between the two commits that will become one. This will be a diff that gives you everything that will get merged.

Would these help?

Rails params explained?

On the Rails side, params is a method that returns an ActionController::Parameters object. See https://stackoverflow.com/a/44070358/5462485

How to convert dd/mm/yyyy string into JavaScript Date object?

I found the default JS date formatting didn't work.

So I used toLocaleString with options

const event = new Date();
const options = { dateStyle: 'short' };
const date = event.toLocaleString('en', options);

to get: DD/MM/YYYY format

See docs for more formatting options: https://www.w3schools.com/jsref/jsref_tolocalestring.asp

Check if a number is odd or even in python

One of the simplest ways is to use de modulus operator %. If n % 2 == 0, then your number is even.

Hope it helps,

Variable name as a string in Javascript

In ES6, you could write something like:

let myVar = 'something';
let nameObject = {myVar};
let getVarNameFromObject = (nameObject) => {
  for(let varName in nameObject) {
    return varName;
  }
}
let varName = getVarNameFromObject(nameObject);

Not really the best looking thing, but it gets the job done.

This leverages ES6's object destructuring.

More info here: https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/

How to hide a navigation bar from first ViewController in Swift?

In Swift 3, you can use isNavigationBarHidden Property also to show or hide navigation bar

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    // Hide the navigation bar for current view controller
    self.navigationController?.isNavigationBarHidden = true;
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    // Show the navigation bar on other view controllers
   self.navigationController?.isNavigationBarHidden = false;
}

What is SELF JOIN and when would you use it?

SQL self-join simply is a normal join which is used to join a table to itself.

Example:

Select *
FROM Table t1, Table t2
WHERE t1.Id = t2.ID

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

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

This is a syntax issue, the jQuery library included with WordPress loads in "no conflict" mode. This is to prevent compatibility problems with other javascript libraries that WordPress can load. In "no-confict" mode, the $ shortcut is not available and the longer jQuery is used, i.e.

jQuery(document).ready(function ($) {

By including the $ in parenthesis after the function call you can then use this shortcut within the code block.

For full details see WordPress Codex

gpg: no valid OpenPGP data found

This problem might occur if you are behind corporate proxy and corporation uses its own certificate. Just add "--no-check-certificate" in the command. e.g. wget --no-check-certificate -qO - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | sudo apt-key add -

It works. If you want to see what is going on, you can use verbose command instead of quiet before adding "--no-check-certificate" option. e.g. wget -vO - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | sudo apt-key add - This will tell you to use "--no-check-certificate" if you are behind proxy.

Eclipse internal error while initializing Java tooling

In my case, I had two of three projects with this problem in my current workspace. I opened workspace catalog and made a backup of corrupted projects, deleted them afterwards. Then opened eclipse once again. Obviously there was missing data to work with. Closed eclipse once again and added back earlier saved projects without metadata catalogs.

TL;DR. Just remove metadata catalogs from projects in your workspace.

WebAPI Multiple Put/Post parameters

Nice question and comments - learnt much from the replies here :)

As an additional example, note that you can also mix body and routes e.g.

[RoutePrefix("api/test")]
public class MyProtectedController 
{
    [Authorize]
    [Route("id/{id}")]
    public IEnumerable<object> Post(String id, [FromBody] JObject data)
    {
        /*
          id                                      = "123"
          data.GetValue("username").ToString()    = "user1"
          data.GetValue("password").ToString()    = "pass1"
         */
    }
}

Calling like this:

POST /api/test/id/123 HTTP/1.1
Host: localhost
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer x.y.z
Cache-Control: no-cache

username=user1&password=pass1


enter code here

PHP Warning Permission denied (13) on session_start()

do a phpinfo(), and look for session.save_path. the directory there needs to have the correct permissions for the user and/or group that your webserver runs as

Replace HTML Table with Divs

This ought to do the trick.

<style>
div.block{
  overflow:hidden;
}
div.block label{
  width:160px;
  display:block;
  float:left;
  text-align:left;
}
div.block .input{
  margin-left:4px;
  float:left;
}
</style>

<div class="block">
  <label>First field</label>
  <input class="input" type="text" id="txtFirstName"/>
</div>
<div class="block">
  <label>Second field</label>
  <input class="input" type="text" id="txtLastName"/>
</div>

I hope you get the concept.

Get the name of an object's type

Here is an implementation based on the accepted answer:

_x000D_
_x000D_
/**_x000D_
 * Returns the name of an object's type._x000D_
 *_x000D_
 * If the input is undefined, returns "Undefined"._x000D_
 * If the input is null, returns "Null"._x000D_
 * If the input is a boolean, returns "Boolean"._x000D_
 * If the input is a number, returns "Number"._x000D_
 * If the input is a string, returns "String"._x000D_
 * If the input is a named function or a class constructor, returns "Function"._x000D_
 * If the input is an anonymous function, returns "AnonymousFunction"._x000D_
 * If the input is an arrow function, returns "ArrowFunction"._x000D_
 * If the input is a class instance, returns "Object"._x000D_
 *_x000D_
 * @param {Object} object an object_x000D_
 * @return {String} the name of the object's class_x000D_
 * @see <a href="https://stackoverflow.com/a/332429/14731">https://stackoverflow.com/a/332429/14731</a>_x000D_
 * @see getFunctionName_x000D_
 * @see getObjectClass _x000D_
 */_x000D_
function getTypeName(object)_x000D_
{_x000D_
  const objectToString = Object.prototype.toString.call(object).slice(8, -1);_x000D_
  if (objectToString === "Function")_x000D_
  {_x000D_
    const instanceToString = object.toString();_x000D_
    if (instanceToString.indexOf(" => ") != -1)_x000D_
      return "ArrowFunction";_x000D_
    const getFunctionName = /^function ([^(]+)\(/;_x000D_
    const match = instanceToString.match(getFunctionName);_x000D_
    if (match === null)_x000D_
      return "AnonymousFunction";_x000D_
    return "Function";_x000D_
  }_x000D_
  // Built-in types (e.g. String) or class instances_x000D_
  return objectToString;_x000D_
};_x000D_
_x000D_
/**_x000D_
 * Returns the name of a function._x000D_
 *_x000D_
 * If the input is an anonymous function, returns ""._x000D_
 * If the input is an arrow function, returns "=>"._x000D_
 *_x000D_
 * @param {Function} fn a function_x000D_
 * @return {String} the name of the function_x000D_
 * @throws {TypeError} if {@code fn} is not a function_x000D_
 * @see getTypeName_x000D_
 */_x000D_
function getFunctionName(fn)_x000D_
{_x000D_
  try_x000D_
  {_x000D_
    const instanceToString = fn.toString();_x000D_
    if (instanceToString.indexOf(" => ") != -1)_x000D_
      return "=>";_x000D_
    const getFunctionName = /^function ([^(]+)\(/;_x000D_
    const match = instanceToString.match(getFunctionName);_x000D_
    if (match === null)_x000D_
    {_x000D_
      const objectToString = Object.prototype.toString.call(fn).slice(8, -1);_x000D_
      if (objectToString === "Function")_x000D_
        return "";_x000D_
      throw TypeError("object must be a Function.\n" +_x000D_
        "Actual: " + getTypeName(fn));_x000D_
    }_x000D_
    return match[1];_x000D_
  }_x000D_
  catch (e)_x000D_
  {_x000D_
    throw TypeError("object must be a Function.\n" +_x000D_
      "Actual: " + getTypeName(fn));_x000D_
  }_x000D_
};_x000D_
_x000D_
/**_x000D_
 * @param {Object} object an object_x000D_
 * @return {String} the name of the object's class_x000D_
 * @throws {TypeError} if {@code object} is not an Object_x000D_
 * @see getTypeName_x000D_
 */_x000D_
function getObjectClass(object)_x000D_
{_x000D_
  const getFunctionName = /^function ([^(]+)\(/;_x000D_
  const result = object.constructor.toString().match(getFunctionName)[1];_x000D_
  if (result === "Function")_x000D_
  {_x000D_
    throw TypeError("object must be an Object.\n" +_x000D_
      "Actual: " + getTypeName(object));_x000D_
  }_x000D_
  return result;_x000D_
};_x000D_
_x000D_
_x000D_
function UserFunction()_x000D_
{_x000D_
}_x000D_
_x000D_
function UserClass()_x000D_
{_x000D_
}_x000D_
_x000D_
let anonymousFunction = function()_x000D_
{_x000D_
};_x000D_
_x000D_
let arrowFunction = i => i + 1;_x000D_
_x000D_
console.log("getTypeName(undefined): " + getTypeName(undefined));_x000D_
console.log("getTypeName(null): " + getTypeName(null));_x000D_
console.log("getTypeName(true): " + getTypeName(true));_x000D_
console.log("getTypeName(5): " + getTypeName(5));_x000D_
console.log("getTypeName(\"text\"): " + getTypeName("text"));_x000D_
console.log("getTypeName(userFunction): " + getTypeName(UserFunction));_x000D_
console.log("getFunctionName(userFunction): " + getFunctionName(UserFunction));_x000D_
console.log("getTypeName(anonymousFunction): " + getTypeName(anonymousFunction));_x000D_
console.log("getFunctionName(anonymousFunction): " + getFunctionName(anonymousFunction));_x000D_
console.log("getTypeName(arrowFunction): " + getTypeName(arrowFunction));_x000D_
console.log("getFunctionName(arrowFunction): " + getFunctionName(arrowFunction));_x000D_
//console.log("getFunctionName(userClass): " + getFunctionName(new UserClass()));_x000D_
console.log("getTypeName(userClass): " + getTypeName(new UserClass()));_x000D_
console.log("getObjectClass(userClass): " + getObjectClass(new UserClass()));_x000D_
//console.log("getObjectClass(userFunction): " + getObjectClass(UserFunction));_x000D_
//console.log("getObjectClass(userFunction): " + getObjectClass(anonymousFunction));_x000D_
//console.log("getObjectClass(arrowFunction): " + getObjectClass(arrowFunction));_x000D_
console.log("getTypeName(nativeObject): " + getTypeName(navigator.mediaDevices.getUserMedia));_x000D_
console.log("getFunctionName(nativeObject): " + getFunctionName(navigator.mediaDevices.getUserMedia));
_x000D_
_x000D_
_x000D_

We only use the constructor property when we have no other choice.

Checking if a character is a special character in Java

Take a look at class java.lang.Character static member methods (isDigit, isLetter, isLowerCase, ...)

Example:

String str = "Hello World 123 !!";
int specials = 0, digits = 0, letters = 0, spaces = 0;
for (int i = 0; i < str.length(); ++i) {
   char ch = str.charAt(i);
   if (!Character.isDigit(ch) && !Character.isLetter(ch) && !Character.isSpace(ch)) {
      ++specials;
   } else if (Character.isDigit(ch)) {
      ++digits;
   } else if (Character.isSpace(ch)) {
      ++spaces;
   } else {
      ++letters;
   }
}

How to interactively (visually) resolve conflicts in SourceTree / git

From SourceTree, click on Tools->Options. Then on the "General" tab, make sure to check the box to allow SourceTree to modify your Git config files.

Then switch to the "Diff" tab. On the lower half, use the drop down to select the external program you want to use to do the diffs and merging. I've installed KDiff3 and like it well enough. When you're done, click OK.

Now when there is a merge, you can go under Actions->Resolve Conflicts->Launch External Merge Tool.

Android - java.lang.SecurityException: Permission Denial: starting Intent

Select your proper configuration for launching Application.

In my case i found mistake as below image:

enter image description here

I had just changed like:

enter image description here

May it will help to someone, Thanks :)

StringUtils.isBlank() vs String.isEmpty()

StringUtils.isBlank() returns true for blanks(just whitespaces)and for null String as well. Actually it trims the Char sequences and then performs check.

StringUtils.isEmpty() returns true when there is no charsequence in the String parameter or when String parameter is null. Difference is that isEmpty() returns false if String parameter contains just whiltespaces. It considers whitespaces as a state of being non empty.

CFLAGS vs CPPFLAGS

The implicit make rule for compiling a C program is

%.o:%.c
    $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<

where the $() syntax expands the variables. As both CPPFLAGS and CFLAGS are used in the compiler call, which you use to define include paths is a matter of personal taste. For instance if foo.c is a file in the current directory

make foo.o CPPFLAGS="-I/usr/include"
make foo.o CFLAGS="-I/usr/include"

will both call your compiler in exactly the same way, namely

gcc -I/usr/include -c -o foo.o foo.c

The difference between the two comes into play when you have multiple languages which need the same include path, for instance if you have bar.cpp then try

make bar.o CPPFLAGS="-I/usr/include"
make bar.o CFLAGS="-I/usr/include"

then the compilations will be

g++ -I/usr/include -c -o bar.o bar.cpp
g++ -c -o bar.o bar.cpp

as the C++ implicit rule also uses the CPPFLAGS variable.

This difference gives you a good guide for which to use - if you want the flag to be used for all languages put it in CPPFLAGS, if it's for a specific language put it in CFLAGS, CXXFLAGS etc. Examples of the latter type include standard compliance or warning flags - you wouldn't want to pass -std=c99 to your C++ compiler!

You might then end up with something like this in your makefile

CPPFLAGS=-I/usr/include
CFLAGS=-std=c99
CXXFLAGS=-Weffc++

What is difference between INNER join and OUTER join

INNER JOIN: Returns all rows when there is at least one match in BOTH tables

LEFT JOIN: Return all rows from the left table, and the matched rows from the right table

RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table

FULL JOIN: Return all rows when there is a match in ONE of the tables

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

A more "generic" version(?), allowing none English letters as special characters.

^(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)(?=\S*[^\w\s])\S{8,}$

_x000D_
_x000D_
var pwdList = [_x000D_
    '@@V4-\3Z`zTzM{>k',_x000D_
    '12qw!"QW12',_x000D_
    '123qweASD!"#',_x000D_
    '1qA!"#$%&',_x000D_
    'Günther32',_x000D_
    '123456789',_x000D_
    'qweASD123',_x000D_
    'qweqQWEQWEqw',_x000D_
    '12qwAS!'_x000D_
  ],_x000D_
  re = /^(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)(?=\S*[^\w\s])\S{8,}$/;_x000D_
  _x000D_
  pwdList.forEach(function (pw) {_x000D_
    document.write('<span style="color:'+ (re.test(pw) ? 'green':'red') + '">' + pw + '</span><br/>');_x000D_
  });
_x000D_
_x000D_
_x000D_

Make the current Git branch a master branch

The solutions given here (renaming the branch in 'master') don't insist on the consequences for the remote (GitHub) repo:

  • if you hadn't push anything since making that branch, you can rename it and push it without any problem.
  • if you had push master on GitHub, you will need to 'git push -f' the new branch: you can no longer push in a fast forward mode.
    -f
    --force

Usually, the command refuses to update a remote ref that is not an ancestor of the local ref used to overwrite it. This flag disables the check. This can cause the remote repository to lose commits; use it with care.

If others have already pulled your repo, they won't be able to pull that new master history without replacing their own master with that new GitHub master branch (or dealing with lots of merges).
There are alternatives to a git push --force for public repos.
Jefromi's answer (merging the right changes back to the original master) is one of them.

Reliable way for a Bash script to get the full path to itself

Use:

SCRIPT_PATH=$(dirname `which $0`)

which prints to standard output the full path of the executable that would have been executed when the passed argument had been entered at the shell prompt (which is what $0 contains)

dirname strips the non-directory suffix from a file name.

Hence you end up with the full path of the script, no matter if the path was specified or not.

How to find Max Date in List<Object>?

Just use Kotlin!

val list = listOf(user1, user2, user3)
val maxDate = list.maxBy { it.date }?.date

Error parsing XHTML: The content of elements must consist of well-formed character data or markup

I had a git conflict left in my workspace.xml i.e.

<<<<———————HEAD

which caused the unknown tag error. It is a bit annoying that it doesn’t name the file.

adb command for getting ip address assigned by operator

ip route | grep rmnet_data0 | cut -d" " -f1 | cut -d"/" -f1

Change rmnet_data0 to the desired nic, in my case, rmnet_data0 represents the data nic.

To get a list of the available nic's you can use ip route

Calculating Page Table Size

In 32 bit virtual address system we can have 2^32 unique address, since the page size given is 4KB = 2^12, we will need (2^32/2^12 = 2^20) entries in the page table, if each entry is 4Bytes then total size of the page table = 4 * 2^20 Bytes = 4MB

How to open this .DB file?

You can use a tool like the TrIDNet - File Identifier to look for the Magic Number and other telltales, if the file format is in it's database it may tell you what it is for.

However searching the definitions did not turn up anything for the string "FLDB", but it checks more than magic numbers so it is worth a try.

If you are using Linux File is a command that will do a similar task.

The other thing to try is if you have access to the program that generated this file, there may be DLL's or EXE's from the database software that may contain meta information about the dll's creator which could give you a starting point for looking for software that can read the file outside of the program that originally created the .db file.

Is try-catch like error handling possible in ASP Classic?

Regarding Wolfwyrd's anwer: "On Error Resume Next" in fact turns error handling off! Not on. On Error Goto 0 turns error-handling back ON because at the least, we want the machine to catch it if we didn't write it in ourselves. Off = leaving it to you to handle it.

If you use On Error Resume Next, you need to be careful about how much code you include after it: remember, the phrase "If Err.Number <> 0 Then" only refers to the most previous error triggered.

If your block of code after "On Error Resume Next" has several places where you might reasonably expect it to fail, then you must place "If Err.number <> 0" after each and every one of those possible failure lines, to check execution.

Otherwise, after "on error resume next" means just what it says - your code can fail on as many lines as it likes and execution will continue merrily along. That's why it's a pain in the ass.

Solutions for INSERT OR UPDATE on SQL Server

In SQL Server 2008 you can use the MERGE statement

Display Last Saved Date on worksheet

May be this time stamp fit you better Code

Function LastInputTimeStamp() As Date
  LastInputTimeStamp = Now()
End Function

and each time you input data in defined cell (in my example below it is cell C36) you'll get a new constant time stamp. As an example in Excel file may use this

=IF(C36>0,LastInputTimeStamp(),"")

What is the difference between .py and .pyc files?

.pyc contain the compiled bytecode of Python source files. The Python interpreter loads .pyc files before .py files, so if they're present, it can save some time by not having to re-compile the Python source code. You can get rid of them if you want, but they don't cause problems, they're not big, and they may save some time when running programs.

Returning a regex match in VBA (excel)

You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).

For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.

Function ExtractSDI(ByVal text As String) As String

Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)

If allMatches.count <> 0 Then
    result = allMatches.Item(0).submatches.Item(0)
End If

ExtractSDI = result

End Function

If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:

Ex) =RegexExtract(A1, "(sdi \d+)", ", ")

Here is:

Function RegexExtract(ByVal text As String, _
                      ByVal extract_what As String, _
                      Optional seperator As String = "") As String

Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)

For i = 0 To allMatches.count - 1
    For j = 0 To allMatches.Item(i).submatches.count - 1
        result = result & seperator & allMatches.Item(i).submatches.Item(j)
    Next
Next

If Len(result) <> 0 Then
    result = Right(result, Len(result) - Len(seperator))
End If

RegexExtract = result

End Function

*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.

android download pdf from url then open it with a pdf reader

Download source code from here (Open Pdf from url in Android Programmatically)

MainActivity.java

package com.deepshikha.openpdf;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {
    WebView webview;
    ProgressBar progressbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webview = (WebView)findViewById(R.id.webview);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        webview.getSettings().setJavaScriptEnabled(true);
        String filename ="http://www3.nd.edu/~cpoellab/teaching/cse40816/android_tutorial.pdf";
        webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);

        webview.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {
                // do your stuff here
                progressbar.setVisibility(View.GONE);
            }
        });

    }
}

Thanks!

How do I get the Back Button to work with an AngularJS ui-router state machine?

Can be solved using a simple directive "go-back-history", this one is also closing window in case of no previous history.

Directive usage

<a data-go-back-history>Previous State</a>

Angular directive declaration

.directive('goBackHistory', ['$window', function ($window) {
    return {
        restrict: 'A',
        link: function (scope, elm, attrs) {
            elm.on('click', function ($event) {
                $event.stopPropagation();
                if ($window.history.length) {
                    $window.history.back();
                } else {
                    $window.close();  
                }
            });
        }
    };
}])

Note: Working using ui-router or not.

How to create RecyclerView with multiple view type?

I recommend this library from Hannes Dorfmann. It encapsulates all the logic related to particular view type in a separate object called "AdapterDelegate". https://github.com/sockeqwe/AdapterDelegates

public class CatAdapterDelegate extends AdapterDelegate<List<Animal>> {

  private LayoutInflater inflater;

  public CatAdapterDelegate(Activity activity) {
    inflater = activity.getLayoutInflater();
  }

  @Override public boolean isForViewType(@NonNull List<Animal> items, int position) {
    return items.get(position) instanceof Cat;
  }

  @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent) {
    return new CatViewHolder(inflater.inflate(R.layout.item_cat, parent, false));
  }

  @Override public void onBindViewHolder(@NonNull List<Animal> items, int position,
      @NonNull RecyclerView.ViewHolder holder, @Nullable List<Object> payloads) {

    CatViewHolder vh = (CatViewHolder) holder;
    Cat cat = (Cat) items.get(position);

    vh.name.setText(cat.getName());
  }

  static class CatViewHolder extends RecyclerView.ViewHolder {

    public TextView name;

    public CatViewHolder(View itemView) {
      super(itemView);
      name = (TextView) itemView.findViewById(R.id.name);
    }
  }
}

public class AnimalAdapter extends ListDelegationAdapter<List<Animal>> {

  public AnimalAdapter(Activity activity, List<Animal> items) {

    // DelegatesManager is a protected Field in ListDelegationAdapter
    delegatesManager.addDelegate(new CatAdapterDelegate(activity))
                    .addDelegate(new DogAdapterDelegate(activity))
                    .addDelegate(new GeckoAdapterDelegate(activity))
                    .addDelegate(23, new SnakeAdapterDelegate(activity));

    // Set the items from super class.
    setItems(items);
  }
}

how to set start value as "0" in chartjs?

Please add this option:

//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,

(Reference: Chart.js)

N.B: The original solution I posted was for Highcharts, if you are not using Highcharts then please remove the tag to avoid confusion

IIS Config Error - This configuration section cannot be used at this path

I think the better way is that you must remove you configuration from your web.config. Publish your code on the server and do what you want to remove directly from the IIS server interface.

Thanks to this method if you sucessfully do what you want, you just have to get the web.config and compare the differences. After that you just have to post the solution in this post :-P.

css absolute position won't work with margin-left:auto margin-right: auto

I've used this trick to center an absolutely positioned element. Though, you have to know the element's width.

.divtagABS {
    width: 100px;
    position: absolute;
    left: 50%;
    margin-left: -50px;
  }

Basically, you use left: 50%, then back it out half of it's width with a negative margin.

String representation of an Enum

You can declare enum and the dictionary in which the key will be the value of the enumeration. In the future, you can refer to the dictionary to get the value. Thus, it will be possible to pass parameters to functions as the type of enum, but to get the real value from the dictionary:

using System;
using System.Collections.Generic;

namespace console_test
{
    class Program
    {
        #region SaveFormat
        internal enum SaveFormat
        {
            DOCX,
            PDF
        }

        internal static Dictionary<SaveFormat,string> DictSaveFormat = new Dictionary<SaveFormat, string>
        {
            { SaveFormat.DOCX,"This is value for DOCX enum item" },
            { SaveFormat.PDF,"This is value for PDF enum item" }
        };

        internal static void enum_value_test(SaveFormat save_format)
        {
            Console.WriteLine(DictSaveFormat[save_format]);
        }
        #endregion

        internal static void Main(string[] args)
        {
            enum_value_test(SaveFormat.DOCX);//Output: This is value for DOCX enum item
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}

Adding a new entry to the PATH variable in ZSH

OPTION 1: Add this line to ~/.zshrc:

export "PATH=$HOME/pear/bin:$PATH"

After that you need to run source ~/.zshrc in order your changes to take affect OR close this window and open a new one

OPTION 2: execute it inside the terminal console to add this path only to the current terminal window session. When you close the window/session, it will be lost.

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

I ran into the same problem.

My app uses Navigation components with a fragment containing my recyclerView. My list displayed fine the first time the fragment was loaded ... but upon navigating away and coming back this error occurred.

When navigating away the fragment lifecycle went only through onDestroyView and upon returning it started at onCreateView. However, my adapter was initialized in the fragment's onCreate and did not reinitialize when returning.

The fix was to initialize the adapter in onCreateView.

Hope this may help someone.

Best way to list files in Java, sorted by Date Modified?

If the files you are sorting can be modified or updated at the same time the sort is being performed:


Java 8+

private static List<Path> listFilesOldestFirst(final String directoryPath) throws IOException {
    try (final Stream<Path> fileStream = Files.list(Paths.get(directoryPath))) {
        return fileStream
            .map(Path::toFile)
            .collect(Collectors.toMap(Function.identity(), File::lastModified))
            .entrySet()
            .stream()
            .sorted(Map.Entry.comparingByValue())
//            .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))  // replace the previous line with this line if you would prefer files listed newest first
            .map(Map.Entry::getKey)
            .map(File::toPath)  // remove this line if you would rather work with a List<File> instead of List<Path>
            .collect(Collectors.toList());
    }
}

Java 7

private static List<File> listFilesOldestFirst(final String directoryPath) throws IOException {
    final List<File> files = Arrays.asList(new File(directoryPath).listFiles());
    final Map<File, Long> constantLastModifiedTimes = new HashMap<File,Long>();
    for (final File f : files) {
        constantLastModifiedTimes.put(f, f.lastModified());
    }
    Collections.sort(files, new Comparator<File>() {
        @Override
        public int compare(final File f1, final File f2) {
            return constantLastModifiedTimes.get(f1).compareTo(constantLastModifiedTimes.get(f2));
        }
    });
    return files;
}


Both of these solutions create a temporary map data structure to save off a constant last modified time for each file in the directory. The reason we need to do this is that if your files are being updated or modified while your sort is being performed then your comparator will be violating the transitivity requirement of the comparator interface's general contract because the last modified times may be changing during the comparison.

If, on the other hand, you know the files will not be updated or modified during your sort, you can get away with pretty much any other answer submitted to this question, of which I'm partial to:

Java 8+ (No concurrent modifications during sort)

private static List<Path> listFilesOldestFirst(final String directoryPath) throws IOException {
    try (final Stream<Path> fileStream = Files.list(Paths.get(directoryPath))) {
        return fileStream
            .map(Path::toFile)
            .sorted(Comparator.comparing(File::lastModified))
            .map(File::toPath)  // remove this line if you would rather work with a List<File> instead of List<Path>
            .collect(Collectors.toList());
    }
}

Note: I know you can avoid the translation to and from File objects in the above example by using Files::getLastModifiedTime api in the sorted stream operation, however, then you need to deal with checked IO exceptions inside your lambda which is always a pain. I'd say if performance is critical enough that the translation is unacceptable then I'd either deal with the checked IOException in the lambda by propagating it as an UncheckedIOException or I'd forego the Files api altogether and deal only with File objects:

final List<File> sorted = Arrays.asList(new File(directoryPathString).listFiles());
sorted.sort(Comparator.comparing(File::lastModified));

How to update Python?

UPDATE: 2018-07-06

This post is now nearly 5 years old! Python-2.7 will stop receiving official updates from python.org in 2020. Also, Python-3.7 has been released. Check out Python-Future on how to make your Python-2 code compatible with Python-3. For updating conda, the documentation now recommends using conda update --all in each of your conda environments to update all packages and the Python executable for that version. Also, since they changed their name to Anaconda, I don't know if the Windows registry keys are still the same.

UPDATE: 2017-03-24

There have been no updates to Python(x,y) since June of 2015, so I think it's safe to assume it has been abandoned.

UPDATE: 2016-11-11

As @cxw comments below, these answers are for the same bit-versions, and by bit-version I mean 64-bit vs. 32-bit. For example, these answers would apply to updating from 64-bit Python-2.7.10 to 64-bit Python-2.7.11, ie: the same bit-version. While it is possible to install two different bit versions of Python together, it would require some hacking, so I'll save that exercise for the reader. If you don't want to hack, I suggest that if switching bit-versions, remove the other bit-version first.

UPDATES: 2016-05-16
  • Anaconda and MiniConda can be used with an existing Python installation by disabling the options to alter the Windows PATH and Registry. After extraction, create a symlink to conda in your bin or install conda from PyPI. Then create another symlink called conda-activate to activate in the Anaconda/Miniconda root bin folder. Now Anaconda/Miniconda is just like Ruby RVM. Just use conda-activate root to enable Anaconda/Miniconda.
  • Portable Python is no longer being developed or maintained.

TL;DR

  • Using Anaconda or miniconda, then just execute conda update --all to keep each conda environment updated,
  • same major version of official Python (e.g. 2.7.5), just install over old (e.g. 2.7.4),
  • different major version of official Python (e.g. 3.3), install side-by-side with old, set paths/associations to point to dominant (e.g. 2.7), shortcut to other (e.g. in BASH $ ln /c/Python33/python.exe python3).

The answer depends:

  1. If OP has 2.7.x and wants to install newer version of 2.7.x, then

    • if using MSI installer from the official Python website, just install over old version, installer will issue warning that it will remove and replace the older version; looking in "installed programs" in "control panel" before and after confirms that the old version has been replaced by the new version; newer versions of 2.7.x are backwards compatible so this is completely safe and therefore IMHO multiple versions of 2.7.x should never necessary.
    • if building from source, then you should probably build in a fresh, clean directory, and then point your path to the new build once it passes all tests and you are confident that it has been built successfully, but you may wish to keep the old build around because building from source may occasionally have issues. See my guide for building Python x64 on Windows 7 with SDK 7.0.
    • if installing from a distribution such as Python(x,y), see their website. Python(x,y) has been abandoned. I believe that updates can be handled from within Python(x,y) with their package manager, but updates are also included on their website. I could not find a specific reference so perhaps someone else can speak to this. Similar to ActiveState and probably Enthought, Python (x,y) clearly states it is incompatible with other installations of Python:

      It is recommended to uninstall any other Python distribution before installing Python(x,y)

    • Enthought Canopy uses an MSI and will install either into Program Files\Enthought or home\AppData\Local\Enthought\Canopy\App for all users or per user respectively. Newer installations are updated by using the built in update tool. See their documentation.
    • ActiveState also uses an MSI so newer installations can be installed on top of older ones. See their installation notes.

      Other Python 2.7 Installations On Windows, ActivePython 2.7 cannot coexist with other Python 2.7 installations (for example, a Python 2.7 build from python.org). Uninstall any other Python 2.7 installations before installing ActivePython 2.7.

    • Sage recommends that you install it into a virtual machine, and provides a Oracle VirtualBox image file that can be used for this purpose. Upgrades are handled internally by issuing the sage -upgrade command.
    • Anaconda can be updated by using the conda command:

      conda update --all
      

      Anaconda/Miniconda lets users create environments to manage multiple Python versions including Python-2.6, 2.7, 3.3, 3.4 and 3.5. The root Anaconda/Miniconda installations are currently based on either Python-2.7 or Python-3.5.

      Anaconda will likely disrupt any other Python installations. Installation uses MSI installer. [UPDATE: 2016-05-16] Anaconda and Miniconda now use .exe installers and provide options to disable Windows PATH and Registry alterations.

      Therefore Anaconda/Miniconda can be installed without disrupting existing Python installations depending on how it was installed and the options that were selected during installation. If the .exe installer is used and the options to alter Windows PATH and Registry are not disabled, then any previous Python installations will be disabled, but simply uninstalling the Anaconda/Miniconda installation should restore the original Python installation, except maybe the Windows Registry Python\PythonCore keys.

      Anaconda/Miniconda makes the following registry edits regardless of the installation options: HKCU\Software\Python\ContinuumAnalytics\ with the following keys: Help, InstallPath, Modules and PythonPath - official Python registers these keys too, but under Python\PythonCore. Also uninstallation info is registered for Anaconda\Miniconda. Unless you select the "Register with Windows" option during installation, it doesn't create PythonCore, so integrations like Python Tools for Visual Studio do not automatically see Anaconda/Miniconda. If the option to register Anaconda/Miniconda is enabled, then I think your existing Python Windows Registry keys will be altered and uninstallation will probably not restore them.

    • WinPython updates, I think, can be handled through the WinPython Control Panel.
    • PortablePython is no longer being developed. It had no update method. Possibly updates could be unzipped into a fresh directory and then App\lib\site-packages and App\Scripts could be copied to the new installation, but if this didn't work then reinstalling all packages might have been necessary. Use pip list to see what packages were installed and their versions. Some were installed by PortablePython. Use easy_install pip to install pip if it wasn't installed.
  2. If OP has 2.7.x and wants to install a different version, e.g. <=2.6.x or >=3.x.x, then installing different versions side-by-side is fine. You must choose which version of Python (if any) to associate with *.py files and which you want on your path, although you should be able to set up shells with different paths if you use BASH. AFAIK 2.7.x is backwards compatible with 2.6.x, so IMHO side-by-side installs is not necessary, however Python-3.x.x is not backwards compatible, so my recommendation would be to put Python-2.7 on your path and have Python-3 be an optional version by creating a shortcut to its executable called python3 (this is a common setup on Linux). The official Python default install path on Windows is

    • C:\Python33 for 3.3.x (latest 2013-07-29)
    • C:\Python32 for 3.2.x
    • &c.
    • C:\Python27 for 2.7.x (latest 2013-07-29)
    • C:\Python26 for 2.6.x
    • &c.
  3. If OP is not updating Python, but merely updating packages, they may wish to look into virtualenv to keep the different versions of packages specific to their development projects separate. Pip is also a great tool to update packages. If packages use binary installers I usually uninstall the old package before installing the new one.

I hope this clears up any confusion.

calling a function from class in python - different way

You need to have an instance of a class to use its methods. Or if you don't need to access any of classes' variables (not static parameters) then you can define the method as static and it can be used even if the class isn't instantiated. Just add @staticmethod decorator to your methods.

class MathsOperations:
    @staticmethod
    def testAddition (x, y):
        return x + y
    @staticmethod
    def testMultiplication (a, b):
        return a * b

docs: http://docs.python.org/library/functions.html#staticmethod

Convert string to ASCII value python

def stringToNumbers(ord(message)):
    return stringToNumbers
    stringToNumbers.append = (ord[0])
    stringToNumbers = ("morocco")

Why does python use 'else' after for and while loops?

I read it like "When the iterable is exhausted completely, and the execution is about to proceed to the next statement after finishing the for, the else clause will be executed." Thus, when the iteration is broken by break, this will not be executed.

GROUP BY having MAX date

There's no need to group in that subquery... a where clause would suffice:

SELECT * FROM tblpm n
WHERE date_updated=(SELECT MAX(date_updated)
    FROM tblpm WHERE control_number=n.control_number)

Also, do you have an index on the 'date_updated' column? That would certainly help.

Renaming branches remotely in Git

I don't know why but @Sylvain Defresne's answer does not work for me.

git branch new-branch-name origin/old-branch-name
git push origin --set-upstream new-branch-name
git push origin :old-branch-name

I have to unset the upstream and then I can set the stream again. The following is how I did it.

git checkout -b new-branch-name
git branch --unset-upstream
git push origin new-branch-name -u
git branch origin :old-branch-name

Create new XML file and write data to it?

DOMDocument is a great choice. It's a module specifically designed for creating and manipulating XML documents. You can create a document from scratch, or open existing documents (or strings) and navigate and modify their structures.

$xml = new DOMDocument();
$xml_album = $xml->createElement("Album");
$xml_track = $xml->createElement("Track");
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );

$xml->save("/tmp/test.xml");

To re-open and write:

$xml = new DOMDocument();
$xml->load('/tmp/test.xml');
$nodes = $xml->getElementsByTagName('Album') ;
if ($nodes->length > 0) {
   //insert some stuff using appendChild()
}

//re-save
$xml->save("/tmp/test.xml");

Get file name from URL

I've come up with this:

String url = "http://www.example.com/some/path/to/a/file.xml";
String file = url.substring(url.lastIndexOf('/')+1, url.lastIndexOf('.'));

Session timeout in ASP.NET

Use the following code block in your web.config file. Here default session time out is 80 mins.

<system.web>
 <sessionState mode="InProc" cookieless="false" timeout="80" />
</system.web>

Use the following link for Session Timeout with popup alert message.

Session Timeout Example

FYI:The above examples is done with devexpress popup control so you need to customize/replace devexpress popup control with normal popup control. If your using devexpress no need to customize

Angular - Can't make ng-repeat orderBy work

the built-in orderBy filter will no longer work when iterating an object. It’s ignored due to the way that object fields are stored. You need create a custom filter

yourApp.filter('orderObjectBy', function() {
  return function(items, field, reverse) {
    var filtered = [];
    angular.forEach(items, function(item) {
      filtered.push(item);
    });
    filtered.sort(function (a, b) {
      return (a[field] > b[field] ? 1 : -1);
    });
    if(reverse) filtered.reverse();
    return filtered;
  };
});

<ul>
<li ng-repeat="item in items | orderObjectBy:'color':true">{{ item.color }}</li>
</ul>

SQL select join: is it possible to prefix all columns as 'prefix.*'?

There is no SQL standard for this.

However With code generation (either on demand as the tables are created or altered or at runtime), you can do this quite easily:

CREATE TABLE [dbo].[stackoverflow_329931_a](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [col2] [nchar](10) NULL,
    [col3] [nchar](10) NULL,
    [col4] [nchar](10) NULL,
 CONSTRAINT [PK_stackoverflow_329931_a] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[stackoverflow_329931_b](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [col2] [nchar](10) NULL,
    [col3] [nchar](10) NULL,
    [col4] [nchar](10) NULL,
 CONSTRAINT [PK_stackoverflow_329931_b] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

DECLARE @table1_name AS varchar(255)
DECLARE @table1_prefix AS varchar(255)
DECLARE @table2_name AS varchar(255)
DECLARE @table2_prefix AS varchar(255)
DECLARE @join_condition AS varchar(255)
SET @table1_name = 'stackoverflow_329931_a'
SET @table1_prefix = 'a_'
SET @table2_name = 'stackoverflow_329931_b'
SET @table2_prefix = 'b_'
SET @join_condition = 'a.[id] = b.[id]'

DECLARE @CRLF AS varchar(2)
SET @CRLF = CHAR(13) + CHAR(10)

DECLARE @a_columnlist AS varchar(MAX)
DECLARE @b_columnlist AS varchar(MAX)
DECLARE @sql AS varchar(MAX)

SELECT @a_columnlist = COALESCE(@a_columnlist + @CRLF + ',', '') + 'a.[' + COLUMN_NAME + '] AS [' + @table1_prefix + COLUMN_NAME + ']'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @table1_name
ORDER BY ORDINAL_POSITION

SELECT @b_columnlist = COALESCE(@b_columnlist + @CRLF + ',', '') + 'b.[' + COLUMN_NAME + '] AS [' + @table2_prefix + COLUMN_NAME + ']'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @table2_name
ORDER BY ORDINAL_POSITION

SET @sql = 'SELECT ' + @a_columnlist + '
,' + @b_columnlist + '
FROM [' + @table1_name + '] AS a
INNER JOIN [' + @table2_name + '] AS b
ON (' + @join_condition + ')'

PRINT @sql
-- EXEC (@sql)

How to plot an array in python?

if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:

If x and/or y is 2-dimensional, then the corresponding columns will be plotted.

In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:

np.squeez doc: Remove single-dimensional entries from the shape of an array.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()

But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:

Jupyter matplotlib plot

T-SQL XOR Operator

<> is generally a good replacement for XOR wherever it can apply to booleans.

Get a list of all the files in a directory (recursive)

The following works for me in Gradle / Groovy for build.gradle for an Android project, without having to import groovy.io.FileType (NOTE: Does not recurse subdirectories, but when I found this solution I no longer cared about recursion, so you may not either):

FileCollection proGuardFileCollection = files { file('./proguard').listFiles() }
proGuardFileCollection.each {
    println "Proguard file located and processed: " + it
}

How do I write to the console from a Laravel Controller?

The question relates to serving via artisan and so Jrop's answer is ideal in that case. I.e, error_log logging to the apache log.

However, if your serving via a standard web server then simply use the Laravel specific logging functions:

\Log::info('This is some useful information.');

\Log::warning('Something could be going wrong.');

\Log::error('Something is really going wrong.');

With current versions of laravel like this for info:

info('This is some useful information.');

This logs to Laravel's log file located at /laravel/storage/logs/laravel-<date>.log (laravel 5.0). Monitor the log - linux/osx: tail -f /laravel/storage/logs/laravel-<date>.log

How would I stop a while loop after n amount of time?

I have read this but I just want to ask something, wouldn't something like I have written work at all? I have done the testing for 5,10 and 20 seconds. Its time isn't exactly accurate but they are really close to the actual values.

import time

begin_time=0
while begin_time<5:

    begin_time+=1
    time.sleep(1.0)
print("The Work is Done")

How remove border around image in css?

Try this:

img{border:0;}

You can also limitate the scope and only remove border on some images by doing so:

.myClass img{border:0;}

More information about the border css property can by found here.

Edit: Changed border from 0px to 0. As explained in comments, px is redundant for a unit of 0.

Java - checking if parseInt throws exception

You can use a scanner instead of try-catch:

Scanner scanner = new Scanner(line).useDelimiter("\n");
if(scanner.hasNextInt()){
    System.out.println("yes, it's an int");
}

What's the source of Error: getaddrinfo EAI_AGAIN?

If you get this error with Firebase Cloud Functions, this is due to the limitations of the free tier (outbound networking only allowed to Google services).

Upgrade to the Flame or Blaze plans for it to work.

enter image description here

How to remove stop words using nltk or python

   import sys
print ("enter the string from which you want to remove list of stop words")
userstring = input().split(" ")
list =["a","an","the","in"]
another_list = []
for x in userstring:
    if x not in list:           # comparing from the list and removing it
        another_list.append(x)  # it is also possible to use .remove
for x in another_list:
     print(x,end=' ')

   # 2) if you want to use .remove more preferred code
    import sys
    print ("enter the string from which you want to remove list of stop words")
    userstring = input().split(" ")
    list =["a","an","the","in"]
    another_list = []
    for x in userstring:
        if x in list:           
            userstring.remove(x)  
    for x in userstring:           
        print(x,end = ' ') 
    #the code will be like this

Getting started with Haskell

If you only have experience with imperative/OO languages, I suggest using a more conventional functional language as a stepping stone. Haskell is really different and you have to understand a lot of different concepts to get anywhere. I suggest tackling a ML-style language (like e.g. F#) first.