Programs & Examples On #Oracleportal

Oracle Portal is a browser-based, self-service content publishing and site development solution built on Oracle Application Server or WebLogic. It uses portlets (small windows of specialized content area) from different sources as building blocks for Portal pages.

Use a JSON array with objects with javascript

@Swapnil Godambe It works for me if JSON.stringfy is removed. That is:

$(jQuery.parseJSON(dataArray)).each(function() {  
    var ID = this.id;
    var TITLE = this.Title;
});

Splitting a Java String by the pipe symbol using split("|")

You could also use the apache library and do this:

StringUtils.split(test, "|");

How can I get client information such as OS and browser

Your best bet is User-Agent header. You can get it like this in JSP or Servlet,

String userAgent = request.getHeader("User-Agent");

The header looks like this,

User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13

It provides detailed information on browser. However, it's pretty much free format so it's very hard to decipher every single one. You just need to figure out which browsers you will support and write parser for each one. When you try to identify the version of browser, always check newer version first. For example, IE6 user-agent may contain IE5 for backward compatibility. If you check IE5 first, IE6 will be categorized as IE5 also.

You can get a full list of all user-agent values from this web site,

http://www.user-agents.org/

With User-Agent, you can tell the exact version of the browser. You can get a pretty good idea on OS but you may not be able to distinguish between different versions of the same OS, for example, Windows NT and 2000 may use same User-Agent.

There is nothing about resolution. However, you can get this with Javascript on an AJAX call.

.bashrc at ssh login

For an excellent resource on how bash invocation works, what dotfiles do what, and how you should use/configure them, read this:

Enterprise app deployment doesn't work on iOS 7.1

Further the previous answers about Dropbox, I implemented the following files tree such as only the PLIST file has to be uploaded to Dropbox:

  1. upload the ipa file to your server in http (no change here)
  2. upload the provisioning (.mobileprovision) file to your server in http (no change here)
  3. upload the plist file to your dropbox (no change to do inside the plist file as the URLs are in absolute)
  4. use the option "Share the link with Dropbox" which copies the link to your clipboard. This link has to be copied into your html file into the itms-servivces URL's query after changing the part www.dropbox.com by dl.dropboxusercontent.com. Note I URL encoded the link as suggested by @Mike but I don't test without to do it. Now the itms-services URL's query should look like this: itms-services://?action=download-manifest&url=https%3A%2F%2Fdl.dropboxusercontent.com%2Fs%2FYourShortDropboxLink.plist

  5. upload the html file to your server in http. Note the html file contains both links to ipa and provisioning files.

  6. access to your html file from your device and now the ipa can be installed by OTA like usually.

From now, only the ipa file has to be changed to provide next app versions by OTA to your beta testers. Until Apple is yet changing the security rules.

I join here after the very simple HTML file I'm using:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>iPhone app for test</title>
</head>
<body>
<h1>iPhone app for test</h1>
<br/>
<ul>
    <li><a href="http://www.yourdomain.com/with/directories/provision/v.last/yourprovision_adhoc.mobileprovision">
            Install Provisioning File</a></li>
    <li><a href="itms-services://?action=download-manifest&url=https%3A%2F%2Fdl.dropboxusercontent.com%2Fs%2FYourShortDropboxLink.plist">
            Install Application</a></li>
</ul>
</body>
</html>

Remove non-ASCII characters from CSV

As an alternative to sed or perl you may consider to use ed(1) and POSIX character classes.

Note: ed(1) reads the entire file into memory to edit it in-place, so for really large files you should use sed -i ..., perl -i ...

# see:
# - http://wiki.bash-hackers.org/doku.php?id=howto:edit-ed
# - http://en.wikipedia.org/wiki/Regular_expression#POSIX_character_classes

# test
echo $'aaa \177 bbb \200 \214 ccc \254 ddd\r\n' > testfile
ed -s testfile <<< $',l' 
ed -s testfile <<< $'H\ng/[^[:graph:][:space:][:cntrl:]]/s///g\nwq'
ed -s testfile <<< $',l'

Bash tool to get nth line from a file

As a followup to CaffeineConnoisseur's very helpful benchmarking answer... I was curious as to how fast the 'mapfile' method was compared to others (as that wasn't tested), so I tried a quick-and-dirty speed comparison myself as I do have bash 4 handy. Threw in a test of the "tail | head" method (rather than head | tail) mentioned in one of the comments on the top answer while I was at it, as folks are singing its praises. I don't have anything nearly the size of the testfile used; the best I could find on short notice was a 14M pedigree file (long lines that are whitespace-separated, just under 12000 lines).

Short version: mapfile appears faster than the cut method, but slower than everything else, so I'd call it a dud. tail | head, OTOH, looks like it could be the fastest, although with a file this size the difference is not all that substantial compared to sed.

$ time head -11000 [filename] | tail -1
[output redacted]

real    0m0.117s

$ time cut -f11000 -d$'\n' [filename]
[output redacted]

real    0m1.081s

$ time awk 'NR == 11000 {print; exit}' [filename]
[output redacted]

real    0m0.058s

$ time perl -wnl -e '$.== 11000 && print && exit;' [filename]
[output redacted]

real    0m0.085s

$ time sed "11000q;d" [filename]
[output redacted]

real    0m0.031s

$ time (mapfile -s 11000 -n 1 ary < [filename]; echo ${ary[0]})
[output redacted]

real    0m0.309s

$ time tail -n+11000 [filename] | head -n1
[output redacted]

real    0m0.028s

Hope this helps!

Linker Error C++ "undefined reference "

Your error shows you are not compiling file with the definition of the insert function. Update your command to include the file which contains the definition of that function and it should work.

S3 Static Website Hosting Route All Paths to Index.html

since the problem is still there I though I throw in another solution. My case was that I wanted to auto deploy all pull requests to s3 for testing before merge making them accessible on [mydomain]/pull-requests/[pr number]/
(ex. www.example.com/pull-requests/822/)

To the best of my knowledge non of s3 rules scenarios would allow to have multiple projects in one bucket using html5 routing so while above most voted suggestion works for a project in root folder, it doesn't for multiple projects in own subfolders.

So I pointed my domain to my server where following nginx config did the job

location /pull-requests/ {
    try_files $uri @get_files;
}
location @get_files {
    rewrite ^\/pull-requests\/(.*) /$1 break;
    proxy_pass http://<your-amazon-bucket-url>;
    proxy_intercept_errors on;
    recursive_error_pages on;
    error_page 404 = @get_routes;
}

location @get_routes {
    rewrite ^\/(\w+)\/(.+) /$1/ break;
    proxy_pass http://<your-amazon-bucket-url>;
    proxy_intercept_errors on;
    recursive_error_pages on;
    error_page 404 = @not_found;
}

location @not_found {
    return 404;
}

it tries to get the file and if not found assumes it is html5 route and tries that. If you have a 404 angular page for not found routes you will never get to @not_found and get you angular 404 page returned instead of not found files, which could be fixed with some if rule in @get_routes or something.

I have to say I don't feel too comfortable in area of nginx config and using regex for that matter, I got this working with some trial and error so while this works I am sure there is room for improvement and please do share your thoughts.

Note: remove s3 redirection rules if you had them in S3 config.

and btw works in Safari

Center image using text-align center?

Only if you need to support ancient versions of Internet Explorer.

The modern approach is to do margin: 0 auto in your CSS.

Example here: http://jsfiddle.net/bKRMY/

HTML:

<p>Hello the following image is centered</p>
<p class="pic"><img src="https://twimg0-a.akamaihd.net/profile_images/440228301/StackoverflowLogo_reasonably_small.png"/></p>
<p>Did it work?</p>

CSS:

p.pic {
    width: 48px;
    margin: 0 auto;
}

The only issue here is that the width of the paragraph must be the same as the width of the image. If you don't put a width on the paragraph, it will not work, because it will assume 100% and your image will be aligned left, unless of course you use text-align:center.

Try out the fiddle and experiment with it if you like.

The project cannot be built until the build path errors are resolved.

Go to > Right CLick on your project folder > Build Path > Configure Build Path > Libraries Tab > remove project and external dependencies > apply & close

Now, Gradle refresh your project.

How do you compare two version Strings in Java?

Using Java 8 Stream to replace leading zeroes in components. This code passed all tests on interviewbit.com

public int compareVersion(String A, String B) {
    List<String> strList1 = Arrays.stream(A.split("\\."))
                                           .map(s -> s.replaceAll("^0+(?!$)", ""))
                                           .collect(Collectors.toList());
    List<String> strList2 = Arrays.stream(B.split("\\."))
                                           .map(s -> s.replaceAll("^0+(?!$)", ""))
                                           .collect(Collectors.toList());
    int len1 = strList1.size();
    int len2 = strList2.size();
    int i = 0;
    while(i < len1 && i < len2){
        if (strList1.get(i).length() > strList2.get(i).length()) return 1;
        if (strList1.get(i).length() < strList2.get(i).length()) return -1;
        int result = new Long(strList1.get(i)).compareTo(new Long(strList2.get(i)));
        if (result != 0) return result;
        i++;
    }
    while (i < len1){
        if (!strList1.get(i++).equals("0")) return 1;
    }
    while (i < len2){
        if (!strList2.get(i++).equals("0")) return -1;
    }
    return 0;
}

Python RuntimeWarning: overflow encountered in long scalars

An easy way to overcome this problem is to use 64 bit type

list = numpy.array(list, dtype=numpy.float64)

C++ cast to derived class

Think like this:

class Animal { /* Some virtual members */ };
class Dog: public Animal {};
class Cat: public Animal {};


Dog     dog;
Cat     cat;
Animal& AnimalRef1 = dog;  // Notice no cast required. (Dogs and cats are animals).
Animal& AnimalRef2 = cat;
Animal* AnimalPtr1 = &dog;
Animal* AnimlaPtr2 = &cat;

Cat&    catRef1 = dynamic_cast<Cat&>(AnimalRef1);  // Throws an exception  AnimalRef1 is a dog
Cat*    catPtr1 = dynamic_cast<Cat*>(AnimalPtr1);  // Returns NULL         AnimalPtr1 is a dog
Cat&    catRef2 = dynamic_cast<Cat&>(AnimalRef2);  // Works
Cat*    catPtr2 = dynamic_cast<Cat*>(AnimalPtr2);  // Works

// This on the other hand makes no sense
// An animal object is not a cat. Therefore it can not be treated like a Cat.
Animal  a;
Cat&    catRef1 = dynamic_cast<Cat&>(a);    // Throws an exception  Its not a CAT
Cat*    catPtr1 = dynamic_cast<Cat*>(&a);   // Returns NULL         Its not a CAT.

Now looking back at your first statement:

Animal   animal = cat;    // This works. But it slices the cat part out and just
                          // assigns the animal part of the object.
Cat      bigCat = animal; // Makes no sense.
                          // An animal is not a cat!!!!!
Dog      bigDog = bigCat; // A cat is not a dog !!!!

You should very rarely ever need to use dynamic cast.
This is why we have virtual methods:

void makeNoise(Animal& animal)
{
     animal.DoNoiseMake();
}

Dog    dog;
Cat    cat;
Duck   duck;
Chicken chicken;

makeNoise(dog);
makeNoise(cat);
makeNoise(duck);
makeNoise(chicken);

The only reason I can think of is if you stored your object in a base class container:

std::vector<Animal*>  barnYard;
barnYard.push_back(&dog);
barnYard.push_back(&cat);
barnYard.push_back(&duck);
barnYard.push_back(&chicken);

Dog*  dog = dynamic_cast<Dog*>(barnYard[1]); // Note: NULL as this was the cat.

But if you need to cast particular objects back to Dogs then there is a fundamental problem in your design. You should be accessing properties via the virtual methods.

barnYard[1]->DoNoiseMake();

How to show progress bar while loading, using ajax

Here is an example that's working for me with MVC and Javascript in the Razor. The first function calls an action via ajax on my controller and passes two parameters.

        function redirectToAction(var1, var2)
        {
            try{

                var url = '../actionnameinsamecontroller/' + routeId;

                $.ajax({
                    type: "GET",
                    url: url,
                    data: { param1: var1, param2: var2 },
                    dataType: 'html',
                    success: function(){
                    },
                    error: function(xhr, ajaxOptions, thrownError){
                        alert(error);
                    }
                });

            }
            catch(err)
            {
                alert(err.message);
            }
        }

Use the ajaxStart to start your progress bar code.

           $(document).ajaxStart(function(){
            try
            {
                // showing a modal
                $("#progressDialog").modal();

                var i = 0;
                var timeout = 750;

                (function progressbar()
                {
                    i++;
                    if(i < 1000)
                    {
                        // some code to make the progress bar move in a loop with a timeout to 
                        // control the speed of the bar
                        iterateProgressBar();
                        setTimeout(progressbar, timeout);
                    }
                }
                )();
            }
            catch(err)
            {
                alert(err.message);
            }
        });

When the process completes close the progress bar

        $(document).ajaxStop(function(){
            // hide the progress bar
            $("#progressDialog").modal('hide');
        });

Should I use int or Int32

I always use the system types - e.g., Int32 instead of int. I adopted this practice after reading Applied .NET Framework Programming - author Jeffrey Richter makes a good case for using the full type names. Here are the two points that stuck with me:

  1. Type names can vary between .NET languages. For example, in C#, long maps to System.Int64 while in C++ with managed extensions, long maps to Int32. Since languages can be mixed-and-matched while using .NET, you can be sure that using the explicit class name will always be clearer, no matter the reader's preferred language.

  2. Many framework methods have type names as part of their method names:

    BinaryReader br = new BinaryReader( /* ... */ );
    float val = br.ReadSingle();     // OK, but it looks a little odd...
    Single val = br.ReadSingle();    // OK, and is easier to read
    

How to remove space from string?

The tools sed or tr will do this for you by swapping the whitespace for nothing

sed 's/ //g'

tr -d ' '

Example:

$ echo "   3918912k " | sed 's/ //g'
3918912k

How to install a certificate in Xcode (preparing for app store submission)

Under

Provisioning -> Distribution -> Distribution Provisioning Profiles

I downloaded the desired certificate again and installed it. Now I don't see an empty file in Xcode. The build also works now (no code sign error).

What I also did: I downloaded the WWDR and installed it, but I don't know if that was the reason (because I think it's always the same)

Extract the first word of a string in a SQL Server query

DECLARE @string NVARCHAR(50)

SET @string = 'CUT STRING'

SELECT LEFT(@string,(PATINDEX('% %',@string)))

How to inject Javascript in WebBrowser control?

i use this:

webBrowser.Document.InvokeScript("execScript", new object[] { "alert(123)", "JavaScript" })

How to return JSON data from spring Controller using @ResponseBody

In my case I was using jackson-databind-2.8.8.jar that is not compatible with JDK 1.6 I need to use so Spring wasn't loading this converter. I downgraded the version and it works now.

How to use callback with useState hook in react

we can write customise function which will call the callBack function if any changes in the state

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const useStateCallbackWrapper = (initilValue, callBack) => {
  const [state, setState] = useState(initilValue);
  useEffect(() => callBack(state), [state]);
  return [state, setState];
};

const callBack = state => {
  console.log("---------------", state);
};
function App() {
  const [count, setCount] = useStateCallbackWrapper(0, callBack);
  return (
    <div className="App">
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>+</button>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

`

How to hide a div element depending on Model value? MVC

Your code isn't working, because the hidden attibute is not supported in versions of IE before v11

If you need to support IE before version 11, add a CSS style to hide when the hidden attribute is present:

*[hidden] { display: none; }

Does C# support multiple inheritance?

Actually, it depends on your definition of inheritance:

  • you can inherit implementation (members, i.e. data and behavior) from a single class, but
  • you can inherit interfaces from multiple, well, interfaces.

This is not what is usually meant by the term "inheritance", but it is also not entirely unreasonable to define it this way.

How to get child element by index in Jquery?

$('.second').find('div:first')

How to change the display name for LabelFor in razor in mvc3?

This was an old question, but existing answers ignore the serious issue of throwing away any custom attributes when you regenerate the model. I am adding a more detailed answer to cover the current options available.

You have 3 options:

  • Add a [DisplayName("Name goes here")] attribute to the data model class. The downside is that this is thrown away whenever you regenerate the data models.
  • Add a string parameter to your Html.LabelFor. e.g. @Html.LabelFor(model => model.SomekingStatus, "My New Label", new { @class = "control-label"}) Reference: https://msdn.microsoft.com/en-us/library/system.web.mvc.html.labelextensions.labelfor(v=vs.118).aspx The downside to this is that you must repeat the label in every view.
  • Third option. Use a meta-data class attached to the data class (details follow).

Option 3 - Add a Meta-Data Class:

Microsoft allows for decorating properties on an Entity Framework class, without modifying the existing class! This by having meta-data classes that attach to your database classes (effectively a sideways extension of your EF class). This allow attributes to be added to the associated class and not to the class itself so the changes are not lost when you regenerate the data models.

For example, if your data class is MyModel with a SomekingStatus property, you could do it like this:

First declare a partial class of the same name (and using the same namespace), which allows you to add a class attribute without being overridden:

[MetadataType(typeof(MyModelMetaData))]
public partial class MyModel
{
}

All generated data model classes are partial classes, which allow you to add extra properties and methods by simply creating more classes of the same name (this is very handy and I often use it e.g. to provide formatted string versions of other field types in the model).

Step 2: add a metatadata class referenced by your new partial class:

public class MyModelMetaData
{
    // Apply DisplayNameAttribute (or any other attributes)
    [DisplayName("My New Label")]
    public string SomekingStatus;
}

Reference: https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.metadatatypeattribute(v=vs.110).aspx

Notes:

  • From memory, if you start using a metadata class, it may ignore existing attributes on the actual class ([required] etc) so you may need to duplicate those in the Meta-data class.
  • This does not operate by magic and will not just work with any classes. The code that looks for UI decoration attributes is designed to look for a meta-data class first.

ImportError: No module named google.protobuf

To find where the name google clashes .... try this:

python3

then >>> help('google')

... I got info about google-auth:

NAME
    google

PACKAGE CONTENTS
    auth (package)
    oauth2 (package)

Also then try

pip show google-auth

Then

sudo pip3 uninstall google-auth

... and re-try >>> help('google')

I then see protobuf:

NAME
    google

PACKAGE CONTENTS
    protobuf (package)

How to insert a new line in strings in Android

Try using System.getProperty("line.separator") to get a new line.

How to use npm with ASP.NET Core

I give you two answers. npm combined with other tools is powerful but requires some work to setup. If you just want to download some libraries, you might want to use Library Manager instead (released in Visual Studio 15.8).

NPM (Advanced)

First add package.json in the root of you project. Add the following content:

{
  "version": "1.0.0",
  "name": "asp.net",
  "private": true,
  "devDependencies": {
    "gulp": "3.9.1",
    "del": "3.0.0"
  },
  "dependencies": {
    "jquery": "3.3.1",
    "jquery-validation": "1.17.0",
    "jquery-validation-unobtrusive": "3.2.10",
    "bootstrap": "3.3.7"
  }
}

This will make NPM download Bootstrap, JQuery and other libraries that is used in a new asp.net core project to a folder named node_modules. Next step is to copy the files to an appropriate place. To do this we will use gulp, which also was downloaded by NPM. Then add a new file in the root of you project named gulpfile.js. Add the following content:

/// <binding AfterBuild='default' Clean='clean' />
/*
This file is the main entry point for defining Gulp tasks and using Gulp plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
*/

var gulp = require('gulp');
var del = require('del');

var nodeRoot = './node_modules/';
var targetPath = './wwwroot/lib/';

gulp.task('clean', function () {
    return del([targetPath + '/**/*']);
});

gulp.task('default', function () {
    gulp.src(nodeRoot + "bootstrap/dist/js/*").pipe(gulp.dest(targetPath + "/bootstrap/dist/js"));
    gulp.src(nodeRoot + "bootstrap/dist/css/*").pipe(gulp.dest(targetPath + "/bootstrap/dist/css"));
    gulp.src(nodeRoot + "bootstrap/dist/fonts/*").pipe(gulp.dest(targetPath + "/bootstrap/dist/fonts"));

    gulp.src(nodeRoot + "jquery/dist/jquery.js").pipe(gulp.dest(targetPath + "/jquery/dist"));
    gulp.src(nodeRoot + "jquery/dist/jquery.min.js").pipe(gulp.dest(targetPath + "/jquery/dist"));
    gulp.src(nodeRoot + "jquery/dist/jquery.min.map").pipe(gulp.dest(targetPath + "/jquery/dist"));

    gulp.src(nodeRoot + "jquery-validation/dist/*.js").pipe(gulp.dest(targetPath + "/jquery-validation/dist"));

    gulp.src(nodeRoot + "jquery-validation-unobtrusive/dist/*.js").pipe(gulp.dest(targetPath + "/jquery-validation-unobtrusive"));
});

This file contains a JavaScript code that is executed when the project is build and cleaned. It’s will copy all necessary files to lib2 (not lib – you can easily change this). I have used the same structure as in a new project, but it’s easy to change files to a different location. If you move the files, make sure you also update _Layout.cshtml. Note that all files in the lib2-directory will be removed when the project is cleaned.

If you right click on gulpfile.js, you can select Task Runner Explorer. From here you can run gulp manually to copy or clean files.

Gulp could also be useful for other tasks like minify JavaScript and CSS-files:

https://docs.microsoft.com/en-us/aspnet/core/client-side/using-gulp?view=aspnetcore-2.1

Library Manager (Simple)

Right click on you project and select Manage client side-libraries. The file libman.json is now open. In this file you specify which library and files to use and where they should be stored locally. Really simple! The following file copies the default libraries that is used when creating a new ASP.NET Core 2.1 project:

{
  "version": "1.0",
  "defaultProvider": "cdnjs",
  "libraries": [
    {
      "library": "[email protected]",
      "files": [ "jquery.js", "jquery.min.map", "jquery.min.js" ],
      "destination": "wwwroot/lib/jquery/dist/"
    },
    {
      "library": "[email protected]",
      "files": [ "additional-methods.js", "additional-methods.min.js", "jquery.validate.js", "jquery.validate.min.js" ],
      "destination": "wwwroot/lib/jquery-validation/dist/"
    },
    {
      "library": "[email protected]",
      "files": [ "jquery.validate.unobtrusive.js", "jquery.validate.unobtrusive.min.js" ],
      "destination": "wwwroot/lib/jquery-validation-unobtrusive/"
    },
    {
      "library": "[email protected]",
      "files": [
        "css/bootstrap.css",
        "css/bootstrap.css.map",
        "css/bootstrap.min.css",
        "css/bootstrap.min.css.map",
        "css/bootstrap-theme.css",
        "css/bootstrap-theme.css.map",
        "css/bootstrap-theme.min.css",
        "css/bootstrap-theme.min.css.map",
        "fonts/glyphicons-halflings-regular.eot",
        "fonts/glyphicons-halflings-regular.svg",
        "fonts/glyphicons-halflings-regular.ttf",
        "fonts/glyphicons-halflings-regular.woff",
        "fonts/glyphicons-halflings-regular.woff2",
        "js/bootstrap.js",
        "js/bootstrap.min.js",
        "js/npm.js"
      ],
      "destination": "wwwroot/lib/bootstrap/dist"
    },
    {
      "library": "[email protected]",
      "files": [ "list.js", "list.min.js" ],
      "destination": "wwwroot/lib/listjs"
    }
  ]
}

If you move the files, make sure you also update _Layout.cshtml.

Split string into string array of single characters

Try this:

var charArray = "this is a test".ToCharArray().Select(c=>c.ToString());

How do I ZIP a file in C#, using no 3rd-party APIs?

How can I programatically (C#) ZIP a file (in Windows) without using any third party libraries?

If using the 4.5+ Framework, there is now the ZipArchive and ZipFile classes.

using (ZipArchive zip = ZipFile.Open("test.zip", ZipArchiveMode.Create))
{
    zip.CreateEntryFromFile(@"c:\something.txt", "data/path/something.txt");
}

You need to add references to:

  • System.IO.Compression
  • System.IO.Compression.FileSystem

For .NET Core targeting net46, you need to add dependencies for

  • System.IO.Compression
  • System.IO.Compression.ZipFile

Example project.json:

"dependencies": {
  "System.IO.Compression": "4.1.0",
  "System.IO.Compression.ZipFile": "4.0.1"
},

"frameworks": {
  "net46": {}
}

For .NET Core 2.0, just adding a simple using statement is all that is needed:

  • using System.IO.Compression;

How to get streaming url from online streaming radio station

Edited ZygD's answer for python 3.x.:

import re
import urllib.request
import string
url1 = input("Please enter a URL from Tunein Radio: ");
request = urllib.request.Request(url1);
response = urllib.request.urlopen(request);
raw_file = response.read().decode('utf-8');
API_key = re.findall(r"StreamUrl\":\"(.*?),\"",raw_file);
#print API_key;
#print "The API key is: " + API_key[0];
request2 = urllib.request.Request(str(API_key[0]));
response2 = urllib.request.urlopen(request2);
key_content = response2.read().decode('utf-8');
raw_stream_url = re.findall(r"Url\": \"(.*?)\"",key_content);
bandwidth = re.findall(r"Bandwidth\":(.*?),", key_content);
reliability = re.findall(r"lity\":(.*?),", key_content);
isPlaylist = re.findall(r"HasPlaylist\":(.*?),",key_content);
codec = re.findall(r"MediaType\": \"(.*?)\",", key_content);
tipe = re.findall(r"Type\": \"(.*?)\"", key_content);
total = 0
for element in raw_stream_url:
    total = total + 1
i = 0
print ("I found " + str(total) + " streams.");
for element in raw_stream_url:
    print ("Stream #" + str(i + 1));
    print ("Stream stats:");
    print ("Bandwidth: " + str(bandwidth[i]) + " kilobytes per second.");
    print ("Reliability: " + str(reliability[i]) + "%");
    print ("HasPlaylist: " + str(isPlaylist[i]));
    print ("Stream codec: " + str(codec[i]));
    print ("This audio stream is " + tipe[i].lower());
    print ("Pure streaming URL: " + str(raw_stream_url[i]));
i = i + 1
input("Press enter to close")

Implicit type conversion rules in C++ operators

Caveat!

The conversions occur from left to right.

Try this:

int i = 3, j = 2;
double k = 33;
cout << k * j / i << endl; // prints 22
cout << j / i * k << endl; // prints 0

Can't start Eclipse - Java was started but returned exit code=13

Please check whether you have set two JAVA paths in the Environment Variable section. If you already installed two versions of the JDK, it might be, then double check you have put PATH for Java like below.

PATH -->  C:\ProgramData\Oracle\Java\javapath

and also

JAVA_HOME ---> C:\Program Files\Java\jdk1.7.0_02\bin

If both are there, then this sort of error may occur.

If it's OK, then check in the ".ini" file the below area is OK or not. Open ".ini" file and check

 -VM  path is  C:\Program Files\Java\jdk1.7.0_79\bin\

If not, please set it like that and run again.

read word by word from file in C++

If I may I could give you some new code for the same task, in my code you can create a so called 'document'(not really)and it is saved, and can be opened up again. It is also stored as a string file though(not a document). Here is the code:

#include "iostream"

#include "windows.h"

#include "string"

#include "fstream"

using namespace std;

int main() {

string saveload;


cout << "---------------------------" << endl;
cout << "|enter 'text' to write your document    |" << endl;
cout << "|enter 'open file' to open the document |" << endl;
cout << "----------------------------------------" << endl;
while (true){
    getline(cin, saveload);

    if (saveload == "open file"){
        string filenamet;
        cout << "file name? " << endl;
        getline(cin, filenamet, '*');
        ifstream loadFile;

        loadFile.open(filenamet, ifstream::in);

        cout << "the text you entered was: ";

        while (loadFile.good()){

            cout << (char)loadFile.get();

            Sleep(100);
        }

        cout << "" << endl;

        loadFile.close();

    }

    if (saveload == "text") {
        string filename;
        cout << "file name: " << endl;
        getline(cin, filename,'*');
        string textToSave;
        cout << "Enter your text: " << endl;
        getline(cin, textToSave,'*');

        ofstream saveFile(filename);

        saveFile << textToSave;

        saveFile.close();

    }
}
return 0;
}

Just take this code and change it to serve your purpose. DREAM BIG,THINK BIG, DO BIG

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

JPA or JDBC, how are they different?

JDBC is a much lower-level (and older) specification than JPA. In it's bare essentials, JDBC is an API for interacting with a database using pure SQL - sending queries and retrieving results. It has no notion of objects or hierarchies. When using JDBC, it's up to you to translate a result set (essentially a row/column matrix of values from one or more database tables, returned by your SQL query) into Java objects.

Now, to understand and use JDBC it's essential that you have some understanding and working knowledge of SQL. With that also comes a required insight into what a relational database is, how you work with it and concepts such as tables, columns, keys and relationships. Unless you have at least a basic understanding of databases, SQL and data modelling you will not be able to make much use of JDBC since it's really only a thin abstraction on top of these things.

How many bytes is unsigned long long?

The beauty of C++, like C, is that the sized of these things are implementation-defined, so there's no correct answer without your specifying the compiler you're using. Are those two the same? Yes. "long long" is a synonym for "long long int", for any compiler that will accept both.

Understanding the Linux oom-killer's logs

This webpage have an explanation and a solution.

The solution is:

To fix this problem the behavior of the kernel has to be changed, so it will no longer overcommit the memory for application requests. Finally I have included those mentioned values into the /etc/sysctl.conf file, so they get automatically applied on start-up:

vm.overcommit_memory = 2

vm.overcommit_ratio = 80

How to get all checked checkboxes

A simple for loop which tests the checked property and appends the checked ones to a separate array. From there, you can process the array of checkboxesChecked further if needed.

// Pass the checkbox name to the function
function getCheckedBoxes(chkboxName) {
  var checkboxes = document.getElementsByName(chkboxName);
  var checkboxesChecked = [];
  // loop over them all
  for (var i=0; i<checkboxes.length; i++) {
     // And stick the checked ones onto an array...
     if (checkboxes[i].checked) {
        checkboxesChecked.push(checkboxes[i]);
     }
  }
  // Return the array if it is non-empty, or null
  return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}

// Call as
var checkedBoxes = getCheckedBoxes("mycheckboxes");

How add unique key to existing table (with non uniques rows)

Set Multiple Unique key into table

ALTER TABLE table_name
ADD CONSTRAINT UC_table_name UNIQUE (field1,field2);

How do I check particular attributes exist or not in XML?

EDIT

Disregard - you can't use ItemOf (that's what I get for typing before I test). I'd strikethrough the text if I could figure out how...or maybe I'll simply delete the answer, since it was ultimately wrong and useless.

END EDIT

You can use the ItemOf(string) property in the XmlAttributesCollection to see if the attribute exists. It returns null if it's not found.

foreach (XmlNode xNode in nodeListName)
{
    if (xNode.ParentNode.Attributes.ItemOf["split"] != null)
    {
         parentSplit = xNode.ParentNode.Attributes["split"].Value;
    }
}

XmlAttributeCollection.ItemOf Property (String)

how to access the command line for xampp on windows

In the version 3.2.4 of the XAMPP Control Panel, there is button that can open a command line prompt (red rectangle in the next figure)

enter image description here

After pressing the button, you will see the command prompt window.

enter image description here

From this window you can navigate through the different folders and start the different services available.

Android: Color To Int conversion

I think it should be R.color.black

Also take a look at Converting android color string in runtime into int

What is the difference between up-casting and down-casting with respect to class variable

Down-casting and up-casting was as follows:
enter image description here

Upcasting: When we want to cast a Sub class to Super class, we use Upcasting(or widening). It happens automatically, no need to do anything explicitly.

Downcasting : When we want to cast a Super class to Sub class, we use Downcasting(or narrowing), and Downcasting is not directly possible in Java, explicitly we have to do.

Dog d = new Dog();
Animal a = (Animal) d; //Explicitly you have done upcasting. Actually no need, we can directly type cast like Animal a = d; compiler now treat Dog as Animal but still it is Dog even after upcasting
d.callme();
a.callme(); // It calls Dog's method even though we use Animal reference.
((Dog) a).callme2(); // Downcasting: Compiler does know Animal it is, In order to use Dog methods, we have to do typecast explicitly.
// Internally if it is not a Dog object it throws ClassCastException

How to create a Restful web service with input parameters?

another way to do is get the UriInfo instead of all the QueryParam

Then you will be able to get the queryParam as per needed in your code

@GET
@Path("/query")
public Response getUsers(@Context UriInfo info) {

    String param_1 = info.getQueryParameters().getFirst("param_1");
    String param_2 = info.getQueryParameters().getFirst("param_2");


    return Response ;

}

How to Empty Caches and Clean All Targets Xcode 4 and later

I have been pulling out hair from my head because I thought that I had the same problem. When building the app I didn't get the same result on my iPhone as on the simulator.

The problem was that I had somehow made a localized version of the MainStoryboard.storyboard file. So when I ran the app on my phone it showed the danish version... and the simulator showed the english version.

Yeah I'm new! :)

Inverse of a matrix using numpy

Inverse of a matrix using python and numpy:

>>> import numpy as np
>>> b = np.array([[2,3],[4,5]])
>>> np.linalg.inv(b)
array([[-2.5,  1.5],
       [ 2. , -1. ]])

Not all matrices can be inverted. For example singular matrices are not Invertable:

>>> import numpy as np
>>> b = np.array([[2,3],[4,6]])
>>> np.linalg.inv(b)

LinAlgError: Singular matrix

Solution to singular matrix problem:

try-catch the Singular Matrix exception and keep going until you find a transform that meets your prior criteria AND is also invertable.

Intuition for why matrix inversion can't always be done; like in singular matrices:

Imagine an old overhead film projector that shines a bright light through film onto a white wall. The pixels in the film are projected to the pixels on the wall.

If I stop the film projection on a single frame, you will see the pixels of the film on the wall and I ask you to regenerate the film based on what you see. That's easy, you say, just take the inverse of the matrix that performed the projection. An Inverse of a matrix is the reversal of the projection.

Now imagine if the projector was corrupted, and I put a distorted lens in front of the film. Now multiple pixels are projected to the same spot on the wall. I asked you again to "undo this operation with the matrix inverse". You say: "I can't because you destroyed information with the lens distortion, I can't get back to where we were, because the matrix is either Singular or Degenerate."

A matrix that can be used to transform some data into other data is invertable only if the process can be reversed with no loss of information. If your matrix can't be inverted, perhaps you are defining your projection using a guess-and-check methodology rather than using a process that guarantees a non-corrupting transform.

If you're using a heuristic or anything less than perfect mathematical precision, then you'll have to define another process to manage and quarantine distortions so that programming by Brownian motion can resume.

Source:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.inv.html#numpy.linalg.inv

PostgreSQL visual interface similar to phpMyAdmin?

I would also highly recommend Adminer - http://www.adminer.org/

It is much faster than phpMyAdmin, does less funky iframe stuff, and supports both MySQL and PostgreSQL.

'sudo gem install' or 'gem install' and gem locations

Installing Ruby gems on a Mac is a common source of confusion and frustration. Unfortunately, most solutions are incomplete, outdated, and provide bad advice. I'm glad the accepted answer here says to NOT use sudo, which you should never need to do, especially if you don't understand what it does. While I used RVM years ago, I would recommend chruby in 2020.

Some of the other answers here provide alternative options for installing gems, but they don't mention the limitations of those solutions. What's missing is an explanation and comparison of the various options and why you might choose one over the other. I've attempted to cover most common scenarios in my definitive guide to installing Ruby gems on a Mac.

MYSQL Sum Query with IF Condition

How about this?

SUM(IF(PaymentType = "credit card", totalamount, 0)) AS CreditCardTotal

Create a function with optional call variables

I don't think your question is very clear, this code assumes that if you're going to include the -domain parameter, it's always 'named' (i.e. dostuff computername arg2 -domain domain); this also makes the computername parameter mandatory.

Function DoStuff(){
    param(
        [Parameter(Mandatory=$true)][string]$computername,
        [Parameter(Mandatory=$false)][string]$arg2,
        [Parameter(Mandatory=$false)][string]$domain
    )
    if(!($domain)){
        $domain = 'domain1'
    }
    write-host $domain
    if($arg2){
        write-host "arg2 present... executing script block"
    }
    else{
        write-host "arg2 missing... exiting or whatever"
    }
}

grabbing first row in a mysql query only

You didn't specify how the order is determined, but this will give you a rank value in MySQL:

SELECT t.*,
       @rownum := @rownum +1 AS rank
  FROM TBL_FOO t
  JOIN (SELECT @rownum := 0) r
 WHERE t.name = 'sarmen'

Then you can pick out what rows you want, based on the rank value.

How to display a database table on to the table in the JSP page

you can also print the data onto your HTML/JSP document. like:-

<!DOCTYPE html>
<html>
<head>
    <title>Jsp Sample</title>
    <%@page import="java.sql.*;"%>
</head>
<body bgcolor=yellow>
    <%
    try
    {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=(Connection)DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/forum","root","root");
        Statement st=con.createStatement();
        ResultSet rs=st.executeQuery("select * from student;");
    %><table border=1 align=center style="text-align:center">
      <thead>
          <tr>
             <th>ID</th>
             <th>NAME</th>
             <th>SKILL</th>
             <th>ACTION</th>
          </tr>
      </thead>
      <tbody>
        <%while(rs.next())
        {
            %>
            <tr>
                <td><%=rs.getString("id") %></td>
                <td><%=rs.getString("name") %></td>
                <td><%=rs.getString("skill") %></td>
                <td><%=rs.getString("action") %></td>
            </tr>
            <%}%>
           </tbody>
        </table><br>
    <%}
    catch(Exception e){
        out.print(e.getMessage());%><br><%
    }
    finally{
        st.close();
        con.close();
    }
    %>
</body>
</html>

<!--executeUpdate() mainupulation and executeQuery() for retriving-->

Is there a typescript List<> and/or Map<> class/library?

It's very easy to write that yourself, and that way you have more control over things.. As the other answers say, TypeScript is not aimed at adding runtime types or functionality.

Map:

class Map<T> {
    private items: { [key: string]: T };

    constructor() {
        this.items = {};
    }

    add(key: string, value: T): void {
        this.items[key] = value;
    }

    has(key: string): boolean {
        return key in this.items;
    }

    get(key: string): T {
        return this.items[key];
    }
}

List:

class List<T> {
    private items: Array<T>;

    constructor() {
        this.items = [];
    }

    size(): number {
        return this.items.length;
    }

    add(value: T): void {
        this.items.push(value);
    }

    get(index: number): T {
        return this.items[index];
    }
}

I haven't tested (or even tried to compile) this code, but it should give you a starting point.. you can of course then change what ever you want and add the functionality that YOU need...

As for your "special needs" from the List, I see no reason why to implement a linked list, since the javascript array lets you add and remove items.
Here's a modified version of the List to handle the get prev/next from the element itself:

class ListItem<T> {
    private list: List<T>;
    private index: number;

    public value: T;

    constructor(list: List<T>, value: T, index: number) {
        this.list = list;
        this.index = index;
        this.value = value;
    }

    prev(): ListItem<T> {
        return this.list.get(this.index - 1);
    }

    next(): ListItem<T> {
        return this.list.get(this.index + 1);   
    }
}

class List<T> {
    private items: Array<ListItem<T>>;

    constructor() {
        this.items = [];
    }

    size(): number {
        return this.items.length;
    }

    add(value: T): void {
        this.items.push(new ListItem<T>(this, value, this.size()));
    }

    get(index: number): ListItem<T> {
        return this.items[index];
    }
}

Here too you're looking at untested code..

Hope this helps.


Edit - as this answer still gets some attention

Javascript has a native Map object so there's no need to create your own:

let map = new Map();
map.set("key1", "value1");
console.log(map.get("key1")); // value1

Java - removing first character of a string

Use the substring() function with an argument of 1 to get the substring from position 1 (after the first character) to the end of the string (leaving the second argument out defaults to the full length of the string).

"Jamaica".substring(1);

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

You can find more debugging info just simply adding the option -loglevel debug, full command will be

ffmpeg -i INPUT OUTPUT -loglevel debug -v verbose

How to parse data in JSON format?

Following is simple example that may help you:

json_string = """
{
    "pk": 1, 
    "fa": "cc.ee", 
    "fb": {
        "fc": "", 
        "fd_id": "12345"
    }
}"""

import json
data = json.loads(json_string)
if data["fa"] == "cc.ee":
    data["fb"]["new_key"] = "cc.ee was present!"

print json.dumps(data)

The output for the above code will be:

{"pk": 1, "fb": {"new_key": "cc.ee was present!", "fd_id": "12345", 
 "fc": ""}, "fa": "cc.ee"}

Note that you can set the ident argument of dump to print it like so (for example,when using print json.dumps(data , indent=4)):

{
    "pk": 1, 
    "fb": {
        "new_key": "cc.ee was present!", 
        "fd_id": "12345", 
        "fc": ""
    }, 
    "fa": "cc.ee"
}

How and when to use ‘async’ and ‘await’

Async & Await Simple Explanation

Simple Analogy

A person may wait for their morning train. This is all they are doing as this is their primary task that they are currently performing. (synchronous programming (what you normally do!))

Another person may await their morning train whilst they smoke a cigarette and then drink their coffee. (Asynchronous programming)

What is asynchronous programming?

Asynchronous programming is where a programmer will choose to run some of his code on a separate thread from the main thread of execution and then notify the main thread on it's completion.

What does the async keyword actually do?

Prefixing the async keyword to a method name like

async void DoSomething(){ . . .

allows the programmer to use the await keyword when calling asynchronous tasks. That's all it does.

Why is this important?

In a lot of software systems the main thread is reserved for operations specifically relating to the User Interface. If I am running a very complex recursive algorithm that takes 5 seconds to complete on my computer, but I am running this on the Main Thread (UI thread) When the user tries to click on anything on my application, it will appear to be frozen as my main thread has queued and is currently processing far too many operations. As a result the main thread cannot process the mouse click to run the method from the button click.

When do you use Async and Await?

Use the asynchronous keywords ideally when you are doing anything that doesn't involve the user interface.

So lets say you're writing a program that allows the user to sketch on their mobile phone but every 5 seconds it is going to be checking the weather on the internet.

We should be awaiting the call the polling calls every 5 seconds to the network to get the weather as the user of the application needs to keep interacting with the mobile touch screen to draw pretty pictures.

How do you use Async and Await

Following on from the example above, here is some pseudo code of how to write it:

    //ASYNCHRONOUS
    //this is called using the await keyword every 5 seconds from a polling timer or something.

    async Task CheckWeather()
    {
        var weather = await GetWeather();
        //do something with the weather now you have it
    }

    async Task<WeatherResult> GetWeather()
    {

        var weatherJson = await CallToNetworkAddressToGetWeather();
        return deserializeJson<weatherJson>(weatherJson);
    }

    //SYNCHRONOUS
    //This method is called whenever the screen is pressed
    void ScreenPressed()
    {
        DrawSketchOnScreen();
    }

Additional Notes - Update

I forgot to mention in my original notes that in C# you can only await methods that are wrapped in Tasks. for example you may await this method:

// awaiting this will return a string.
// calling this without await (synchronously) will result in a Task<string> object.
async Task<string> FetchHelloWorld() {..

You cannot await methods that are not tasks like this:

async string FetchHelloWorld() {..

Feel free to review the source code for the Task class here.

Does a favicon have to be 32x32 or 16x16?

You will need separate files for each resolution I am afraid. There is a really good article on campaign monitor describing how they created and implemented their icons for each iOS device too:

http://www.campaignmonitor.com/blog/post/3234/designing-campaign-monitor-ios-icons/

How to remove specific object from ArrayList in Java?

or you can use java 8 lambda

test.removeIf(i -> i==2);

it will simply remove all object that meet the condition

How to add a button dynamically using jquery

Try this:

<script type="text/javascript">

function test()
{
    if($('input#field').length==0)
    {
       $('<input type="button" id="field"/>').appendTo('body');
     }
}
</script>

How do I see the current encoding of a file in Sublime Text?

Another option in case you don't wanna use a plugin:

Ctrl+` or

View -> Show Console

type on the console the following command:

view.encoding()

In case you want to something more intrusive, there's a option to create an shortcut that executes the following command:

sublime.message_dialog(view.encoding())

Unable to load script from assets index.android.bundle on windows

For this problem I just solve it by running:

react-native start

then

adb reverse tcp:8081 tcp:8081

on command line. And then i can run:

react-native run-android

So i will not waste my time to run:

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

every time.

How can I produce an effect similar to the iOS 7 blur view?

You can find your solution from apple's DEMO in this page: WWDC 2013 , find out and download UIImageEffects sample code.

Then with @Jeremy Fox's code. I changed it to

- (UIImage*)getDarkBlurredImageWithTargetView:(UIView *)targetView
{
    CGSize size = targetView.frame.size;

    UIGraphicsBeginImageContext(size);
    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(c, 0, 0);
    [targetView.layer renderInContext:c]; // view is the view you are grabbing the screen shot of. The view that is to be blurred.
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return [image applyDarkEffect];
}

Hope this will help you.

How do I set up Vim autoindentation properly for editing Python files?

for more advanced python editing consider installing the simplefold vim plugin. it allows you do advanced code folding using regular expressions. i use it to fold my class and method definitions for faster editing.

How to increase executionTimeout for a long-running query?

To set timeout on a per page level, you could use this simple code:

Page.Server.ScriptTimeout = 60;

Note: 60 means 60 seconds, this time-out applies only if the debug attribute in the compilation element is False.

File to import not found or unreadable: compass

If you're like me and came here looking for a way to make sass --watch work with compass, the answer is to use Compass' version of watch, simply:

compass watch

If you're on a Mac and don't yet have the gem installed, you might run into errors when you try to install the Compass gem, due to permission problems that arise on OSX versions later than 10.11. Install ruby with Homebrew to get around this. See this answer for how to do that.

Alternatively you could just use CodeKit, but if you're stubborn like me and want to use Sublime Text and command line, this is the route to go.

Force file download with php using header()

Here is a snippet from me in testing... obviously passing via get to the script may not be the best... should post or just send an id and grab guid from db... anyhow.. this worked. I take the URL and convert it to a path.

// Initialize a file URL to the variable
$file = $_GET['url'];
$file = str_replace(Polepluginforrvms_Plugin::$install_url, $DOC_ROOT.'/pole-permitter/', $file );

$quoted = sprintf('"%s"', addcslashes(basename($file), '"\\'));
$size   = filesize($file);

header( "Content-type: application/octet-stream" );
header( "Content-Disposition: attachment; filename={$quoted}" );
header( "Content-length: " . $size );
header( "Pragma: no-cache" );
header( "Expires: 0" );
readfile( "{$file}" );

Create an Android GPS tracking application

The source code for the Android mobile application open-gpstracker which you appreciated is available here.

You can checkout the code using SVN client application or via Git:

Debugging the source code will surely help you.

How to create a hidden <img> in JavaScript?

This question is vague, but if you want to make the image with Javascript. It is simple.

function loadImages(src) {
  if (document.images) {
    img1 = new Image();
    img1.src = src;
}
loadImages("image.jpg");

The image will be requested but until you show it it will never be displayed. great for pre loading images you expect to be requests but delaying it until the document is loaded.

Example

How to change the color of a button?

You can change the colour two ways; through XML or through coding. I would recommend XML since it's easier to follow for beginners.

XML:

<Button
    android:background="@android:color/white"
    android:textColor="@android:color/black"
/>

You can also use hex values ex.

android:background="@android:color/white"

Coding:

//btn represents your button object

btn.setBackgroundColor(Color.WHITE);
btn.setTextColor(Color.BLACK);

"Cannot start compilation: the output path is not specified for module..."

After this

Two things to do:

Project Settings > Project compiler output > Set it as "Project path(You actual project's path)”+”\out”.

Project Settings > Module > Path > Choose "Inherit project compile path""

If button ran is not active

You must reload IDEA

How can I insert values into a table, using a subquery with more than one result?

INSERT INTO prices (group, id, price)
  SELECT 7, articleId, 1.50 FROM article WHERE name LIKE 'ABC%'

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

I had a similar issue and based on above suggestions I first added "super.setIntegerProperty("loadUrlTimeoutValue", 70000);" but that did not help. So I tried Project -> Clean, that worked and I can launch the app now !

Avinash...

How to display the value of the bar on each bar with pyplot.barh()?

Add:

for i, v in enumerate(y):
    ax.text(v + 3, i + .25, str(v), color='blue', fontweight='bold')

result:

enter image description here

The y-values v are both the x-location and the string values for ax.text, and conveniently the barplot has a metric of 1 for each bar, so the enumeration i is the y-location.

How to add and remove item from array in components in Vue 2

You can use Array.push() for appending elements to an array.

For deleting, it is best to use this.$delete(array, index) for reactive objects.

Vue.delete( target, key ): Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.

https://vuejs.org/v2/api/#Vue-delete

Getting list of Facebook friends with latest API

friends.get

Is function to get a list of friend's

And yes this is best

    $friends = $facebook->api('/me/friends');

    echo '<ul>';
    foreach ($friends["data"] as $value) {
        echo '<li>';
        echo '<div class="pic">';
        echo '<img src="https://graph.facebook.com/' . $value["id"] . '/picture"/>';
        echo '</div>';
        echo '<div class="picName">'.$value["name"].'</div>'; 
        echo '</li>';
    }
    echo '</ul>';

What is the !! (not not) operator in JavaScript?

It's a horribly obscure way to do a type conversion.

! is NOT. So !true is false, and !false is true. !0 is true, and !1 is false.

So you're converting a value to a boolean, then inverting it, then inverting it again.

// Maximum Obscurity:
val.enabled = !!userId;

// Partial Obscurity:
val.enabled = (userId != 0) ? true : false;

// And finally, much easier to understand:
val.enabled = (userId != 0);

PHP how to get value from array if key is in a variable

As others stated, it's likely failing because the requested key doesn't exist in the array. I have a helper function here that takes the array, the suspected key, as well as a default return in the event the key does not exist.

    protected function _getArrayValue($array, $key, $default = null)
    {
        if (isset($array[$key])) return $array[$key];
        return $default;
    }

hope it helps.

Android get Current UTC time

System.currentTimeMillis() does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date instance to a string before using it. You can use DateFormats to convert Dates to Strings in any timezone:

DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());

Also see this related question.

Multiple cases in switch statement

gcc implements an extension to the C language to support sequential ranges:

switch (value)
{
   case 1...3:
      //Do Something
      break;
   case 4...6:
      //Do Something
      break;
   default:
      //Do the Default
      break;
}

Edit: Just noticed the C# tag on the question, so presumably a gcc answer doesn't help.

How to do an INNER JOIN on multiple columns

if mysql is okay for you:

SELECT flights.*, 
       fromairports.city as fromCity, 
       toairports.city as toCity
FROM flights
LEFT JOIN (airports as fromairports, airports as toairports)
ON (fromairports.code=flights.fairport AND toairports.code=flights.tairport )
WHERE flights.fairport = '?' OR fromairports.city = '?'

edit: added example to filter the output for code or city

INNER JOIN same table

Your query should work fine, but you have to use the alias parent to show the values of the parent table like this:

select 
  CONCAT(user.user_fname, ' ', user.user_lname) AS 'User Name',
  CONCAT(parent.user_fname, ' ', parent.user_lname) AS 'Parent Name'
from users as user
inner join users as parent on parent.user_parent_id = user.user_id
where user.user_id = $_GET[id];

Fit Image in ImageButton in Android

You can make your ImageButton widget as I did. In my case, I needed a widget with a fixed icon size. Let's start from custom attributes:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ImageButtonFixedIconSize">
        <attr name="imageButton_icon" format="reference" />
        <attr name="imageButton_iconWidth" format="dimension" />
        <attr name="imageButton_iconHeight" format="dimension" />
    </declare-styleable>
</resources>

Widget class is quite simple (the key point is padding calculations in onLayout method):

class ImageButtonFixedIconSize
@JvmOverloads
constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = android.R.attr.imageButtonStyle
) : ImageButton(context, attrs, defStyleAttr) {

    private lateinit var icon: Drawable

    @Px
    private var iconWidth: Int = 0
    @Px
    private var iconHeight: Int = 0

    init {
        scaleType = ScaleType.FIT_XY
        attrs?.let { retrieveAttributes(it) }
    }

    /**
     *
     */
    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        val width = right - left
        val height = bottom - top

        val horizontalPadding = if(width > iconWidth) (width - iconWidth) / 2 else 0
        val verticalPadding = if(height > iconHeight) (height - iconHeight) / 2 else 0

        setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding)

        setImageDrawable(icon)

        super.onLayout(changed, left, top, right, bottom)
    }

    /**
     *
     */
    private fun retrieveAttributes(attrs: AttributeSet) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ImageButtonFixedIconSize)

        icon = typedArray.getDrawable(R.styleable.ImageButtonFixedIconSize_imageButton_icon)!!

        iconWidth = typedArray.getDimension(R.styleable.ImageButtonFixedIconSize_imageButton_iconWidth, 0f).toInt()
        iconHeight = typedArray.getDimension(R.styleable.ImageButtonFixedIconSize_imageButton_iconHeight, 0f).toInt()

        typedArray.recycle()
    }
}

And at last you should use your widget like this:

<com.syleiman.gingermoney.ui.common.controls.ImageButtonFixedIconSize
    android:layout_width="90dp"
    android:layout_height="63dp"

    app:imageButton_icon="@drawable/ic_backspace"
    app:imageButton_iconWidth="20dp"
    app:imageButton_iconHeight="15dp"

    android:id="@+id/backspaceButton"
    tools:ignore="ContentDescription"
    />

What happens if you don't commit a transaction to a database (say, SQL Server)?

In addition to the potential locking problems you might cause you will also find that your transaction logs begin to grow as they can not be truncated past the minimum LSN for an active transaction and if you are using snapshot isolation your version store in tempdb will grow for similar reasons.

You can use dbcc opentran to see details of the oldest open transaction.

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

How do I log a Python error with debug information?

If you can cope with the extra dependency then use twisted.log, you don't have to explicitly log errors and also it returns the entire traceback and time to the file or stream.

How to close TCP and UDP ports via windows command line

You can't close sockets on your server without owning those sockets hence you can't actually close the socket down without having code running in the process that owns the server socket.

However, there is another option which is telling the client to close its socket. Sending a RST TCP packet to the port the client is connecting on will cause the client to drop their connection. You can do that with RST scanning using nmap.

http://nmap.org/

When to use "new" and when not to, in C++?

You should use new when you wish an object to remain in existence until you delete it. If you do not use new then the object will be destroyed when it goes out of scope. Some examples of this are:

void foo()
{
  Point p = Point(0,0);
} // p is now destroyed.

for (...)
{
  Point p = Point(0,0);
} // p is destroyed after each loop

Some people will say that the use of new decides whether your object is on the heap or the stack, but that is only true of variables declared within functions.

In the example below the location of 'p' will be where its containing object, Foo, is allocated. I prefer to call this 'in-place' allocation.

class Foo
{

  Point p;
}; // p will be automatically destroyed when foo is.

Allocating (and freeing) objects with the use of new is far more expensive than if they are allocated in-place so its use should be restricted to where necessary.

A second example of when to allocate via new is for arrays. You cannot* change the size of an in-place or stack array at run-time so where you need an array of undetermined size it must be allocated via new.

E.g.

void foo(int size)
{
   Point* pointArray = new Point[size];
   ...
   delete [] pointArray;
}

(*pre-emptive nitpicking - yes, there are extensions that allow variable sized stack allocations).

Begin, Rescue and Ensure in Ruby?

Yes, ensure ENSURES it is run every time, so you don't need the file.close in the begin block.

By the way, a good way to test is to do:

begin
  # Raise an error here
  raise "Error!!"
rescue
  #handle the error here
ensure
  p "=========inside ensure block"
end

You can test to see if "=========inside ensure block" will be printed out when there is an exception. Then you can comment out the statement that raises the error and see if the ensure statement is executed by seeing if anything gets printed out.

How can I ask the Selenium-WebDriver to wait for few seconds in Java?

I prefer the following code to wait for 2 seconds.

for(int i=0; i<2 && driver.findElements(By.id("textbox")).size()==0 ; i++){
   Thread.sleep(1000);
}

PHP Echo a large block of text

I prefer to concatenate multiple Strings together. This works either for echo AND for variables. Also some IDEs auto-initialize new lines if you hit enter. This Syntax also generate small output because there are much less whitespaces in the strings.

echo ''
    .'one {'
    .'    color: red;'
    .'}'
    ;

$foo = ''
    .'<h1>' . $bar . '</h1>'  // insert value of bar
    .$bar                     // insert value of bar again
    ."<p>$bar</p>"            // and again
    ."<p>You can also use Double-Quoted \t Strings for single lines. \n To use Escape Sequences.</p>"
    // also you can insert comments in middle, which aren't in the string.
    .'<p>Or to insert Escape Sequences in middle '."\n".' of a string</p>'
    ;

Normally i start with an empty string and then append bit by bit to it:

$foo = '';

$foo .= 'function sayHello()'
    .'    alert( "Hello" );'
    ."}\n";

$foo .= 'function sum( a , b )'
    .'{'
    .'    return a + b ;'
    ."}\n";

(Please stop Posts like "uh. You answer to an five jears old Question." Why not? There are much people searching for an answer. And what's wrong to use five year old ideas? If they don't find "their" solution they would open a new Question. Then the first five answers are only "use the search function before you ask!" So. I give you another solution to solve problems like this.)

Can I pass an array as arguments to a method with variable arguments in Java?

It's ok to pass an array - in fact it amounts to the same thing

String.format("%s %s", "hello", "world!");

is the same as

String.format("%s %s", new Object[] { "hello", "world!"});

It's just syntactic sugar - the compiler converts the first one into the second, since the underlying method is expecting an array for the vararg parameter.

See

Each for object?

for(var key in object) {
   console.log(object[key]);
}

jquery $(this).id return Undefined

Another option (just so you've seen it):

$(function () {
    $(".inputs").click(function (e) {
         alert(e.target.id);
    });
});

HTH.

How do you make a HTTP request with C++?

With this answer I refer to the answer from Software_Developer. By rebuilding the code I found that some parts are deprecated (gethostbyname()) or do not provide error handling (creation of sockets, sending something) for an operation.

The following windows code is tested with Visual Studio 2013 and Windows 8.1 64-bit as well as Windows 7 64-bit. It will target an IPv4 TCP Connection with the Web Server of www.google.com.

#include <winsock2.h>
#include <WS2tcpip.h>
#include <windows.h>
#include <iostream>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
    int main (){
    // Initialize Dependencies to the Windows Socket.
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
        cout << "WSAStartup failed.\n";
        system("pause");
        return -1;
    }

    // We first prepare some "hints" for the "getaddrinfo" function
    // to tell it, that we are looking for a IPv4 TCP Connection.
    struct addrinfo hints;
    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;          // We are targeting IPv4
    hints.ai_protocol = IPPROTO_TCP;    // We are targeting TCP
    hints.ai_socktype = SOCK_STREAM;    // We are targeting TCP so its SOCK_STREAM

    // Aquiring of the IPv4 address of a host using the newer
    // "getaddrinfo" function which outdated "gethostbyname".
    // It will search for IPv4 addresses using the TCP-Protocol.
    struct addrinfo* targetAdressInfo = NULL;
    DWORD getAddrRes = getaddrinfo("www.google.com", NULL, &hints, &targetAdressInfo);
    if (getAddrRes != 0 || targetAdressInfo == NULL)
    {
        cout << "Could not resolve the Host Name" << endl;
        system("pause");
        WSACleanup();
        return -1;
    }

    // Create the Socket Address Informations, using IPv4
    // We dont have to take care of sin_zero, it is only used to extend the length of SOCKADDR_IN to the size of SOCKADDR
    SOCKADDR_IN sockAddr;
    sockAddr.sin_addr = ((struct sockaddr_in*) targetAdressInfo->ai_addr)->sin_addr;    // The IPv4 Address from the Address Resolution Result
    sockAddr.sin_family = AF_INET;  // IPv4
    sockAddr.sin_port = htons(80);  // HTTP Port: 80

    // We have to free the Address-Information from getaddrinfo again
    freeaddrinfo(targetAdressInfo);

    // Creation of a socket for the communication with the Web Server,
    // using IPv4 and the TCP-Protocol
    SOCKET webSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (webSocket == INVALID_SOCKET)
    {
        cout << "Creation of the Socket Failed" << endl;
        system("pause");
        WSACleanup();
        return -1;
    }

    // Establishing a connection to the web Socket
    cout << "Connecting...\n";
    if(connect(webSocket, (SOCKADDR*)&sockAddr, sizeof(sockAddr)) != 0)
    {
        cout << "Could not connect";
        system("pause");
        closesocket(webSocket);
        WSACleanup();
        return -1;
    }
    cout << "Connected.\n";

    // Sending a HTTP-GET-Request to the Web Server
    const char* httpRequest = "GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n";
    int sentBytes = send(webSocket, httpRequest, strlen(httpRequest),0);
    if (sentBytes < strlen(httpRequest) || sentBytes == SOCKET_ERROR)
    {
        cout << "Could not send the request to the Server" << endl;
        system("pause");
        closesocket(webSocket);
        WSACleanup();
        return -1;
    }

    // Receiving and Displaying an answer from the Web Server
    char buffer[10000];
    ZeroMemory(buffer, sizeof(buffer));
    int dataLen;
    while ((dataLen = recv(webSocket, buffer, sizeof(buffer), 0) > 0))
    {
        int i = 0;
        while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
            cout << buffer[i];
            i += 1;
        }
    }

    // Cleaning up Windows Socket Dependencies
    closesocket(webSocket);
    WSACleanup();

    system("pause");
    return 0;
}

References:

Deprecation of gethostbyname

Return Value of socket()

Return Value of send()

How to scp in Python?

Have a look at fabric.transfer.

from fabric import Connection

with Connection(host="hostname", 
                user="admin", 
                connect_kwargs={"key_filename": "/home/myuser/.ssh/private.key"}
               ) as c:
    c.get('/foo/bar/file.txt', '/tmp/')

Python TypeError: cannot convert the series to <class 'int'> when trying to do math on dataframe

What if you do this (as was suggested earlier):

new_time = dfs['XYF']['TimeUS'].astype(float)
new_time_F = new_time / 1000000

How do I mock a static method that returns void with PowerMock?

To mock a static method that return void for e.g. Fileutils.forceMKdir(File file),

Sample code:

File file =PowerMockito.mock(File.class);
PowerMockito.doNothing().when(FileUtils.class,"forceMkdir",file);

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

I'll give a slightly advanced answer. In Python, functions are first-class objects. This means they can be "dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have."

Calling a function/class instance in Python means invoking the __call__ method of that object. For old-style classes, class instances are also callable but only if the object which creates them has a __call__ method. The same applies for new-style classes, except there is no notion of "instance" with new-style classes. Rather they are "types" and "objects".

As quoted from the Python 2 Data Model page, for function objects, class instances(old style classes), and class objects(new-style classes), "x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...)".

Thus whenever you define a function with the shorthand def funcname(parameters): you are really just creating an object with a method __call__ and the shorthand for __call__ is to just name the instance and follow it with parentheses containing the arguments to the call. Because functions are first class objects in Python, they can be created on the fly with dynamic parameters (and thus accept dynamic arguments). This comes into handy with decorator functions/classes which you will read about later.

For now I suggest reading the Official Python Tutorial.

bool to int conversion

Section 6.5.8.6 of the C standard says:

Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.) The result has type int.

jQuery AJAX Character Encoding

I came by this question with exactly the same issue as the asker. The answers here are very informing, and I tried out almost every single one of the suggested answers. None of the answers here worked for me though - there might have been a slight difference in my problem. And that seems to be the case for many. I tried so much before ending up with an answer.

So now I'm adding to the already long list of answers, a solution of my own that solved my kind of encoding problem.

I did just two things. In the database connection script I added:

mysql_set_charset('utf8',$connection);

and apart from that:

  • I changed the encoding of all the files to UTF-8

The point is that everything must be of the same encoding. And when creating new php-files, for the scripts it is not enough just to change the encoding in the script - the file itself must be correctly encoded.

Bash syntax error: unexpected end of file

FOR WINDOWS:

In my case, I was working on Windows OS and I got the same error while running autoconf.

  • I simply open configure.ac file with my NOTEPAD++ IDE.
  • Then I converted the File with EOL conversion into Windows (CR LF) as follows:

    EDIT -> EOL CONVERSION -> WINDOWS (CR LF)

Error including image in Latex

On a Mac (pdftex) I managed to include a png file simply with \includegraphics[width=1.2\textwidth]{filename.png}. But in order for that to work I had to comment out the following 2 packages:

%\usepackage[dvips]{epsfig}

%\usepackage[dvips]{graphicx}

...and simply use package graphicx:

\usepackage{graphicx}

It seems [dvips] is problematic when used with pdftex.

Renaming the current file in Vim

Short, secure, without plugin:

:sav new_name
:!rm <C-R>#  // or !del <C-R># for windows

control + R, # will instantly expand to an alternate-file (previously edited path in current window) before pressing Enter. That allows us to review what exactly we're going to delete. Using pipe | in such a case is not secure, because if sav fails for any reason, # will still point to another place (or to nothing). That means !rm # or delete(expand(#)) may delete completely different file! So do it by hand carefully or use good script (they are mentioned in many answers here).

Educational

...or try build a function/command/script yourself. Start from sth simple like:

command! -nargs=1 Rename saveas <args> | call delete(expand('#')) | bd #

after vimrc reload, just type :Rename new_filename. What is the problem with this command?

Security test 1: What does:Rename without argument?

Yes, it deletes file hidden in '#' !

Solution: you can use eg. conditions or try statement like that:

command! -nargs=1 Rename try | saveas <args> | call delete(expand('#')) | bd # | endtry

Security test 1: :Rename (without argument) will throw an error:

E471: Argument required

Security test 2: What if the name will be the same like previous one?

Security test 3: What if the file will be in different location than your actual?

Fix it yourself. For readability you can write it in this manner:

function! s:localscript_name(name):
  try
    execute 'saveas ' . a:name
    ...
  endtry
endfunction
command! -nargs=1 Rename call s:localscript_name(<f-args>)

notes

  • !rm # is better than !rm old_name -> you don't need remember the old name

  • !rm <C-R># is better than !rm # when do it by hand -> you will see what you actually remove (safety reason)

  • !rm is generally not very secure... mv to a trash location is better

  • call delete(expand('#')) is better than shell command (OS agnostic) but longer to type and impossible to use control + R

  • try | code1 | code2 | tryend -> when error occurs while code1, don't run code2

  • :sav (or :saveas) is equivalent to :f new_name | w - see file_f - and preserves undo history

  • expand('%:p') gives whole path of your location (%) or location of alternate file (#)

How to know Laravel version and where is it defined?

Yet another way is to read the composer.json file, but it can end with wildcard character *

Runtime vs. Compile time

The difference between compile time and run time is an example of what pointy-headed theorists call the phase distinction. It is one of the hardest concepts to learn, especially for people without much background in programming languages. To approach this problem, I find it helpful to ask

  1. What invariants does the program satisfy?
  2. What can go wrong in this phase?
  3. If the phase succeeds, what are the postconditions (what do we know)?
  4. What are the inputs and outputs, if any?

Compile time

  1. The program need not satisfy any invariants. In fact, it needn't be a well-formed program at all. You could feed this HTML to the compiler and watch it barf...
  2. What can go wrong at compile time:
    • Syntax errors
    • Typechecking errors
    • (Rarely) compiler crashes
  3. If the compiler succeeds, what do we know?
    • The program was well formed---a meaningful program in whatever language.
    • It's possible to start running the program. (The program might fail immediately, but at least we can try.)
  4. What are the inputs and outputs?
    • Input was the program being compiled, plus any header files, interfaces, libraries, or other voodoo that it needed to import in order to get compiled.
    • Output is hopefully assembly code or relocatable object code or even an executable program. Or if something goes wrong, output is a bunch of error messages.

Run time

  1. We know nothing about the program's invariants---they are whatever the programmer put in. Run-time invariants are rarely enforced by the compiler alone; it needs help from the programmer.
  2. What can go wrong are run-time errors:

    • Division by zero
    • Dereferencing a null pointer
    • Running out of memory

    Also there can be errors that are detected by the program itself:

    • Trying to open a file that isn't there
    • Trying find a web page and discovering that an alleged URL is not well formed
  3. If run-time succeeds, the program finishes (or keeps going) without crashing.
  4. Inputs and outputs are entirely up to the programmer. Files, windows on the screen, network packets, jobs sent to the printer, you name it. If the program launches missiles, that's an output, and it happens only at run time :-)

What tools do you use to test your public REST API?

We're planning to use FitNesse, with the RestFixture. We haven't started writing our tests yet, our newest tester got things up and running last week, however he has used FitNesse for this in his last company, so we know it's a reasonable setup for what we want to do.

More info available here: http://smartrics.blogspot.com/2008/08/get-fitnesse-with-some-rest.html

How to delete items from a dictionary while iterating over it?

You can't modify a collection while iterating it. That way lies madness - most notably, if you were allowed to delete and deleted the current item, the iterator would have to move on (+1) and the next call to next would take you beyond that (+2), so you'd end up skipping one element (the one right behind the one you deleted). You have two options:

  • Copy all keys (or values, or both, depending on what you need), then iterate over those. You can use .keys() et al for this (in Python 3, pass the resulting iterator to list). Could be highly wasteful space-wise though.
  • Iterate over mydict as usual, saving the keys to delete in a seperate collection to_delete. When you're done iterating mydict, delete all items in to_delete from mydict. Saves some (depending on how many keys are deleted and how many stay) space over the first approach, but also requires a few more lines.

Get User Selected Range

Selection is its own object within VBA. It functions much like a Range object.

Selection and Range do not share all the same properties and methods, though, so for ease of use it might make sense just to create a range and set it equal to the Selection, then you can deal with it programmatically like any other range.

Dim myRange as Range
Set myRange = Selection

For further reading, check out the MSDN article.

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

Please try with below code

var s = "15 Feb 2015 11.30 a.m";
        var times = s.match("((([0-9])|([0-2][0-9])).([0-9][0-9])[\t ]?((a.m|p.m)|(A.M|P.M)))");            
        var time = "";

        if(times != null){                          
            var hour = times[2];
            if((times[6] == "p.m" || times[6] == "P.M")){
                if(hour < 12){
                    hour = parseInt(hour) + parseInt(12);
                }else if(hour == 12){
                    hour = "00";
                }
            }
            time = [hour, times[5], "00"].join(":");

        }

Thanks

Jquery .on('scroll') not firing the event while scrolling

I know that this is quite old thing, but I solved issue like that: I had parent and child element was scrollable.

   if ($('#parent > *').length == 0 ){
        var wait = setInterval(function() {
            if($('#parent > *').length != 0 ) {
                $('#parent .child').bind('scroll',function() {
                  //do staff
                });
                clearInterval(wait);
            },1000);
        }

The issue I had is that I didn't know when the child is loaded to DOM, but I kept checking for it every second.

NOTE:this is useful if it happens soon but not right after document load, otherwise it will use clients computing power for no reason.

How does origin/HEAD get set?

Run the following commands from git CLI:

# move to the wanted commit
git reset --hard <commit-hash> 

# update remote
git push --force origin <branch-name> 

How do I get values from a SQL database into textboxes using C#?

using (SqlConnection connection =  new SqlConnection("Data Source=localhost;Initial Catalog=LoginScreen;Integrated Security=True"))
{
    SqlCommand command =
    new SqlCommand("select * from Pending_Tasks WHERE CustomerId=...", connection);
    connection.Open();

    SqlDataReader read= command.ExecuteReader();

    while (read.Read())
    {
        CustID.Text = (read["Customer_ID"].ToString());
        CustName.Text = (read["Customer_Name"].ToString());
        Add1.Text = (read["Address_1"].ToString());
        Add2.Text = (read["Address_2"].ToString());
        PostBox.Text = (read["Postcode"].ToString());
        PassBox.Text = (read["Password"].ToString());
        DatBox.Text = (read["Data_Important"].ToString());
        LanNumb.Text = (read["Landline"].ToString());
        MobNumber.Text = (read["Mobile"].ToString());
        FaultRep.Text = (read["Fault_Report"].ToString());
    }
    read.Close();
}

Make sure you have data in the query : select * from Pending_Tasks and you are using "using System.Data.SqlClient;"

Why is processing a sorted array faster than processing an unsorted array?

Branch prediction.

With a sorted array, the condition data[c] >= 128 is first false for a streak of values, then becomes true for all later values. That's easy to predict. With an unsorted array, you pay for the branching cost.

How to use ? : if statements with Razor and inline code blocks

In most cases the solution of CD.. will work perfectly fine. However I had a bit more twisted situation:

 @(String.IsNullOrEmpty(Model.MaidenName) ? "&nbsp;" : Model.MaidenName)

This would print me "&nbsp;" in my page, respectively generate the source &amp;nbsp;. Now there is a function Html.Raw("&nbsp;") which is supposed to let you write source code, except in this constellation it throws a compiler error:

Compiler Error Message: CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Web.IHtmlString' and 'string'

So I ended up writing a statement like the following, which is less nice but works even in my case:

@if (String.IsNullOrEmpty(Model.MaidenName)) { @Html.Raw("&nbsp;") } else { @Model.MaidenName } 

Note: interesting thing is, once you are inside the curly brace, you have to restart a Razor block.

Print to the same line and not a new line?

This works for me, hacked it once to see if it is possible, but never actually used in my program (GUI is so much nicer):

import time
f = '%4i %%'
len_to_clear = len(f)+1
clear = '\x08'* len_to_clear
print 'Progress in percent:'+' '*(len_to_clear),
for i in range(123):
    print clear+f % (i*100//123),
    time.sleep(0.4)
raw_input('\nDone')

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

I don't use the same version, but uninstall actions are the same: Looking for file uninstall-postgresql inside directory

/Library/PostgreSQL/9.6

enter image description here

then run it.

enter image description here

(Screenshot in macOS 10.13)

then

sudo rm -rf /Library/PostgreSQL/

to delete all unnecessary directory.

ADB No Devices Found

On my Windows 8.1 64bit (Nexus 5 did not show up), only manually installing the USB driver fixed it: http://developer.android.com/sdk/win-usb.html The "Google USB Driver" in "Android SDK Manager" was installed already.

AngularJS ui-router login authentication

I think you need a service that handle the authentication process (and its storage).

In this service you'll need some basic methods :

  • isAuthenticated()
  • login()
  • logout()
  • etc ...

This service should be injected in your controllers of each module :

  • In your dashboard section, use this service to check if user is authenticated (service.isAuthenticated() method) . if not, redirect to /login
  • In your login section, just use the form data to authenticate the user through your service.login() method

A good and robust example for this behavior is the project angular-app and specifically its security module which is based over the awesome HTTP Auth Interceptor Module

Hope this helps

How to insert array of data into mysql using php

I've a PHP library which helps to insert array into MySQL Database. By using this you can create update and delete. Your array key value should be same as the table column value. Just using a single line code for the create operation

DB::create($db, 'YOUR_TABLE_NAME', $dataArray);

where $db is your Database connection.

Similarly, You can use this for update and delete. Select operation will be available soon. Github link to download : https://github.com/pairavanvvl/crud

Java variable number or arguments for a method

Yes Java allows vargs in method parameter .

public class  Varargs
{
   public int add(int... numbers)
   { 
      int result = 1; 
      for(int number: numbers)
      {
         result= result+number;  
      }  return result; 
   }
}

How to convert a private key to an RSA private key?

Newer versions of OpenSSL say BEGIN PRIVATE KEY because they contain the private key + an OID that identifies the key type (this is known as PKCS8 format). To get the old style key (known as either PKCS1 or traditional OpenSSL format) you can do this:

openssl rsa -in server.key -out server_new.key

Alternately, if you have a PKCS1 key and want PKCS8:

openssl pkcs8 -topk8 -nocrypt -in privkey.pem

Save matplotlib file to a directory

If the directory you wish to save to is a sub-directory of your working directory, simply specify the relative path before your file name:

    fig.savefig('Sub Directory/graph.png')

If you wish to use an absolute path, import the os module:

    import os
    my_path = os.path.abspath(__file__) # Figures out the absolute path for you in case your working directory moves around.
    ...
    fig.savefig(my_path + '/Sub Directory/graph.png')

If you don't want to worry about the leading slash in front of the sub-directory name, you can join paths intelligently as follows:

    import os
    my_path = os.path.abspath(__file__) # Figures out the absolute path for you in case your working directory moves around.
    my_file = 'graph.png'
    ...
    fig.savefig(os.path.join(my_path, my_file))        

How generate unique Integers based on GUIDs

Here is the simplest way:

Guid guid = Guid.NewGuid();
Random random = new Random();
int i = random.Next();

You'll notice that guid is not actually used here, mainly because there would be no point in using it. Microsoft's GUID algorithm does not use the computer's MAC address any more - GUID's are actually generated using a pseudo-random generator (based on time values), so if you want a random integer it makes more sense to use the Random class for this.

Update: actually, using a GUID to generate an int would probably be worse than just using Random ("worse" in the sense that this would be more likely to generate collisions). This is because not all 128 bits in a GUID are random. Ideally, you would want to exclude the non-varying bits from a hashing function, although it would be a lot easier to just generate a random number, as I think I mentioned before. :)

Phone: numeric keyboard for text input

I have found that, at least for "passcode"-like fields, doing something like <input type="tel" /> ends up producing the most authentic number-oriented field and it also has the benefit of no autoformatting. For example, in a mobile application I developed for Hilton recently, I ended up going with this:

iPhone Web Application Display with an Input Tag Having a Type of TEL which Produces a very Decent Numeric Keyboard as Opposed to Type Number which is Autoformatted and Has a Somewhat Less Intuitive Input Configuration

... and my client was very impressed.

_x000D_
_x000D_
<form>_x000D_
  <input type="tel" />_x000D_
  <button type="submit">Submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Deleting specific rows from DataTable

DataRow[] dtr=dtPerson.select("name=Joe");
foreach(var drow in dtr)
{
   drow.delete();
}
dtperson.AcceptChanges();

I hope it will help you

How to change the plot line color from blue to black?

If you get the object after creation (for instance after "seasonal_decompose"), you can always access and edit the properties of the plot; for instance, changing the color of the first subplot from blue to black:

plt.axes[0].get_lines()[0].set_color('black')

What is the difference between JVM, JDK, JRE & OpenJDK?

JVM : virtual machine of java. tells machine what to do with the Java Code. You cannot download JVM as is. It comes packaged in some other component.

JRE: Some other component referred as above is the JRE. It is JVM+ other jars to create runtime environmeny

JDK: contains JRE(which in turn contains JVM). Once you get JDK you need not install JRE and JVM separately. It contains compiler which compiles your .java files to .class files

How to convert char to int?

What everyone is forgeting is explaining WHY this happens.

A Char, is basically an integer, but with a pointer in the ASCII table. All characters have a corresponding integer value as you can clearly see when trying to parse it.

Pranay has clearly a different character set, thats why HIS code doesnt work. the only way is

int val = '1' - '0';

because this looks up the integer value in the table of '0' which is then the 'base value' subtracting your number in char format from this will give you the original number.

How to modify JsonNode in Java?

The @Sharon-Ben-Asher answer is ok.

But in my case, for an array i have to use:

((ArrayNode) jsonNode).add("value");

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

How to delete multiple files at once in Bash on Linux?

Use a wildcard (*) to match multiple files.

For example, the command below will delete all files with names beginning with abc.log.2012-03-.

rm -f abc.log.2012-03-*

I'd recommend running ls abc.log.2012-03-* to list the files so that you can see what you are going to delete before running the rm command.

For more details see the Bash man page on filename expansion.

How to make a Java thread wait for another thread's output?

You could read from a blocking queue in one thread and write to it in another thread.

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

One of the most common errors that I found developing Android Apps is the “java.lang.OutOfMemoryError: Bitmap Size Exceeds VM Budget” error. I found this error frequently on activities using lots of bitmaps after changing orientation: the Activity is destroyed, created again and the layouts are “inflated” from the XML consuming the VM memory available for bitmaps.

Bitmaps on the previous activity layout are not properly de-allocated by the garbage collector because they have crossed references to their activity. After many experiments I found a quite good solution for this problem.

First, set the “id” attribute on the parent view of your XML layout:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:id="@+id/RootView"
     >
     ...

Then, on the onDestroy() method of your Activity, call the unbindDrawables() method passing a reference to the parent View and then do a System.gc().

    @Override
    protected void onDestroy() {
    super.onDestroy();

    unbindDrawables(findViewById(R.id.RootView));
    System.gc();
    }

    private void unbindDrawables(View view) {
        if (view.getBackground() != null) {
        view.getBackground().setCallback(null);
        }
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
            unbindDrawables(((ViewGroup) view).getChildAt(i));
            }
        ((ViewGroup) view).removeAllViews();
        }
    }

This unbindDrawables() method explores the view tree recursively and:

  1. Removes callbacks on all the background drawables
  2. Removes children on every viewgroup

Difference between \n and \r?

Two different characters.

\n is used as an end-of-line terminator in Unix text files

\r Was historically (pre-OS X) used as an end-of-line terminator in Mac text files

\r\n (ie both) are used to terminate lines in Windows and DOS text files.

Error in Swift class: Property not initialized at super.init call

Add nil to the end of the declaration.


// Must be nil or swift complains
var someProtocol:SomeProtocol? = nil

// Init the view
override init(frame: CGRect)
    super.init(frame: frame)
    ...

This worked for my case, but may not work for yours

Counting Chars in EditText Changed Listener

This is a slightly more general answer with more explanation for future viewers.

Add a text changed listener

If you want to find the text length or do something else after the text has been changed, you can add a text changed listener to your edit text.

EditText editText = (EditText) findViewById(R.id.testEditText);
editText.addTextChangedListener(new TextWatcher() {

    @Override
    public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int start, int before, int count)  {

    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
});

The listener needs a TextWatcher, which requires three methods to be overridden: beforeTextChanged, onTextChanged, and afterTextChanged.

Counting the characters

You can get the character count in onTextChanged or beforeTextChanged with

charSequence.length()

or in afterTextChanged with

editable.length()

Meaning of the methods

The parameters are a little confusing so here is a little extra explanation.

beforeTextChanged

beforeTextChanged(CharSequence charSequence, int start, int count, int after)

  • charSequence: This is the text content before the pending change is made. You should not try to change it.
  • start: This is the index of where the new text will be inserted. If a range is selected, then it is the beginning index of the range.
  • count: This is the length of selected text that is going to be replaced. If nothing is selected then count will be 0.
  • after: this is the length of the text to be inserted.

onTextChanged

onTextChanged(CharSequence charSequence, int start, int before, int count)

  • charSequence: This is the text content after the change was made. You should not try to modify this value here. Modify the editable in afterTextChanged if you need to.
  • start: This is the index of the start of where the new text was inserted.
  • before: This is the old value. It is the length of previously selected text that was replaced. This is the same value as count in beforeTextChanged.
  • count: This is the length of text that was inserted. This is the same value as after in beforeTextChanged.

afterTextChanged

afterTextChanged(Editable editable)

Like onTextChanged, this is called after the change has already been made. However, now the text may be modified.

  • editable: This is the editable text of the EditText. If you change it, though, you have to be careful not to get into an infinite loop. See the documentation for more details.

Supplemental image from this answer

enter image description here

Handling warning for possible multiple enumeration of IEnumerable

First off, that warning does not always mean so much. I usually disabled it after making sure it's not a performance bottle neck. It just means the IEnumerable is evaluated twice, wich is usually not a problem unless the evaluation itself takes a long time. Even if it does take a long time, in this case your only using one element the first time around.

In this scenario you could also exploit the powerful linq extension methods even more.

var firstObject = objects.First();
return DoSomeThing(firstObject).Concat(DoSomeThingElse(objects).ToList();

It is possible to only evaluate the IEnumerable once in this case with some hassle, but profile first and see if it's really a problem.

Styling input buttons for iPad and iPhone

You may be looking for

-webkit-appearance: none;

Jersey Exception : SEVERE: A message body reader for Java class

If you are building an uberjar or "shaded jar", make sure your meta inf service files are merged. (This bit me multiple times on a dropwizard project.)

If you are using the gradle shadowJar plugin, you want to call mergeServiceFiles() in your shadowJar target: https://github.com/johnrengelman/shadow#merging-service-files

Not sure what the analogous commands are for maven or other build systems.

Git submodule head 'reference is not a tree' error

Your branch may not be up to date, a simple solution but try git fetch

How to get a value from the last inserted row?

If you are using Statement, go for the following

//MY_NUMBER is the column name in the database 
String generatedColumns[] = {"MY_NUMBER"};
Statement stmt = conn.createStatement();

//String sql holds the insert query
stmt.executeUpdate(sql, generatedColumns);

ResultSet rs = stmt.getGeneratedKeys();

// The generated id

if(rs.next())
long key = rs.getLong(1);

If you are using PreparedStatement, go for the following

String generatedColumns[] = {"MY_NUMBER"};
PreparedStatement pstmt = conn.prepareStatement(sql,generatedColumns);
pstmt.setString(1, "qwerty");

pstmt.execute();
ResultSet rs = pstmt.getGeneratedKeys();
if(rs.next())
long key = rs.getLong(1);

CSS3 animate border color

If you need the transition to run infinitely, try the below example:

_x000D_
_x000D_
#box {_x000D_
  position: relative;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background-color: gray;_x000D_
  border: 5px solid black;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
#box:hover {_x000D_
  border-color: red;_x000D_
  animation-name: flash_border;_x000D_
  animation-duration: 2s;_x000D_
  animation-timing-function: linear;_x000D_
  animation-iteration-count: infinite;_x000D_
  -webkit-animation-name: flash_border;_x000D_
  -webkit-animation-duration: 2s;_x000D_
  -webkit-animation-timing-function: linear;_x000D_
  -webkit-animation-iteration-count: infinite;_x000D_
  -moz-animation-name: flash_border;_x000D_
  -moz-animation-duration: 2s;_x000D_
  -moz-animation-timing-function: linear;_x000D_
  -moz-animation-iteration-count: infinite;_x000D_
}_x000D_
_x000D_
@keyframes flash_border {_x000D_
  0% {_x000D_
    border-color: red;_x000D_
  }_x000D_
  50% {_x000D_
    border-color: black;_x000D_
  }_x000D_
  100% {_x000D_
    border-color: red;_x000D_
  }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes flash_border {_x000D_
  0% {_x000D_
    border-color: red;_x000D_
  }_x000D_
  50% {_x000D_
    border-color: black;_x000D_
  }_x000D_
  100% {_x000D_
    border-color: red;_x000D_
  }_x000D_
}_x000D_
_x000D_
@-moz-keyframes flash_border {_x000D_
  0% {_x000D_
    border-color: red;_x000D_
  }_x000D_
  50% {_x000D_
    border-color: black;_x000D_
  }_x000D_
  100% {_x000D_
    border-color: red;_x000D_
  }_x000D_
}
_x000D_
<div id="box">roll over me</div>
_x000D_
_x000D_
_x000D_

JavaScript single line 'if' statement - best syntax, this alternative?

Example in arrow functions:

let somethingTrue = true
[1,2,3,4,5].map(i=>somethingTrue && i*2)

In promises:

Promise.resolve()
  .then(_=>checkTrueFalse && asyncFunc())
  .then(_=>{ .. })

Otherwise:

if(somethingTrue) thenDo()

If it's just a simple conditional, I prefer using if(value) whenever possible because the word if in the beginning of the statement says more about what's happening than paranthesis and questionmarks.

facebook: permanent Page Access Token?

In addition to mentioned methods it is worth mentioning that for server-to-server applications, you can also use this form of permanent access token: app_id|app_secret This type of access token is called App Token. It can generally be used to call Graph API and query for public nodes within your application back-end. It is mentioned here: https://developers.facebook.com/docs/facebook-login/access-tokens

How to upload and parse a CSV file in php

This can be done in a much simpler manner now.

$tmpName = $_FILES['csv']['tmp_name'];
$csvAsArray = array_map('str_getcsv', file($tmpName));

This will return you a parsed array of your CSV data. Then you can just loop through it using a foreach statement.

Move seaborn plot legend to a different position?

it seems you can directly call:

g = sns.factorplot("class", "survived", "sex",
                data=titanic, kind="bar",
                size=6, palette="muted",
               legend_out=False)

g._legend.set_bbox_to_anchor((.7, 1.1))

Why use pointers?

Regarding your second question, generally you don't need to use pointers while programming, however there is one exception to this and that is when you make a public API.

The problem with C++ constructs that people generally use to replace pointers are very dependent on the toolset that you use which is fine when you have all the control you need over the source code, however if you compile a static library with visual studio 2008 for instance and try to use it in a visual studio 2010 you will get a ton of linker errors because the new project is linked with a newer version of STL which is not backwards compatible. Things get even nastier if you compile a DLL and give an import library that people use in a different toolset because in that case your program will crash sooner or later for no apparent reason.

So for the purpose of moving large data sets from one library to another you could consider giving a pointer to an array to the function that is supposed to copy the data if you don't want to force others to use the same tools that you use. The good part about this is that it doesn't even have to be a C-style array, you can use a std::vector and give the pointer by giving the address of the first element &vector[0] for instance, and use the std::vector to manage the array internally.

Another good reason to use pointers in C++ again relates to libraries, consider having a dll that cannot be loaded when your program runs, so if you use an import library then the dependency isn't satisfied and the program crashes. This is the case for instance when you give a public api in a dll alongside your application and you want to access it from other applications. In this case in order to use the API you need to load the dll from its' location (usually it's in a registry key) and then you need to use a function pointer to be able to call functions inside the DLL. Sometimes the people that make the API are nice enough to give you a .h file that contain helper functions to automate this process and give you all the function pointers that you need, but if not you can use LoadLibrary and GetProcAddress on windows and dlopen and dlsym on unix to get them (considering that you know the entire signature of the function).

Matlab: Running an m-file from command-line

Thanks to malat. Your comment helped me. But I want to add my try-catch block, as I found the MExeption method getReport() that returns the whole error message and prints it to the matlab console.

Additionally I printed the filename as this compilation is part of a batch script that calls matlab.

try
    some_code
    ...
catch message
    display(['ERROR in file: ' message.stack.file])
    display(['ERROR: ' getReport(message)])
end;

For a false model name passed to legacy code generation method, the output would look like:

ERROR in file: C:\..\..\..
ERROR: Undefined function or variable 'modelname'.

Error in sub-m-file (line 63)
legacy_code( 'slblock_generate', specs, modelname);

Error in m-file (line 11)
sub-m-file

Error in run (line 63)
evalin('caller', [script ';']);

Finally, to display the output at the windows command prompt window, just log the matlab console to a file with -logfile logfile.txt (use additionally -wait) and call the batch command type logfile.txt

How to use SSH to run a local shell script on a remote machine?

<hostA_shell_prompt>$ ssh user@hostB "ls -la"

That will prompt you for password, unless you have copied your hostA user's public key to the authorized_keys file on the home of user .ssh's directory. That will allow for passwordless authentication (if accepted as an auth method on the ssh server's configuration)

How to center align the ActionBar title in Android?

The other tutorials I've seen override the whole action bar layout hiding the MenuItems. I've got it worked just doing the following steps:

Create a xml file as following:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:ellipsize="end"
        android:maxLines="1"
        android:text="@string/app_name"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@android:color/white" />

</RelativeLayout>

And in the classe do it:

LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.action_bar_title, null);

ActionBar.LayoutParams params = new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER);

TextView titleTV = (TextView) v.findViewById(R.id.title);
titleTV.setText("Test");

Android TextView Justify Text

I think there are two options:

  • Use something like Pango that specializes in this via the NDK and render text to an OpenGL or other surface.

  • Use Paint.measureText() and friends to get the lengths of words and lay them out manually on a Canvas in a custom view.

ValueError: Wrong number of items passed - Meaning and suggestions?

Not sure if this is relevant to your question but it might be relevant to someone else in the future: I had a similar error. Turned out that the df was empty (had zero rows) and that is what was causing the error in my command.

How to replace NaN value with zero in a huge data frame?

It would seem that is.nan doesn't actually have a method for data frames, unlike is.na. So, let's fix that!

is.nan.data.frame <- function(x)
do.call(cbind, lapply(x, is.nan))

data123[is.nan(data123)] <- 0

Checking out Git tag leads to "detached HEAD state"

Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.

But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)

nginx error connect to php5-fpm.sock failed (13: Permission denied)

The problem in my case was that the Nginx web server was running as user nginx and the pool was running as user www-data.

I solved the issue by changing the user Nginx is running at in the /etc/nginx/nginx.conf file (could be different on your system, mine is Ubuntu 16.04.1)

Change: user nginx;

to: user www-data;

then restart Nginx: service nginx restart

Installing Java 7 (Oracle) in Debian via apt-get

Managed to get answer after do some google..

echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer

Multiple condition in single IF statement

Yes it is, there have to be boolean expresion after IF. Here you have a direct link. I hope it helps. GL!

Is there a way to pass optional parameters to a function?

def my_func(mandatory_arg, optional_arg=100):
    print(mandatory_arg, optional_arg)

http://docs.python.org/2/tutorial/controlflow.html#default-argument-values

I find this more readable than using **kwargs.

To determine if an argument was passed at all, I use a custom utility object as the default value:

MISSING = object()

def func(arg=MISSING):
    if arg is MISSING:
        ...

col align right

For The Bootstrap 4+

This Code Worked Well for me

<div class="row">
        <div class="col">
            <div class="ml-auto">
                this content will be in the Right
            </div>
        </div>
        <div class="col mr-auto">
            <div class="mr-auto">
                this content will be in the leftt
            </div>
        </div>
    </div>

Why should Java 8's Optional not be used in arguments

First of all, if you're using method 3, you can replace those last 14 lines of code with this:

int result = myObject.calculateSomething(p1.orElse(null), p2.orElse(null));

The four variations you wrote are convenience methods. You should only use them when they're more convenient. That's also the best approach. That way, the API is very clear which members are necessary and which aren't. If you don't want to write four methods, you can clarify things by how you name your parameters:

public int calculateSomething(String p1OrNull, BigDecimal p2OrNull)

This way, it's clear that null values are allowed.

Your use of p1.orElse(null) illustrates how verbose our code gets when using Optional, which is part of why I avoid it. Optional was written for functional programming. Streams need it. Your methods should probably never return Optional unless it's necessary to use them in functional programming. There are methods, like Optional.flatMap() method, that requires a reference to a function that returns Optional. Here's its signature:

public <U> Optional<U> flatMap(Function<? super T, ? extends Optional<? extends U>> mapper)

So that's usually the only good reason for writing a method that returns Optional. But even there, it can be avoided. You can pass a getter that doesn't return Optional to a method like flatMap(), by wrapping it in a another method that converts the function to the right type. The wrapper method looks like this:

public static <T, U> Function<? super T, Optional<U>> optFun(Function<T, U> function) {
    return t -> Optional.ofNullable(function.apply(t));
}

So suppose you have a getter like this: String getName()

You can't pass it to flatMap like this:

opt.flatMap(Widget::getName) // Won't work!

But you can pass it like this:

opt.flatMap(optFun(Widget::getName)) // Works great!

Outside of functional programming, Optionals should be avoided.

Brian Goetz said it best when he said this:

The reason Optional was added to Java is because this:

return Arrays.asList(enclosingInfo.getEnclosingClass().getDeclaredMethods())
    .stream()
    .filter(m -> Objects.equals(m.getName(), enclosingInfo.getName())
    .filter(m ->  Arrays.equals(m.getParameterTypes(), parameterClasses))
    .filter(m -> Objects.equals(m.getReturnType(), returnType))
    .findFirst()
    .getOrThrow(() -> new InternalError(...));

is cleaner than this:

Method matching =
    Arrays.asList(enclosingInfo.getEnclosingClass().getDeclaredMethods())
    .stream()
    .filter(m -> Objects.equals(m.getName(), enclosingInfo.getName())
    .filter(m ->  Arrays.equals(m.getParameterTypes(), parameterClasses))
    .filter(m -> Objects.equals(m.getReturnType(), returnType))
    .getFirst();
if (matching == null)
  throw new InternalError("Enclosing method not found");
return matching;

How to get back to most recent version in Git?

With Git 2.23+ (August 2019), the best practice would be to use git switch instead of the confusing git checkout command.

To create a new branch based on an older version:

git switch -c temp_branch HEAD~2

To go back to the current master branch:

git switch master

What is a PDB file?

Program Debug Database file (pdb) is a file format by Microsoft for storing debugging information.

When you build a project using Visual Studio or command prompt the compiler creates these symbol files.

Check Microsoft Docs

How to set a session variable when clicking a <a> link

Is your link to another web page? If so, perhaps you could put the variable in the query string and set the session variable when the page being linked to is loaded.

So the link looks like this:

<a href="home.php?variable=value" name="home">home</a>

And the homge page would parse the query string and set the session variable.

How to present popover properly in iOS 8

I made an Objective-C version of Imagine Digitals swift answer above. I don't think I missed anything as it seems to work under preliminary testing, if you spot something let me know, and I'll update it

-(void) presentPopover
{
    YourViewController* popoverContent = [[YourViewController alloc] init]; //this will be a subclass of UIViewController
    UINavigationController* nav =  [[UINavigationController alloc] initWithRootViewController:popoverContent];
    nav.modalPresentationStyle = UIModalPresentationPopover;
    UIPopoverPresentationController* popover = nav.popoverPresentationController;
    popoverContent.preferredContentSize = CGSizeMake(500,600);
    popover.delegate = self;
    popover.sourceRect = CGRectMake(100,100,0,0); //I actually used popover.barButtonItem = self.myBarButton;

    [self presentViewController:nav animated:YES completion:nil];
}

How to work on UAC when installing XAMPP

This is a specific issue for Windows Vista, 7, 8 (and presumably newer).

User Account Control (UAC) is a feature in Windows that can help you stay in control of your computer by informing you when a program makes a change that requires administrator-level permission. UAC works by adjusting the permission level of your user account.

This is applied mostly to C:\Program Files. You may have noticed sometimes, that some applications can see files in C:\Program Files that does not exist there. You know why? Windows now tend to have "C:\Program Files" folder customized for every user. For example, old applications store config files (like .ini) in the same folder where the executable files are stored. In the good old days all users had the same configurations for such apps. In nowadays Windows stores configs in the special folder tied to the user account. Thus, now different users may have different configs while application still think that config files are in the same folder with the executables.

XAMPP does not like to have different config for different users. In fact it is not a config file for XAMPP, it is folders where you keep your projects and databases. The idea of XAMPP is to make projects same for all users. This is a source of a conflict with Windows.

All you need is to avoid installing XAMPP into C:\Program Files. Thus XAMPP will always use the original files for all users and there would be no confusion.

I recommend to install XAMPP into the special folder in root directory like in C:\XAMPP. But before you choose the folder you need to click on this warning message.

How can I add or update a query string parameter?

It's so simple with URLSearchParams, supported in all modern browsers (caniuse).

_x000D_
_x000D_
let p = new URLSearchParams();
p.set("foo", "bar");
p.set("name", "Jack & Jill?");
console.log("http://example.com/?" + p.toString());
_x000D_
_x000D_
_x000D_

If you want to modify the existing URL, construct the object like this: new URLSearchParams(window.location.search) and assign the string to window.location.search.

AngularJS: How to clear query parameters in the URL?

if you process the parameters immediately and then move to the next page, you can put a question mark on the end of the new location.

for example, if you would have done $location.path('/nextPage');

you can do this instead: $location.path('/nextPage?');

Is key-value pair available in Typescript?

You can also consider using Record, like this:

const someArray: Record<string, string>[] = [
    {'first': 'one'},
    {'second': 'two'}
];

Or write something like this:

const someArray: {key: string, value: string}[] = [
    {key: 'first', value: 'one'},
    {key: 'second', value: 'two'}
];

How do you stop tracking a remote branch in Git?

As mentioned in Yoshua Wuyts' answer, using git branch:

git branch --unset-upstream

Other options:

You don't have to delete your local branch.

Simply delete the local branch that is tracking the remote branch:

git branch -d -r origin/<remote branch name>

-r, --remotes tells git to delete the remote-tracking branch (i.e., delete the branch set to track the remote branch). This will not delete the branch on the remote repo!

See "Having a hard time understanding git-fetch"

there's no such concept of local tracking branches, only remote tracking branches.
So origin/master is a remote tracking branch for master in the origin repo

As mentioned in Dobes Vandermeer's answer, you also need to reset the configuration associated to the local branch:

git config --unset branch.<branch>.remote
git config --unset branch.<branch>.merge

Remove the upstream information for <branchname>.
If no branch is specified it defaults to the current branch.

(git 1.8+, Oct. 2012, commit b84869e by Carlos Martín Nieto (carlosmn))

That will make any push/pull completely unaware of origin/<remote branch name>.

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

In my case, I solved this by following these two steps

1. Go to android studio preferences -> other settings -> kotlin compiler -> set Target JVM version = 1.8 
   if it doesn't work then go to the second option.

2. In your module-level build.gradle file add 
   compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }
    tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
        kotlinOptions {
            jvmTarget = "1.8"
        }
    }

Disable nginx cache for JavaScript files

Remember set sendfile off; or cache headers doesn't work. I use this snipped:

location / {

        index index.php index.html index.htm;
        try_files $uri $uri/ =404; #.s. el /index.html para html5Mode de angular

        #.s. kill cache. use in dev
        sendfile off;
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
        proxy_no_cache 1;
        proxy_cache_bypass 1; 
    }

How to check if a file is a valid image file?

Update

I also implemented the following solution in my Python script here on GitHub.

I also verified that damaged files (jpg) frequently are not 'broken' images i.e, a damaged picture file sometimes remains a legit picture file, the original image is lost or altered but you are still able to load it with no errors. But, file truncation cause always errors.

End Update

You can use Python Pillow(PIL) module, with most image formats, to check if a file is a valid and intact image file.

In the case you aim at detecting also broken images, @Nadia Alramli correctly suggests the im.verify() method, but this does not detect all the possible image defects, e.g., im.verify does not detect truncated images (that most viewers often load with a greyed area).

Pillow is able to detect these type of defects too, but you have to apply image manipulation or image decode/recode in or to trigger the check. Finally I suggest to use this code:

try:
  im = Image.load(filename)
  im.verify() #I perform also verify, don't know if he sees other types o defects
  im.close() #reload is necessary in my case
  im = Image.load(filename) 
  im.transpose(PIL.Image.FLIP_LEFT_RIGHT)
  im.close()
except: 
  #manage excetions here

In case of image defects this code will raise an exception. Please consider that im.verify is about 100 times faster than performing the image manipulation (and I think that flip is one of the cheaper transformations). With this code you are going to verify a set of images at about 10 MBytes/sec with standard Pillow or 40 MBytes/sec with Pillow-SIMD module (modern 2.5Ghz x86_64 CPU).

For the other formats psd,xcf,.. you can use Imagemagick wrapper Wand, the code is as follows:

im = wand.image.Image(filename=filename)
temp = im.flip;
im.close()

But, from my experiments Wand does not detect truncated images, I think it loads lacking parts as greyed area without prompting.

I red that Imagemagick has an external command identify that could make the job, but I have not found a way to invoke that function programmatically and I have not tested this route.

I suggest to always perform a preliminary check, check the filesize to not be zero (or very small), is a very cheap idea:

statfile = os.stat(filename)
filesize = statfile.st_size
if filesize == 0:
  #manage here the 'faulty image' case

Detect if string contains any spaces

var inValid = new RegExp('^[_A-z0-9]{1,}$');
var value = "test string";
var k = inValid.test(value);
alert(k);

Attempted to read or write protected memory

Check to make sure you don't have threads within threads. That's what caused this error for me. See this link: Attempted to read or write protected memory. This is often an indication that other memory is corrupt

What characters are allowed in an email address?

Gmail will only allow + sign as special character and in some cases (.) but any other special characters are not allowed at Gmail. RFC's says that you can use special characters but you should avoid sending mail to Gmail with special characters.

Link a photo with the cell in excel

Select both the column you are sorting, and the column that the picture is in (I am assuming the picture is small compared to the cell, i.e. it is "in" the cell). Make sure that the object positioning property is set as "move but don't size with cells". Now if you do a sort, the pictures will move with the list being sorted.

Note - you must include the column with the picture in your range when you sort, and the picture must fit inside the cell.

The following VBA snippet will make sure all pictures in your spreadsheet have their "move and size" property set:

Sub moveAndSize()
Dim s As Shape
For Each s In ActiveSheet.Shapes
  If s.Type = msoPicture Or s.Type = msoLinkedPicture Or s.Type = msoPlaceholder Then
    s.Placement = xlMove
  End If
Next
End Sub

If you want to make sure the picture continues to fit after you move it, you can use xlMoveAndSize instead of xlMove.

Convert JSON string to dict using Python

If you trust the data source, you can use eval to convert your string into a dictionary:

eval(your_json_format_string)

Example:

>>> x = "{'a' : 1, 'b' : True, 'c' : 'C'}"
>>> y = eval(x)

>>> print x
{'a' : 1, 'b' : True, 'c' : 'C'}
>>> print y
{'a': 1, 'c': 'C', 'b': True}

>>> print type(x), type(y)
<type 'str'> <type 'dict'>

>>> print y['a'], type(y['a'])
1 <type 'int'>

>>> print y['a'], type(y['b'])
1 <type 'bool'>

>>> print y['a'], type(y['c'])
1 <type 'str'>

How to implement class constructor in Visual Basic?

Suppose your class is called MyStudent. Here's how you define your class constructor:

Public Class MyStudent
    Public StudentId As Integer

    'Here's the class constructor:
    Public Sub New(newStudentId As Integer)
        StudentId = newStudentId
    End Sub
End Class

Here's how you call it:

Dim student As New MyStudent(studentId)

Of course, your class constructor can contain as many or as few arguments as you need--even none, in which case you leave the parentheses empty. You can also have several constructors for the same class, all with different combinations of arguments. These are known as different "signatures" for your class constructor.

Foreach with JSONArray and JSONObject

Seems like you can't iterate through JSONArray with a for each. You can loop through your JSONArray like this:

for (int i=0; i < arr.length(); i++) {
    arr.getJSONObject(i);
}

Source

How to check if PHP array is associative or sequential?

Modification on the most popular answer.
This takes a little more processing, but is more accurate.

<?php
//$a is a subset of $b
function isSubset($a, $b)
{
    foreach($a =>$v)
        if(array_search($v, $b) === false)
            return false;

    return true;

    //less effecient, clearer implementation. (uses === for comparison)
    //return array_intersect($a, $b) === $a;
}

function isAssoc($arr)
{
    return !isSubset(array_keys($arr), range(0, count($arr) - 1));
}

var_dump(isAssoc(array('a', 'b', 'c'))); // false
var_dump(isAssoc(array(1 => 'a', 0 => 'b', 2 => 'c'))); // false
var_dump(isAssoc(array("0" => 'a', "1" => 'b', "2" => 'c'))); // false 
//(use === in isSubset to get 'true' for above statement)
var_dump(isAssoc(array("a" => 'a', "b" => 'b', "c" => 'c'))); // true
?>

Oracle - How to create a readonly user

you can create user and grant privilege

create user read_only identified by read_only; grant create session,select any table to read_only;

Switch statement: must default be the last case?

The default condition can be anyplace within the switch that a case clause can exist. It is not required to be the last clause. I have seen code that put the default as the first clause. The case 2: gets executed normally, even though the default clause is above it.

As a test, I put the sample code in a function, called test(int value){} and ran:

  printf("0=%d\n", test(0));
  printf("1=%d\n", test(1));
  printf("2=%d\n", test(2));
  printf("3=%d\n", test(3));
  printf("4=%d\n", test(4));

The output is:

0=2
1=1
2=4
3=8
4=10

Where is Java's Array indexOf?

You're probably thinking of the java.util.ArrayList, not the array.

mysql count group by having

SELECT COUNT(*) 
FROM   (SELECT COUNT(*) 
        FROM   movies 
        GROUP  BY id 
        HAVING COUNT(genre) = 4) t

HttpServletRequest to complete URL

You can use filter .

@Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
            HttpServletRequest test1=    (HttpServletRequest) arg0;

         test1.getRequestURL()); it gives  http://localhost:8081/applicationName/menu/index.action
         test1.getRequestURI()); it gives applicationName/menu/index.action
         String pathname = test1.getServletPath()); it gives //menu/index.action


        if(pathname.equals("//menu/index.action")){ 
            arg2.doFilter(arg0, arg1); // call to urs servlet or frameowrk managed controller method


            // in resposne 
           HttpServletResponse httpResp = (HttpServletResponse) arg1;
           RequestDispatcher rd = arg0.getRequestDispatcher("another.jsp");     
           rd.forward(arg0, arg1);





    }

donot forget to put <dispatcher>FORWARD</dispatcher> in filter mapping in web.xml

How to count certain elements in array?

I'm a begin fan of js array's reduce function.

const myArray =[1, 2, 3, 5, 2, 8, 9, 2];
const count = myArray.reduce((count, num) => num === 2 ? count + 1 : count, 0)

In fact if you really want to get fancy you can create a count function on the Array prototype. Then you can reuse it.

Array.prototype.count = function(filterMethod) {
  return this.reduce((count, item) => filterMethod(item)? count + 1 : count, 0);
} 

Then do

const myArray =[1, 2, 3, 5, 2, 8, 9, 2]
const count = myArray.count(x => x==2)

Comparing object properties in c#

Do you override .ToString() on all of your objects that are in the properties? Otherwise, that second comparison could come back with null.

Also, in that second comparison, I'm on the fence about the construct of !( A == B) compared to (A != B), in terms of readability six months/two years from now. The line itself is pretty wide, which is ok if you've got a wide monitor, but might not print out very well. (nitpick)

Are all of your objects always using properties such that this code will work? Could there be some internal, non-propertied data that could be different from one object to another, but all exposed data is the same? I'm thinking of some data which could change over time, like two random number generators that happen to hit the same number at one point, but are going to produce two different sequences of information, or just any data that doesn't get exposed through the property interface.

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

I think you need str.contains, if you need rows where values of column date contains string 07311954:

print df[df['date'].astype(str).str.contains('07311954')]

Or if type of date column is string:

print df[df['date'].str.contains('07311954')]

If you want check last 4 digits for string 1954 in column date:

print df[df['date'].astype(str).str[-4:].str.contains('1954')]

Sample:

print df['date']
0    8152007
1    9262007
2    7311954
3    2252011
4    2012011
5    2012011
6    2222011
7    2282011
Name: date, dtype: int64

print df['date'].astype(str).str[-4:].str.contains('1954')
0    False
1    False
2     True
3    False
4    False
5    False
6    False
7    False
Name: date, dtype: bool

print df[df['date'].astype(str).str[-4:].str.contains('1954')]
     cmte_id trans_typ entity_typ state  employer  occupation     date  \
2  C00119040       24K        CCM    MD       NaN         NaN  7311954   

   amount     fec_id    cand_id  
2    1000  C00140715  H2MD05155  

What is difference between @RequestBody and @RequestParam?

@RequestParam makes Spring to map request parameters from the GET/POST request to your method argument.

GET Request

http://testwebaddress.com/getInformation.do?city=Sydney&country=Australia

public String getCountryFactors(@RequestParam(value = "city") String city, 
                    @RequestParam(value = "country") String country){ }

POST Request

@RequestBody makes Spring to map entire request to a model class and from there you can retrieve or set values from its getter and setter methods. Check below.

http://testwebaddress.com/getInformation.do

You have JSON data as such coming from the front end and hits your controller class

{
   "city": "Sydney",
   "country": "Australia"
}

Java Code - backend (@RequestBody)

public String getCountryFactors(@RequestBody Country countryFacts)
    {
        countryFacts.getCity();
        countryFacts.getCountry();
    }


public class Country {

    private String city;
    private String country;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}

How to check for registry value using VbScript

   function readFromRegistry (strRegistryKey, strDefault )
    Dim WSHShell, value

    On Error Resume Next
    Set WSHShell = CreateObject("WScript.Shell")
    value = WSHShell.RegRead( strRegistryKey )

    if err.number <> 0 then
        readFromRegistry= strDefault
    else
        readFromRegistry=value
    end if

    set WSHShell = nothing
end function

Usage :

str = readfromRegistry("HKEY_LOCAL_MACHINE\SOFTWARE\Adobe\ESD\Install_Dir", "ha")
wscript.echo "returned " & str

Original post

How to retrieve the LoaderException property?

Another Alternative for those who are probing around and/or in interactive mode:

$Error[0].Exception.LoaderExceptions

Note: [0] grabs the most recent Error from the stack

Where to find extensions installed folder for Google Chrome on Mac?

With the new App Launcher YOUR APPS (not chrome extensions) stored in Users/[yourusername]/Applications/Chrome Apps/

How to Apply Mask to Image in OpenCV?

You don't apply a binary mask to an image. You (optionally) use a binary mask in a processing function call to tell the function which pixels of the image you want to process. If I'm completely misinterpreting your question, you should add more detail to clarify.

JQUERY: Uncaught Error: Syntax error, unrecognized expression

If you're using jQuery 2.1.4 or above, try this:

$("#" + this.d);

Or, you can define var before using it. It makes your code simpler.

var d = this.d
$("#" + d);