Programs & Examples On #Vsix

A VSIX package is a .vsix file that contains one or more Visual Studio extensions (VS2010 onwards).

How can I install Visual Studio Code extensions offline?

A small powershell to get needed information for also visual studio extension :

function Get-VSMarketPlaceExtension {
    [CmdLetBinding()]
    Param(
        [Parameter(ValueFromPipeline = $true,Mandatory = $true)]
        [string[]]
        $extensionName
    )
    begin {
        $body=@{
            filters = ,@{
            criteria =,@{
                    filterType=7
                    value = $null
                }
            }
            flags = 1712
        }    
    }
    process {
        foreach($Extension in $extensionName) {
            $response =  try {
                $body.filters[0].criteria[0].value = $Extension
                $Query =  $body|ConvertTo-JSON -Depth 4
                (Invoke-WebRequest -Uri "https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery?api-version=6.0-preview" -ErrorAction Stop -Body $Query -Method Post -ContentType "application/json")
            } catch [System.Net.WebException] { 
                Write-Verbose "An exception was caught: $($_.Exception.Message)"
                $_.Exception.Response 
            }
            $statusCodeInt = [int]$response.StatusCode

            if ($statusCodeInt -ge 400) {
                Write-Warning "Erreur sur l'appel d'API :  $($response.StatusDescription)"
                return
            }
            $ObjResults = ($response.Content | ConvertFrom-Json).results
    
            If ($ObjResults.resultMetadata.metadataItems.count -ne 1) {
                Write-Warning "l'extension '$Extension' n'a pas été trouvée."
                return
            }
    
            $Extension = $ObjResults.extensions
    
            $obj2Download = ($Extension.versions[0].properties | Where-Object key -eq 'Microsoft.VisualStudio.Services.Payload.FileName').value
            [PSCustomObject]@{
                displayName = $Extension.displayName
                extensionId = $Extension.extensionId
                deploymentType = ($obj2Download -split '\.')[-1]
                version = [version]$Extension.versions[0].version
                LastUpdate = [datetime]$Extension.versions[0].lastUpdated
                IsValidated = ($Extension.versions[0].flags -eq "validated")
                extensionName = $Extension.extensionName 
                publisher     = $Extension.publisher.publisherName
                SourceURL = $Extension.versions[0].assetUri +"/" + $obj2Download
                FileName = $obj2Download                     
            }             
        }
    }
}

This use marketplace API to get extension information. Exemple of usage and results :

>Get-VSMarketPlaceExtension "ProBITools.MicrosoftReportProjectsforVisualStudio"


displayName    : Microsoft Reporting Services Projects
extensionId    : 85e42f76-6afa-4a68-afb5-033d1fe08d7b
deploymentType : vsix
version        : 2.6.7
LastUpdate     : 13/05/2020 22:23:45
IsValidated    : True
extensionName  : MicrosoftReportProjectsforVisualStudio
publisher      : ProBITools
SourceURL      : https://probitools.gallery.vsassets.io/_apis/public/gallery/publisher/ProBITools/extension/MicrosoftReportProjectsforVisualStudio/2.6.7/assetbyname/Microsoft.DataTools.ReportingServices.vsix
FileName       : Microsoft.DataTools.ReportingServices.vsix

All flags value are available here

Thanks to m4js7er and Adam Haynes for inspiration

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

This worked for me:

  1. Delete the originally created site.
  2. Recreate the site in IIS
  3. Clean solution
  4. Build solution

Seems like something went south when I originally created the site. I hate solutions that are similar to "Restart your machine, then reinstall windows" without knowing what caused the error. But, this worked for me. Quick and simple. Hope it helps someone else.

Bash script to calculate time elapsed

Either $(()) or $[] will work for computing the result of an arithmetic operation. You're using $() which is simply taking the string and evaluating it as a command. It's a bit of a subtle distinction. Hope this helps.

As tink pointed out in the comments on this answer, $[] is deprecated, and $(()) should be favored.

Why use multiple columns as primary keys (composite primary key)

Another example of compound primary keys are the usage of Association tables. Suppose you have a person table that contains a set of people and a group table that contains a set of groups. Now you want to create a many to many relationship on person and group. Meaning each person can belong to many groups. Here is what the table structure would look like using a compound primary key.

Create Table Person(
PersonID int Not Null,
FirstName varchar(50),
LastName varchar(50),
Constraint PK_Person PRIMARY KEY (PersonID))

Create Table Group (
GroupId int Not Null,
GroupName varchar(50),
Constraint PK_Group PRIMARY KEY (GroupId))

Create Table GroupMember (
GroupId int Not Null,
PersonId int Not Null,
CONSTRAINT FK_GroupMember_Group FOREIGN KEY (GroupId) References Group(GroupId),
CONSTRAINT FK_GroupMember_Person FOREIGN KEY (PersonId) References Person(PersonId),
CONSTRAINT PK_GroupMember PRIMARY KEY (GroupId, PersonID))

How are people unit testing with Entity Framework 6, should you bother?

If you want to unit test code then you need to isolate your code you want to test (in this case your service) from external resources (e.g. databases). You could probably do this with some sort of in-memory EF provider, however a much more common way is to abstract away your EF implementation e.g. with some sort of repository pattern. Without this isolation any tests you write will be integration tests, not unit tests.

As for testing EF code - I write automated integration tests for my repositories that write various rows to the database during their initialization, and then call my repository implementations to make sure that they behave as expected (e.g. making sure that results are filtered correctly, or that they are sorted in the correct order).

These are integration tests not unit tests, as the tests rely on having a database connection present, and that the target database already has the latest up-to-date schema installed.

Getting list of tables, and fields in each, in a database

SELECT * FROM INFORMATION_SCHEMA.COLUMNS

How to merge 2 List<T> and removing duplicate values from it in C#

Union has not good performance : this article describe about compare them with together

var dict = list2.ToDictionary(p => p.Number);
foreach (var person in list1)
{
        dict[person.Number] = person;
}
var merged = dict.Values.ToList();

Lists and LINQ merge: 4820ms
Dictionary merge: 16ms
HashSet and IEqualityComparer: 20ms
LINQ Union and IEqualityComparer: 24ms

How to create empty text file from a batch file?

Techniques I gathered from other answers:

Makes a 0 byte file a very clear, backward-compatible way:

type nul >EmptyFile.txt

idea via: anonymous, Danny Backett, possibly others, myself inspired by JdeBP's work

A 0 byte file another way, it's backward-compatible-looking:

REM. >EmptyFile.txt

idea via: Johannes

A 0 byte file 3rd way backward-compatible-looking, too:

echo. 2>EmptyFile.txt

idea via: TheSmurf

A 0 byte file the systematic way probably available since Windows 2000:

fsutil file createnew EmptyFile.txt 0

idea via: Emm

A 0 bytes file overwriting readonly files

ATTRIB -R filename.ext>NUL
(CD.>filename.ext)2>NUL

idea via: copyitright

A single newline (2 bytes: 0x0D 0x0A in hex notation, alternatively written as \r\n):

echo.>AlmostEmptyFile.txt

Note: no space between echo, . and >.

idea via: How can you echo a newline in batch files?


edit It seems that any invalid command redirected to a file would create an empty file. heh, a feature! compatibility: uknown

TheInvisibleFeature <nul >EmptyFile.txt

A 0 bytes file: invalid command/ with a random name (compatibility: uknown):

%RANDOM%-%TIME:~6,5% <nul >EmptyFile.txt

via: great source for random by Hung Huynh

edit 2 Andriy M points out the probably most amusing/provoking way to achieve this via invalid command

A 0 bytes file: invalid command/ the funky way (compatibility: unknown)

*>EmptyFile.txt

idea via: Andriy M

A 0 bytes file 4th-coming way:

break > file.txt

idea via: foxidrive thanks to comment of Double Gras!

How to capture multiple repeated groups?

The key distinction is repeating a captured group instead of capturing a repeated group.

As you have already found out, the difference is that repeating a captured group captures only the last iteration. Capturing a repeated group captures all iterations.

In PCRE (PHP):

((?:\w+)+),?
Match 1, Group 1.    0-5      HELLO
Match 2, Group 1.    6-11     THERE
Match 3, Group 1.    12-20    BRUTALLY
Match 4, Group 1.    21-26    CRUEL
Match 5, Group 1.    27-32    WORLD

Since all captures are in Group 1, you only need $1 for substitution.

I used the following general form of this regular expression:

((?:{{RE}})+)

Example at regex101

Why aren't python nested functions called closures?

Python has a weak support for closure. To see what I mean take the following example of a counter using closure with JavaScript:

function initCounter(){
    var x = 0;
    function counter  () {
        x += 1;
        console.log(x);
    };
    return counter;
}

count = initCounter();

count(); //Prints 1
count(); //Prints 2
count(); //Prints 3

Closure is quite elegant since it gives functions written like this the ability to have "internal memory". As of Python 2.7 this is not possible. If you try

def initCounter():
    x = 0;
    def counter ():
        x += 1 ##Error, x not defined
        print x
    return counter

count = initCounter();

count(); ##Error
count();
count();

You'll get an error saying that x is not defined. But how can that be if it has been shown by others that you can print it? This is because of how Python it manages the functions variable scope. While the inner function can read the outer function's variables, it cannot write them.

This is a shame really. But with just read-only closure you can at least implement the function decorator pattern for which Python offers syntactic sugar.

Update

As its been pointed out, there are ways to deal with python's scope limitations and I'll expose some.

1. Use the global keyword (in general not recommended).

2. In Python 3.x, use the nonlocal keyword (suggested by @unutbu and @leewz)

3. Define a simple modifiable class Object

class Object(object):
    pass

and create an Object scope within initCounter to store the variables

def initCounter ():
    scope = Object()
    scope.x = 0
    def counter():
        scope.x += 1
        print scope.x

    return counter

Since scope is really just a reference, actions taken with its fields do not really modify scope itself, so no error arises.

4. An alternative way, as @unutbu pointed out, would be to define each variable as an array (x = [0]) and modify it's first element (x[0] += 1). Again no error arises because x itself is not modified.

5. As suggested by @raxacoricofallapatorius, you could make x a property of counter

def initCounter ():

    def counter():
        counter.x += 1
        print counter.x

    counter.x = 0
    return counter

How to check for an empty object in an AngularJS view

http://plnkr.co/edit/u3xZFRKYCUh4D6hGzERw?p=preview

Because angular is not available from the scope, you can pass it to your controller scope.

$scope.angular = angular;

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

Looking at the Volley perspective here are some advantages for your requirement:

Volley, on one hand, is totally focused on handling individual, small HTTP requests. So if your HTTP request handling has some quirks, Volley probably has a hook for you. If, on the other hand, you have a quirk in your image handling, the only real hook you have is ImageCache. "It’s not nothing, but it’s not a lot!, either". but it has more other advantages like Once you define your requests, using them from within a fragment or activity is painless unlike parallel AsyncTasks

Pros and cons of Volley:

So what’s nice about Volley?

  • The networking part isn’t just for images. Volley is intended to be an integral part of your back end. For a fresh project based off of a simple REST service, this could be a big win.

  • NetworkImageView is more aggressive about request cleanup than Picasso, and more conservative in its GC usage patterns. NetworkImageView relies exclusively on strong memory references, and cleans up all request data as soon as a new request is made for an ImageView, or as soon as that ImageView moves offscreen.

  • Performance. This post won’t evaluate this claim, but they’ve clearly taken some care to be judicious in their memory usage patterns. Volley also makes an effort to batch callbacks to the main thread to reduce context switching.

  • Volley apparently has futures, too. Check out RequestFuture if you’re interested.

  • If you’re dealing with high-resolution compressed images, Volley is the only solution here that works well.

  • Volley can be used with Okhttp (New version of Okhttp supports NIO for better performance )

  • Volley plays nice with the Activity life cycle.

Problems With Volley:
Since Volley is new, few things are not supported yet, but it's fixed.

  1. Multipart Requests (Solution: https://github.com/vinaysshenoy/enhanced-volley)

  2. status code 201 is taken as an error, Status code from 200 to 207 are successful responses now.(Fixed: https://github.com/Vinayrraj/CustomVolley)

    Update: in latest release of Google volley, the 2XX Status codes bug is fixed now!Thanks to Ficus Kirkpatrick!

  3. it's less documented but many of the people are supporting volley in github, java like documentation can be found here. On android developer website, you may find guide for Transmitting Network Data Using Volley. And volley source code can be found at Google Git

  4. To solve/change Redirect Policy of Volley Framework use Volley with OkHTTP (CommonsWare mentioned above)

Also you can read this Comparing Volley's image loading with Picasso

Retrofit:

It's released by Square, This offers very easy to use REST API's (Update: Voila! with NIO support)

Pros of Retrofit:

  • Compared to Volley, Retrofit's REST API code is brief and provides excellent API documentation and has good support in communities! It is very easy to add into the projects.

  • We can use it with any serialization library, with error handling.

Update: - There are plenty of very good changes in Retrofit 2.0.0-beta2

  • version 1.6 of Retrofit with OkHttp 2.0 is now dependent on Okio to support java.io and java.nio which makes it much easier to access, store and process your data using ByteString and Buffer to do some clever things to save CPU and memory. (FYI: This reminds me of the Koush's OIN library with NIO support!) We can use Retrofit together with RxJava to combine and chain REST calls using rxObservables to avoid ugly callback chains (to avoid callback hell!!).

Cons of Retrofit for version 1.6:

  • Memory related error handling functionality is not good (in older versions of Retrofit/OkHttp) not sure if it's improved with the Okio with Java NIO support.

  • Minimum threading assistance can result call back hell if we use this in an improper way.

(All above Cons have been solved in the new version of Retrofit 2.0 beta)

========================================================================

Update:

Android Async vs Volley vs Retrofit performance benchmarks (milliseconds, lower value is better):

Android Async vs Volley vs Retrofit performance benchmarks

(FYI above Retrofit Benchmarks info will improve with java NIO support because the new version of OKhttp is dependent on NIO Okio library)

In all three tests with varying repeats (1 – 25 times), Volley was anywhere from 50% to 75% faster. Retrofit clocked in at an impressive 50% to 90% faster than the AsyncTasks, hitting the same endpoint the same number of times. On the Dashboard test suite, this translated into loading/parsing the data several seconds faster. That is a massive real-world difference. In order to make the tests fair, the times for AsyncTasks/Volley included the JSON parsing as Retrofit does it for you automatically.

RetroFit Wins in benchmark test!

In the end, we decided to go with Retrofit for our application. Not only is it ridiculously fast, but it meshes quite well with our existing architecture. We were able to make a parent Callback Interface that automatically performs error handling, caching, and pagination with little to no effort for our APIs. In order to merge in Retrofit, we had to rename our variables to make our models GSON compliant, write a few simple interfaces, delete functions from the old API, and modify our fragments to not use AsyncTasks. Now that we have a few fragments completely converted, it’s pretty painless. There were some growing pains and issues that we had to overcome, but overall it went smoothly. In the beginning, we ran into a few technical issues/bugs, but Square has a fantastic Google+ community that was able to help us through it.

When to use Volley?!

We can use Volley when we need to load images as well as consuming REST APIs!, network call queuing system is needed for many n/w request at the same time! also Volley has better memory related error handling than Retrofit!

OkHttp can be used with Volley, Retrofit uses OkHttp by default! It has SPDY support, connection pooling, disk caching, transparent compression! Recently, it has got some support of java NIO with Okio library.

Source, credit: volley-vs-retrofit by Mr. Josh Ruesch

Note: About streaming it depends on what type of streaming you want like RTSP/RTCP.

How to add items to a spinner in Android?

Add a spinner to the XML layout, and then add this code to the Java file:

Spinner spinner;
spinner = (Spinner) findViewById(R.id.spinner1) ;
java.util.ArrayList<String> strings = new java.util.ArrayList<>();
strings.add("Mobile") ;
strings.add("Home");
strings.add("Work");
SpinnerAdapter spinnerAdapter = new SpinnerAdapter(AddMember.this, R.layout.support_simple_spinner_dropdown_item, strings);
spinner.setAdapter(spinnerAdapter);

How do I use popover from Twitter Bootstrap to display an image?

Very simple :)

<a href="#" id="blob" class="btn large primary" rel="popover">hover for popover</a>

var img = '<img src="https://si0.twimg.com/a/1339639284/images/three_circles/twitter-bird-white-on-blue.png" />';

$("#blob").popover({ title: 'Look! A bird!', content: img, html:true });

http://jsfiddle.net/weuWk/

jQuery equivalent to Prototype array.last()

SugarJS

It's not jQuery but another library you may find useful in addition to jQuery: Try SugarJS.

Sugar is a Javascript library that extends native objects with helpful methods. It is designed to be intuitive, unobtrusive, and let you do more with less code.

With SugarJS, you can do:

[1,2,3,4].last()    //  => 4

That means, your example does work out of the box:

var array = [1,2,3,4];
var lastEl = array.last();    //  => 4

More Info

How can I add comments in MySQL?

"A comment for a column can be specified with the COMMENT option. The comment is displayed by the SHOW CREATE TABLE and SHOW FULL COLUMNS statements. This option is operational as of MySQL 4.1. (It is allowed but ignored in earlier versions.)"

As an example

--
-- Table structure for table 'accesslog'
--

CREATE TABLE accesslog (
aid int(10) NOT NULL auto_increment COMMENT 'unique ID for each access entry', 
title varchar(255) default NULL COMMENT 'the title of the page being accessed',
path varchar(255) default NULL COMMENT 'the local path of teh page being accessed',
....
) TYPE=MyISAM;

Take nth column in a text file

One more simple variant -

$ while read line
  do
      set $line          # assigns words in line to positional parameters
      echo "$3 $5"
  done < file

GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

In my case. I had the error because I forgot to make a commit after create a repository on github into an existing project. So I solved:

git add .
git commit -m"commentary"

Then I was able to type:

git push -u origin master

How to split a string literal across multiple lines in C / Objective-C?

There's a trick you can do with the pre-processor.
It has the potential down sides that it will collapse white-space, and could be confusing for people reading the code.
But, it has the up side that you don't need to escape quote characters inside it.

#define QUOTE(...) #__VA_ARGS__
const char *sql_query = QUOTE(
    SELECT word_id
    FROM table1, table2
    WHERE table2.word_id = table1.word_id
    ORDER BY table1.word ASC
);

the preprocessor turns this into:

const char *sql_query = "SELECT word_id FROM table1, table2 WHERE table2.word_id = table1.word_id ORDER BY table1.word ASC";

I've used this trick when I was writing some unit tests that had large literal strings containing JSON. It meant that I didn't have to escape every quote character \".

Write a file on iOS

May be this is useful to you.

//Method writes a string to a text file
-(void) writeToTextFile{
        //get the documents directory:
        NSArray *paths = NSSearchPathForDirectoriesInDomains
            (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        //make a file name to write the data to using the documents directory:
        NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                                                      documentsDirectory];
        //create content - four lines of text
        NSString *content = @"One\nTwo\nThree\nFour\nFive";
        //save content to the documents directory
        [content writeToFile:fileName 
                         atomically:NO 
                               encoding:NSUTF8StringEncoding 
                                      error:nil];

}


//Method retrieves content from documents directory and
//displays it in an alert
-(void) displayContent{
        //get the documents directory:
        NSArray *paths = NSSearchPathForDirectoriesInDomains
                        (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        //make a file name to write the data to using the documents directory:
        NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                                                      documentsDirectory];
        NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
                                                      usedEncoding:nil
                                                             error:nil];
        //use simple alert from my library (see previous post for details)
        [ASFunctions alert:content];
        [content release];

}

What is the best way to do a substring in a batch file?

Nicely explained above!

For all those who may suffer like me to get this working in a localized Windows (mine is XP in Slovak), you may try to replace the % with a !

So:

SET TEXT=Hello World
SET SUBSTRING=!TEXT:~3,5!
ECHO !SUBSTRING!

TypeError: $.ajax(...) is not a function?

let me share my experience:

my html page designer use:

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>

when I create a simple AJAX request, getting an error it says, TypeError: $.ajax(…) is not a function

So, i add:

<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>

then, it perfectly works for me at least.

How to display request headers with command line curl

curl's -v or --verbose option shows the HTTP request headers, among other things. Here is some sample output:

$ curl -v http://google.com/
* About to connect() to google.com port 80 (#0)
*   Trying 66.102.7.104... connected
* Connected to google.com (66.102.7.104) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.16.4 (i386-apple-darwin9.0) libcurl/7.16.4 OpenSSL/0.9.7l zlib/1.2.3
> Host: google.com
> Accept: */*
> 
< HTTP/1.1 301 Moved Permanently
< Location: http://www.google.com/
< Content-Type: text/html; charset=UTF-8
< Date: Thu, 15 Jul 2010 06:06:52 GMT
< Expires: Sat, 14 Aug 2010 06:06:52 GMT
< Cache-Control: public, max-age=2592000
< Server: gws
< Content-Length: 219
< X-XSS-Protection: 1; mode=block
< 
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
* Connection #0 to host google.com left intact
* Closing connection #0

How to download Xcode DMG or XIP file?

You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).

You must login to have a valid session before downloading anything below.

*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)

*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.

Xcode 12

  • 12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)

  • 12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)

  • 12.2

  • 12.1

  • 12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)

Xcode 11

Xcode 10 (unsupported for iTunes Connect)

  • 10.3 (Requires macOS 10.14.3 or later)
  • 10.2.1 (Requires macOS 10.14.3 or later)
  • 10.1 (Last version supporting macOS 10.13.6 High Sierra)
  • 10 (Subsequent versions were unsupported for iTunes Connect from March 2019)

Xcode 9

Xcode 8

Xcode 7

Xcode 6

Even Older Versions (unsupported for iTunes Connect)

Passing arguments forward to another javascript function

The explanation that none of the other answers supplies is that the original arguments are still available, but not in the original position in the arguments object.

The arguments object contains one element for each actual parameter provided to the function. When you call a you supply three arguments: the numbers 1, 2, and, 3. So, arguments contains [1, 2, 3].

function a(args){
    console.log(arguments) // [1, 2, 3]
    b(arguments);
}

When you call b, however, you pass exactly one argument: a's arguments object. So arguments contains [[1, 2, 3]] (i.e. one element, which is a's arguments object, which has properties containing the original arguments to a).

function b(args){
    // arguments are lost?
    console.log(arguments) // [[1, 2, 3]]
}

a(1,2,3);

As @Nick demonstrated, you can use apply to provide a set arguments object in the call.

The following achieves the same result:

function a(args){
    b(arguments[0], arguments[1], arguments[2]); // three arguments
}

But apply is the correct solution in the general case.

How to select all checkboxes with jQuery?

A more complete example that should work in your case:

_x000D_
_x000D_
$('#select_all').change(function() {_x000D_
  var checkboxes = $(this).closest('form').find(':checkbox');_x000D_
  checkboxes.prop('checked', $(this).is(':checked'));_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form>_x000D_
  <table>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" id="select_all" /></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" name="select[]" /></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" name="select[]" /></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" name="select[]" /></td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</form>
_x000D_
_x000D_
_x000D_

When the #select_all checkbox is clicked, the status of the checkbox is checked and all the checkboxes in the current form are set to the same status.

Note that you don't need to exclude the #select_all checkbox from the selection as that will have the same status as all the others. If you for some reason do need to exclude the #select_all, you can use this:

_x000D_
_x000D_
$('#select_all').change(function() {_x000D_
  var checkboxes = $(this).closest('form').find(':checkbox').not($(this));_x000D_
  checkboxes.prop('checked', $(this).is(':checked'));_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form>_x000D_
  <table>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" id="select_all" /></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" name="select[]" /></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" name="select[]" /></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td><input type="checkbox" name="select[]" /></td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to make CSS width to fill parent?

almost there, just change outerWidth: 100%; to width: auto; (outerWidth is not a CSS property)

alternatively, apply the following styles to bar:

width: auto;
display: block;

jQuery Ajax calls and the Html.AntiForgeryToken()

The Solution i found is not for ASPX but for Razor, but quite comperable issue.

I resolved it by adding the AntiForgery to the request. The HTML Helper does not create a HTML id with the call

@Html.AntiForgeryToken()

In order to add the token to the postrequest i just added the AntiForgery id to the hidden field with jquery:

$("input[name*='__RequestVerificationToken']").attr('id', '__AjaxAntiForgeryForm');

This caused the controller to accept the request with the [ValidateAntiForgeryToken] attribute

How to change a table name using an SQL query?

execute this command

sp_rename 'Employee','EData'

How to execute multiple SQL statements from java

you can achieve that using Following example uses addBatch & executeBatch commands to execute multiple SQL commands simultaneously.

Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database. reference

When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance.

  • JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature.
  • The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together.
  • The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement.
  • Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove.

EXAMPLE:

import java.sql.*;

public class jdbcConn {
   public static void main(String[] args) throws Exception{
      Class.forName("org.apache.derby.jdbc.ClientDriver");
      Connection con = DriverManager.getConnection
      ("jdbc:derby://localhost:1527/testDb","name","pass");

      Statement stmt = con.createStatement
      (ResultSet.TYPE_SCROLL_SENSITIVE,
      ResultSet.CONCUR_UPDATABLE);
      String insertEmp1 = "insert into emp values
      (10,'jay','trainee')";
      String insertEmp2 = "insert into emp values
      (11,'jayes','trainee')";
      String insertEmp3 = "insert into emp values
      (12,'shail','trainee')";
      con.setAutoCommit(false);
      stmt.addBatch(insertEmp1);//inserting Query in stmt
      stmt.addBatch(insertEmp2);
      stmt.addBatch(insertEmp3);
      ResultSet rs = stmt.executeQuery("select * from emp");
      rs.last();
      System.out.println("rows before batch execution= "
      + rs.getRow());
      stmt.executeBatch();
      con.commit();
      System.out.println("Batch executed");
      rs = stmt.executeQuery("select * from emp");
      rs.last();
      System.out.println("rows after batch execution= "
      + rs.getRow());
   }
} 

refer http://www.tutorialspoint.com/javaexamples/jdbc_executebatch.htm

C++ equivalent of Java's toString?

The question has been answered. But I wanted to add a concrete example.

class Point{

public:
      Point(int theX, int theY) :x(theX), y(theY)
      {}
      // Print the object
      friend ostream& operator <<(ostream& outputStream, const Point& p);
private:
      int x;
      int y;
};

ostream& operator <<(ostream& outputStream, const Point& p){
       int posX = p.x;
       int posY = p.y;

       outputStream << "x="<<posX<<","<<"y="<<posY;
      return outputStream;
}

This example requires understanding operator overload.

Scroll to bottom of div?

smooth scroll with Javascript:

document.getElementById('messages').scrollIntoView({ behavior: 'smooth', block: 'end' });

How to create composite primary key in SQL Server 2008

CREATE TABLE UserGroup
(
  [User_Id] INT Foreign Key,
  [Group_Id] INT foreign key,

 PRIMARY KEY ([User_Id], [Group_Id])
)

MySQL INNER JOIN Alias

You'll need to join twice:

SELECT home.*, away.*, g.network, g.date_start 
FROM game AS g
INNER JOIN team AS home
  ON home.importid = g.home
INNER JOIN team AS away
  ON away.importid = g.away
ORDER BY g.date_start DESC 
LIMIT 7

Xampp localhost/dashboard

Try this solution:

Go to->

  1. xammp ->htdocs-> then open index.php from the htdocs folder
  2. you can modify the dashboard
  3. restart the server

Example Code index.php :

    <?php
    if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
        $uri = 'https://';
    } else {
        $uri = 'http://';
    }
    $uri .= $_SERVER['HTTP_HOST'];
    header('Location: '.$uri.'/dashboard/');
    exit;
   ?>

How to map calculated properties with JPA and Hibernate

You have three options:

  • either you are calculating the attribute using a @Transient method
  • you can also use @PostLoad entity listener
  • or you can use the Hibernate specific @Formula annotation

While Hibernate allows you to use @Formula, with JPA, you can use the @PostLoad callback to populate a transient property with the result of some calculation:

@Column(name = "price")
private Double price;

@Column(name = "tax_percentage")
private Double taxes;

@Transient
private Double priceWithTaxes;

@PostLoad
private void onLoad() {
    this.priceWithTaxes = price * taxes;
}

So, you can use the Hibernate @Formula like this:

@Formula("""
    round(
       (interestRate::numeric / 100) *
       cents *
       date_part('month', age(now(), createdOn)
    )
    / 12)
    / 100::numeric
    """)
private double interestDollars;

What is The difference between ListBox and ListView

Listview derives from listbox control. One most important difference is listview uses the extended selection mode by default . listview also adds a property called view which enables you to customize the view in a richer way than a custom itemspanel. One real life example of listview with gridview is file explorer's details view. Listview with grid view is a less powerful data grid. After the introduction of datagrid control listview lost its importance.

How do I get today's date in C# in mm/dd/yyyy format?

string today = DateTime.Today.ToString("M/d");

sorting integers in order lowest to highest java

You can put them into a list and then sort them using their natural ordering, like so:

final List<Integer> list = Arrays.asList(11367, 11358, 11421, 11530, 11491, 11218, 11789);
Collections.sort( list );
// Use the sorted list

If the numbers are stored in the same variable, then you'll have to somehow put them into a List and then call sort, like so:

final List<Integer> list = new ArrayList<Integer>();
list.add( myVariable );
// Change myVariable to another number...
list.add( myVariable );
// etc...

Collections.sort( list );
// Use the sorted list

exporting multiple modules in react.js

When you

import App from './App.jsx';

That means it will import whatever you export default. You can rename App class inside App.jsx to whatever you want as long as you export default it will work but you can only have one export default.

So you only need to export default App and you don't need to export the rest.

If you still want to export the rest of the components, you will need named export.

https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export

z-index not working with position absolute

z-index only applies to elements that have been given an explicit position. Add position:relative to #popupContent and you should be good to go.

Difference between OpenJDK and Adoptium/AdoptOpenJDK

In short:

  • OpenJDK has multiple meanings and can refer to:
    • free and open source implementation of the Java Platform, Standard Edition (Java SE)
    • open source repository — the Java source code aka OpenJDK project
    • prebuilt OpenJDK binaries maintained by Oracle
    • prebuilt OpenJDK binaries maintained by the OpenJDK community
  • AdoptOpenJDK — prebuilt OpenJDK binaries maintained by community (open source licensed)

Explanation:

Prebuilt OpenJDK (or distribution) — binaries, built from http://hg.openjdk.java.net/, provided as an archive or installer, offered for various platforms, with a possible support contract.

OpenJDK, the source repository (also called OpenJDK project) - is a Mercurial-based open source repository, hosted at http://hg.openjdk.java.net. The Java source code. The vast majority of Java features (from the VM and the core libraries to the compiler) are based solely on this source repository. Oracle have an alternate fork of this.

OpenJDK, the distribution (see the list of providers below) - is free as in beer and kind of free as in speech, but, you do not get to call Oracle if you have problems with it. There is no support contract. Furthermore, Oracle will only release updates to any OpenJDK (the distribution) version if that release is the most recent Java release, including LTS (long-term support) releases. The day Oracle releases OpenJDK (the distribution) version 12.0, even if there's a security issue with OpenJDK (the distribution) version 11.0, Oracle will not release an update for 11.0. Maintained solely by Oracle.

Some OpenJDK projects - such as OpenJDK 8 and OpenJDK 11 - are maintained by the OpenJDK community and provide releases for some OpenJDK versions for some platforms. The community members have taken responsibility for releasing fixes for security vulnerabilities in these OpenJDK versions.

AdoptOpenJDK, the distribution is very similar to Oracle's OpenJDK distribution (in that it is free, and it is a build produced by compiling the sources from the OpenJDK source repository). AdoptOpenJDK as an entity will not be backporting patches, i.e. there won't be an AdoptOpenJDK 'fork/version' that is materially different from upstream (except for some build script patches for things like Win32 support). Meaning, if members of the community (Oracle or others, but not AdoptOpenJDK as an entity) backport security fixes to updates of OpenJDK LTS versions, then AdoptOpenJDK will provide builds for those. Maintained by OpenJDK community.

OracleJDK - is yet another distribution. Starting with JDK12 there will be no free version of OracleJDK. Oracle's JDK distribution offering is intended for commercial support. You pay for this, but then you get to rely on Oracle for support. Unlike Oracle's OpenJDK offering, OracleJDK comes with longer support for LTS versions. As a developer you can get a free license for personal/development use only of this particular JDK, but that's mostly a red herring, as 'just the binary' is basically the same as the OpenJDK binary. I guess it means you can download security-patched versions of LTS JDKs from Oracle's websites as long as you promise not to use them commercially.

Note. It may be best to call the OpenJDK builds by Oracle the "Oracle OpenJDK builds".

Donald Smith, Java product manager at Oracle writes:

Ideally, we would simply refer to all Oracle JDK builds as the "Oracle JDK", either under the GPL or the commercial license, depending on your situation. However, for historical reasons, while the small remaining differences exist, we will refer to them separately as Oracle’s OpenJDK builds and the Oracle JDK.


OpenJDK Providers and Comparison

----------------------------------------------------------------------------------------
|     Provider      | Free Builds | Free Binary   | Extended | Commercial | Permissive |
|                   | from Source | Distributions | Updates  | Support    | License    |
|--------------------------------------------------------------------------------------|
| AdoptOpenJDK      |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Amazon – Corretto |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Azul Zulu         |    No       |    Yes        |   Yes    |   Yes      |   Yes      |
| BellSoft Liberica |    No       |    Yes        |   Yes    |   Yes      |   Yes      |
| IBM               |    No       |    No         |   Yes    |   Yes      |   Yes      |
| jClarity          |    No       |    No         |   Yes    |   Yes      |   Yes      |
| OpenJDK           |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Oracle JDK        |    No       |    Yes        |   No**   |   Yes      |   No       |
| Oracle OpenJDK    |    Yes      |    Yes        |   No     |   No       |   Yes      |
| ojdkbuild         |    Yes      |    Yes        |   No     |   No       |   Yes      |
| RedHat            |    Yes      |    Yes        |   Yes    |   Yes      |   Yes      |
| SapMachine        |    Yes      |    Yes        |   Yes    |   Yes      |   Yes      |
----------------------------------------------------------------------------------------

Free Builds from Source - the distribution source code is publicly available and one can assemble its own build

Free Binary Distributions - the distribution binaries are publicly available for download and usage

Extended Updates - aka LTS (long-term support) - Public Updates beyond the 6-month release lifecycle

Commercial Support - some providers offer extended updates and customer support to paying customers, e.g. Oracle JDK (support details)

Permissive License - the distribution license is non-protective, e.g. Apache 2.0


Which Java Distribution Should I Use?

In the Sun/Oracle days, it was usually Sun/Oracle producing the proprietary downstream JDK distributions based on OpenJDK sources. Recently, Oracle had decided to do their own proprietary builds only with the commercial support attached. They graciously publish the OpenJDK builds as well on their https://jdk.java.net/ site.

What is happening starting JDK 11 is the shift from single-vendor (Oracle) mindset to the mindset where you select a provider that gives you a distribution for the product, under the conditions you like: platforms they build for, frequency and promptness of releases, how support is structured, etc. If you don't trust any of existing vendors, you can even build OpenJDK yourself.

Each build of OpenJDK is usually made from the same original upstream source repository (OpenJDK “the project”). However each build is quite unique - $free or commercial, branded or unbranded, pure or bundled (e.g., BellSoft Liberica JDK offers bundled JavaFX, which was removed from Oracle builds starting JDK 11).

If no environment (e.g., Linux) and/or license requirement defines specific distribution and if you want the most standard JDK build, then probably the best option is to use OpenJDK by Oracle or AdoptOpenJDK.


Additional information

Time to look beyond Oracle's JDK by Stephen Colebourne

Java Is Still Free by Java Champions community (published on September 17, 2018)

Java is Still Free 2.0.0 by Java Champions community (published on March 3, 2019)

Aleksey Shipilev about JDK updates interview by Opsian (published on June 27, 2019)

Return list from async/await method

Instead of doing all these, one can simply use ".Result" to get the result from a particular task.

eg: List list = GetListAsync().Result;

Which as per the definition => Gets the result value of this Task < TResult >

What is stability in sorting algorithms and why is it important?

I know there are many answers for this, but to me, this answer, by Robert Harvey, summarized it much more clearly:

A stable sort is one which preserves the original order of the input set, where the [unstable] algorithm does not distinguish between two or more items.

Source

Submit a form using jQuery

Note that if you already installed a submit event listener for your form, the innner call to submit()

jQuery('#<form-id>').submit( function(e){ 
    e.preventDefault();
    // maybe some validation in here
    if ( <form-is-valid> ) jQuery('#<form-id>').submit();
});

won't work as it tries to install a new event listener for this form's submit event (which fails). So you have to acces the HTML Element itself (unwrap from jQquery) and call submit() on this element directly:

    jQuery('#<form-id>').submit( function(e){ 
      e.preventDefault();
      // note the [0] array access:
      if ( <form-is-valid> ) jQuery('#<form-id>')[0].submit();
    });

No plot window in matplotlib

Try this:

import matplotlib
matplotlib.use('TkAgg') 

BEFORE import pylab

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

So I was running 300 PHP processes simulatenously and was getting a rate of between 60 - 90 per second (my process involves 3x queries). I upped it to 400 and this fell to about 40-50 per second. I dropped it to 200 and am back to between 60 and 90!

So my advice to anyone with this problem is experiment with running less than more and see if it improves. There will be less memory and CPU being used so the processes that do run will have greater ability and the speed may improve.

Cast Double to Integer in Java

It's worked for me. Try this:

double od = Double.parseDouble("1.15");
int oi = (int) od;

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

On Windows when you are using PowerShell you have to enclose all parameters with quotes.

So if you want to create a maven webapp archetype you would do as follows:

Prerequisites:

  1. Make sure you have maven installed and have it in your PATH environment variable.

Howto:

  1. Open windows powershell
  2. mkdir MyWebApp
  3. cd MyWebApp
  4. mvn archetype:generate "-DgroupId=com.javan.dev" "-DartifactId=MyWebApp" "-DarchetypeArtifactId=maven-archetype-webapp" "-DinteractiveMode=false"

enter image description here

Note: This is tested only on windows 10 powershell

How to delete a localStorage item when the browser window/tab is closed?

should be done like that and not with delete operator:

localStorage.removeItem(key);

Creating multiple objects with different names in a loop to store in an array list

You can use this code...

public class Main {

    public static void main(String args[]) {
        String[] names = {"First", "Second", "Third"};//You Can Add More Names
        double[] amount = {20.0, 30.0, 40.0};//You Can Add More Amount
        List<Customer> customers = new ArrayList<Customer>();
        int i = 0;
        while (i < names.length) {
            customers.add(new Customer(names[i], amount[i]));
            i++;
        }
    }
}

How do you align left / right a div without using float?

Another way to do something similar is with flexbox on a wrapper element, i.e.,

_x000D_
_x000D_
 .row {_x000D_
        display: flex;_x000D_
        justify-content: space-between;_x000D_
    }
_x000D_
  <div class="row">_x000D_
        <div>Left</div>_x000D_
        <div>Right</div>_x000D_
    </div>_x000D_
_x000D_
   
_x000D_
_x000D_
_x000D_

How do I disable TextBox using JavaScript?

Form elements can be accessed via the form's DOM element by name, not by "id" value. Give your form elements names if you want to access them like that, or else access them directly by "id" value:

document.getElementById("color").disabled = true;

edit — oh also, as pointed out by others, it's just "text", not "TextBox", for the "type" attribute.

You might want to invest a little time in reading some front-end development tutorials.

How to install a PHP IDE plugin for Eclipse directly from the Eclipse environment?

Updated for 2019: As previously suggested, in the latest Eclipse, go to "Install New Software" in the Help Menu and click the "add" button with this URL http://download.eclipse.org/tools/pdt/updates/latest/ that should show the latest release of PHP Development Tools (PDT). You might need to search for "php" or "pdt". For Nightly releases you can use http://download.eclipse.org/tools/pdt/updates/latest-nightly/.

macro - open all files in a folder

Try the below code:

Sub opendfiles()

Dim myfile As Variant
Dim counter As Integer
Dim path As String

myfolder = "D:\temp\"
ChDir myfolder
myfile = Application.GetOpenFilename(, , , , True)
counter = 1
If IsNumeric(myfile) = True Then
    MsgBox "No files selected"
End If
While counter <= UBound(myfile)
    path = myfile(counter)
    Workbooks.Open path
    counter = counter + 1
Wend

End Sub

What is the difference between HTTP 1.1 and HTTP 2.0?

HTTP 2.0 is a binary protocol that multiplexes numerous streams going over a single (normally TLS-encrypted) TCP connection.

The contents of each stream are HTTP 1.1 requests and responses, just encoded and packed up differently. HTTP2 adds a number of features to manage the streams, but leaves old semantics untouched.

How to remove an id attribute from a div using jQuery?

The capitalization is wrong, and you have an extra argument.

Do this instead:

$('img#thumb').removeAttr('id');

For future reference, there aren't any jQuery methods that begin with a capital letter. They all take the same form as this one, starting with a lower case, and the first letter of each joined "word" is upper case.

Tomcat startup logs - SEVERE: Error filterStart how to get a stack trace?

Generally Server JDK version will be lower than the deployed application (built with higher jdk version)

Correct way to remove plugin from Eclipse

Help --> About Eclipse --> Installation Details --> select whatever you want to uninstall from "Installed Software" tab.

Android Studio - Failed to apply plugin [id 'com.android.application']

As in Accepted post, the problem solved with updating gradle to 4.4.1.

  1. Get Latest Gradle 4.4.1 from here
  2. Extract and put it in "C:\Program Files\Android\Android Studio\gradle"
  3. Then from android studio go to "File -> Settings -> Build, Excecution, Deployment -> Gradle", from Project-level settings: Select Use local gradle Distribution and give the above
    address(folder with name "gradle-4.4.1" in "C:\Program Files\ ...")
  4. Then make project.

enter image description here

My Problem solved this way.

How do you revert to a specific tag in Git?

Git tags are just pointers to the commit. So you use them the same way as you do HEAD, branch names or commit sha hashes. You can use tags with any git command that accepts commit/revision arguments. You can try it with git rev-parse tagname to display the commit it points to.

In your case you have at least these two alternatives:

  1. Reset the current branch to specific tag:

    git reset --hard tagname
    
  2. Generate revert commit on top to get you to the state of the tag:

    git revert tag
    

This might introduce some conflicts if you have merge commits though.

How do I configure different environments in Angular.js?

Very late to the thread, but a technique I've used, pre-Angular, is to take advantage of JSON and the flexibility of JS to dynamically reference collection keys, and use inalienable facts of the environment (host server name, current browser language, etc.) as inputs to selectively discriminate/prefer suffixed key names within a JSON data structure.

This provides not merely deploy-environment context (per OP) but any arbitrary context (such as language) to provide i18n or any other variance required simultaneously, and (ideally) within a single configuration manifest, without duplication, and readably obvious.

IN ABOUT 10 LINES VANILLA JS

Overly-simplified but classic example: An API endpoint base URL in a JSON-formatted properties file that varies per environment where (natch) the host server will also vary:

    ...
    'svcs': {
        'VER': '2.3',
        'API@localhost': 'http://localhost:9090/',
        '[email protected]': 'https://www.uat.productionwebsite.com:9090/res/',
        '[email protected]': 'https://www.productionwebsite.com:9090/api/res/'
    },
    ...

A key to the discrimination function is simply the server hostname in the request.

This, naturally, can be combined with an additional key based on the user's language settings:

    ...
    'app': {
        'NAME': 'Ferry Reservations',
        'NAME@fr': 'Réservations de ferry',
        'NAME@de': 'Fähren Reservierungen'
    },
    ...

The scope of the discrimination/preference can be confined to individual keys (as above) where the "base" key is only overwritten if there's a matching key+suffix for the inputs to the function -- or an entire structure, and that structure itself recursively parsed for matching discrimination/preference suffixes:

    'help': {
        'BLURB': 'This pre-production environment is not supported. Contact Development Team with questions.',
        'PHONE': '808-867-5309',
        'EMAIL': '[email protected]'
    },
    '[email protected]': {
        'BLURB': 'Please contact Customer Service Center',
        'BLURB@fr': 'S\'il vous plaît communiquer avec notre Centre de service à la clientèle',
        'BLURB@de': 'Bitte kontaktieren Sie unseren Kundendienst!!1!',
        'PHONE': '1-800-CUS-TOMR',
        'EMAIL': '[email protected]'
    },

SO, if a visiting user to the production website has German (de) language preference setting, the above configuration would collapse to:

    'help': {
        'BLURB': 'Bitte kontaktieren Sie unseren Kundendienst!!1!',
        'PHONE': '1-800-CUS-TOMR',
        'EMAIL': '[email protected]'
    },

What does such a magical preference/discrimination JSON-rewriting function look like? Not much:

// prefer(object,suffix|[suffixes]) by/par/durch storsoc
// prefer({ a: 'apple', a@env: 'banana', b: 'carrot' },'env') -> { a: 'banana', b: 'carrot' }
function prefer(o,sufs) {
    for (var key in o) {
        if (!o.hasOwnProperty(key)) continue; // skip non-instance props
        if(key.split('@')[1]) { // suffixed!
            // replace root prop with the suffixed prop if among prefs
            if(o[key] && sufs.indexOf(key.split('@')[1]) > -1) o[key.split('@')[0]] = JSON.parse(JSON.stringify(o[key]));

            // and nuke the suffixed prop to tidy up
            delete o[key];

            // continue with root key ...
            key = key.split('@')[0];
        }

        // ... in case it's a collection itself, recurse it!
        if(o[key] && typeof o[key] === 'object') prefer(o[key],sufs);

    };
};

In our implementations, which include Angular and pre-Angular websites, we simply bootstrap the configuration well ahead of other resource calls by placing the JSON within a self-executing JS closure, including the prefer() function, and fed basic properties of hostname and language-code (and accepts any additional arbitrary suffixes you might need):

(function(prefs){ var props = {
    'svcs': {
        'VER': '2.3',
        'API@localhost': 'http://localhost:9090/',
        '[email protected]': 'https://www.uat.productionwebsite.com:9090/res/',
        '[email protected]': 'https://www.productionwebsite.com:9090/api/res/'
    },
    ...
    /* yadda yadda moar JSON und bisque */

    function prefer(o,sufs) {
        // body of prefer function, broken for e.g.
    };

    // convert string and comma-separated-string to array .. and process it
    prefs = [].concat( ( prefs.split ? prefs.split(',') : prefs ) || []);
    prefer(props,prefs);
    window.app_props = JSON.parse(JSON.stringify(props));
})([location.hostname, ((window.navigator.userLanguage || window.navigator.language).split('-')[0])  ] );

A pre-Angular site would now have a collapsed (no @ suffixed keys) window.app_props to refer to.

An Angular site, as a bootstrap/init step, simply copies the dead-dropped props object into $rootScope, and (optionally) destroys it from global/window scope

app.constant('props',angular.copy(window.app_props || {})).run( function ($rootScope,props) { $rootScope.props = props; delete window.app_props;} );

to be subsequently injected into controllers:

app.controller('CtrlApp',function($log,props){ ... } );

or referred to from bindings in views:

<span>{{ props.help.blurb }} {{ props.help.email }}</span>

Caveats? The @ character is not valid JS/JSON variable/key naming, but so far accepted. If that's a deal-breaker, substitute for any convention you like, such as "__" (double underscore) as long as you stick to it.

The technique could be applied server-side, ported to Java or C# but your efficiency/compactness may vary.

Alternately, the function/convention could be part of your front-end compile script, so that the full gory all-environment/all-language JSON is never transmitted over the wire.

UPDATE

We've evolved usage of this technique to allow multiple suffixes to a key, to avoid being forced to use collections (you still can, as deeply as you want), and as well to honor the order of the preferred suffixes.

Example (also see working jsFiddle):

var o = { 'a':'apple', 'a@dev':'apple-dev', 'a@fr':'pomme',
          'b':'banana', 'b@fr':'banane', 'b@dev&fr':'banane-dev',
          'c':{ 'o':'c-dot-oh', 'o@fr':'c-point-oh' }, 'c@dev': { 'o':'c-dot-oh-dev', 'o@fr':'c-point-oh-dev' } };

/*1*/ prefer(o,'dev');        // { a:'apple-dev', b:'banana',     c:{o:'c-dot-oh-dev'}   }
/*2*/ prefer(o,'fr');         // { a:'pomme',     b:'banane',     c:{o:'c-point-oh'}     }
/*3*/ prefer(o,'dev,fr');     // { a:'apple-dev', b:'banane-dev', c:{o:'c-point-oh-dev'} }
/*4*/ prefer(o,['fr','dev']); // { a:'pomme',     b:'banane-dev', c:{o:'c-point-oh-dev'} }
/*5*/ prefer(o);              // { a:'apple',     b:'banana',     c:{o:'c-dot-oh'}       }

1/2 (basic usage) prefers '@dev' keys, discards all other suffixed keys

3 prefers '@dev' over '@fr', prefers '@dev&fr' over all others

4 (same as 3 but prefers '@fr' over '@dev')

5 no preferred suffixes, drops ALL suffixed properties

It accomplishes this by scoring each suffixed property and promoting the value of a suffixed property to the non-suffixed property when iterating over the properties and finding a higher-scored suffix.

Some efficiencies in this version, including removing dependence on JSON to deep-copy, and only recursing into objects that survive the scoring round at their depth:

function prefer(obj,suf) {
    function pr(o,s) {
        for (var p in o) {
            if (!o.hasOwnProperty(p) || !p.split('@')[1] || p.split('@@')[1] ) continue; // ignore: proto-prop OR not-suffixed OR temp prop score
            var b = p.split('@')[0]; // base prop name
            if(!!!o['@@'+b]) o['@@'+b] = 0; // +score placeholder
            var ps = p.split('@')[1].split('&'); // array of property suffixes
            var sc = 0; var v = 0; // reset (running)score and value
            while(ps.length) {
                // suffix value: index(of found suffix in prefs)^10
                v = Math.floor(Math.pow(10,s.indexOf(ps.pop())));
                if(!v) { sc = 0; break; } // found suf NOT in prefs, zero score (delete later)
                sc += v;
            }
            if(sc > o['@@'+b]) { o['@@'+b] = sc; o[b] = o[p]; } // hi-score! promote to base prop
            delete o[p];
        }
        for (var p in o) if(p.split('@@')[1]) delete o[p]; // remove scores
        for (var p in o) if(typeof o[p] === 'object') pr(o[p],s); // recurse surviving objs
    }
    if( typeof obj !== 'object' ) return; // validate
    suf = ( (suf || suf === 0 ) && ( suf.length || suf === parseFloat(suf) ) ? suf.toString().split(',') : []); // array|string|number|comma-separated-string -> array-of-strings
    pr(obj,suf.reverse());
}

JRE installation directory in Windows

Following on from my other comment, here's a batch file which displays the current JRE or JDK based on the registry values.

It's different from the other solutions in instances where java is installed, but not on the PATH.

@ECHO off

SET KIT=JavaSoft\Java Runtime Environment
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE

SET KIT=Wow6432Node\JavaSoft\Java Runtime Environment
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE

SET KIT=JavaSoft\Java Development Kit
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE

SET KIT=Wow6432Node\JavaSoft\Java Development Kit
call:ReadRegValue VER "HKLM\Software\%KIT%" "CurrentVersion"
IF "%VER%" NEQ "" GOTO FoundJRE

ECHO Failed to find Java
GOTO :EOF

:FoundJRE
call:ReadRegValue JAVAPATH "HKLM\Software\%KIT%\%VER%" "JavaHome"
ECHO %JAVAPATH%
GOTO :EOF

:ReadRegValue
SET key=%2%
SET name=%3%
SET "%~1="
SET reg=reg
IF DEFINED ProgramFiles(x86) (
  IF EXIST %WINDIR%\sysnative\reg.exe SET reg=%WINDIR%\sysnative\reg.exe
)
FOR /F "usebackq tokens=3* skip=1" %%A IN (`%reg% QUERY %key% /v %name% 2^>NUL`) DO SET "%~1=%%A %%B"
GOTO :EOF

<code> vs <pre> vs <samp> for inline and block code snippets

Consider Prism.js: https://prismjs.com/#examples

It makes <pre><code> work and is attractive.

Flask - Calling python function on button OnClick event

You can simply do this with help of AJAX... Here is a example which calls a python function which prints hello without redirecting or refreshing the page.

In app.py put below code segment.

#rendering the HTML page which has the button
@app.route('/json')
def json():
    return render_template('json.html')

#background process happening without any refreshing
@app.route('/background_process_test')
def background_process_test():
    print ("Hello")
    return ("nothing")

And your json.html page should look like below.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
        $(function() {
          $('a#test').on('click', function(e) {
            e.preventDefault()
            $.getJSON('/background_process_test',
                function(data) {
              //do nothing
            });
            return false;
          });
        });
</script>


//button
<div class='container'>
    <h3>Test</h3>
        <form>
            <a href=# id=test><button class='btn btn-default'>Test</button></a>
        </form>

</div>

Here when you press the button Test simple in the console you can see "Hello" is displaying without any refreshing.

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

I'm using Juno 4.2 with latest spring, maven plugin and JDK1.6.0_25.

I faced same issue and here is my fix that make default after each Eclipse restart:

  1. List item
  2. Right-click on the maven project
  3. Java Build Path
  4. Libraries tab
  5. Select current wrong JRE item
  6. Click Edit
  7. Select the last option (Workspace default JRE (jdk1.6.0_25)

How to fix: "HAX is not working and emulator runs in emulation mode"

Default memory assigned to HAX is 1024MB. And the emulator has 1536MB apparently for Nexus 5x api 25.

if you're using Android Studio,

  • just go to tools -> AVD manager.
  • Then select the emulator and click on pencil button on the right for editing.
  • Go to advanced settings in the new window and change the RAM value to 1024

Works like a charm. :)

screenshot of android studio

TypeError: 'undefined' is not an object

I'm not sure how you could just check if something isn't undefined and at the same time get an error that it is undefined. What browser are you using?

You could check in the following way (extra = and making length a truthy evaluation)

if (typeof(sub.from) !== 'undefined' && sub.from.length) {

[update]

I see that you reset sub and thereby reset sub.from but fail to re check if sub.from exist:

for (var i = 0; i < sub.from.length; i++) {//<== assuming sub.from.exist
            mainid = sub.from[i]['id'];
            var sub = afcHelper_Submissions[mainid]; // <== re setting sub

My guess is that the error is not on the if statement but on the for(i... statement. In Firebug you can break automatically on an error and I guess it'll break on that line (not on the if statement).

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

The ISO C99 standard specifies that these macros must only be defined if explicitly requested.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

... now PRIu64 will work

How to print table using Javascript?

One cheeky solution :

  function printDiv(divID) {
        //Get the HTML of div
        var divElements = document.getElementById(divID).innerHTML;
        //Get the HTML of whole page
        var oldPage = document.body.innerHTML;
        //Reset the page's HTML with div's HTML only
        document.body.innerHTML = 
          "<html><head><title></title></head><body>" + 
          divElements + "</body>";
        //Print Page
        window.print();
        //Restore orignal HTML
        document.body.innerHTML = oldPage;

    }

HTML :

<form id="form1" runat="server">
    <div id="printablediv" style="width: 100%; background-color: Blue; height: 200px">
        Print me I am in 1st Div
    </div>
    <div id="donotprintdiv" style="width: 100%; background-color: Gray; height: 200px">
        I am not going to print
    </div>
    <input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" />
</form>

open link in iframe

Well, there's an alternate way! You can use a button instead of hyperlink. Hence, when the button is clicked the web page specified in "name_of_webpage" is opened in the target frame named "name_of_iframe". It works for me!

<form method="post" action="name_of_webpage" target="name_of_iframe">
<input type="submit" value="any_name_you_want" />
</form>
<iframe name="name_of_iframe"></iframe>

How to right align widget in horizontal linear layout Android?

As a supplement to alcsan's answer, you can use Space since API 14 (Android 4.0 ICE_CREAM_SANDWICH), document here.

Space is a lightweight View subclass that may be used to create gaps between components in general purpose layouts.

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

    <Space
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <TextView
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:text="TextView"
        android:gravity="right" />

</LinearLayout>

For apps that supporting API levels under 14, there is an android.support.v4.widget.Space since Android Support Library r22.1.0.

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

I have build such kind of application using approximatively the same approach except :

  • I cache the generated image on the disk and always generate two to three images in advance in a separate thread.
  • I don't overlay with a UIImage but instead draw the image in the layer when zooming is 1. Those tiles will be released automatically when memory warnings are issued.

Whenever the user start zooming, I acquire the CGPDFPage and render it using the appropriate CTM. The code in - (void)drawLayer: (CALayer*)layer inContext: (CGContextRef) context is like :

CGAffineTransform currentCTM = CGContextGetCTM(context);    
if (currentCTM.a == 1.0 && baseImage) {
    //Calculate ideal scale
    CGFloat scaleForWidth = baseImage.size.width/self.bounds.size.width;
    CGFloat scaleForHeight = baseImage.size.height/self.bounds.size.height; 
    CGFloat imageScaleFactor = MAX(scaleForWidth, scaleForHeight);

    CGSize imageSize = CGSizeMake(baseImage.size.width/imageScaleFactor, baseImage.size.height/imageScaleFactor);
    CGRect imageRect = CGRectMake((self.bounds.size.width-imageSize.width)/2, (self.bounds.size.height-imageSize.height)/2, imageSize.width, imageSize.height);
    CGContextDrawImage(context, imageRect, [baseImage CGImage]);
} else {
    @synchronized(issue) { 
        CGPDFPageRef pdfPage = CGPDFDocumentGetPage(issue.pdfDoc, pageIndex+1);
        pdfToPageTransform = CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, layer.bounds, 0, true);
        CGContextConcatCTM(context, pdfToPageTransform);    
        CGContextDrawPDFPage(context, pdfPage);
    }
}

issue is the object containg the CGPDFDocumentRef. I synchronize the part where I access the pdfDoc property because I release it and recreate it when receiving memoryWarnings. It seems that the CGPDFDocumentRef object do some internal caching that I did not find how to get rid of.

How to sum the values of a JavaScript object?

Now you can make use of reduce function and get the sum.

_x000D_
_x000D_
const object1 = { 'a': 1 , 'b': 2 , 'c':3 }_x000D_
_x000D_
console.log(Object.values(object1).reduce((a, b) => a + b, 0));
_x000D_
_x000D_
_x000D_

Connecting an input stream to an outputstream

Asynchronous way to achieve it.

void inputStreamToOutputStream(final InputStream inputStream, final OutputStream out) {
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                int d;
                while ((d = inputStream.read()) != -1) {
                    out.write(d);
                }
            } catch (IOException ex) {
                //TODO make a callback on exception.
            }
        }
    });
    t.setDaemon(true);
    t.start();
}

POST unchecked HTML checkboxes

If you want to submit an array of checkbox values (including un-checked items) then you could try something like this:

<form>
<input type="hidden" value="0" name="your_checkbox_array[]"><input type="checkbox">Dog
<input type="hidden" value="0" name="your_checkbox_array[]"><input type="checkbox">Cat
</form>

$('form').submit(function(){
    $('input[type="checkbox"]:checked').prev().val(1);
});

Arrays in unix shell?

If you want a key value store with support for spaces use the -A parameter:

declare -A programCollection
programCollection["xwininfo"]="to aquire information about the target window."

for program in ${!programCollection[@]}
do
    echo "The program ${program} is used ${programCollection[${program}]}"
done

http://linux.die.net/man/1/bash "Associative arrays are created using declare -A name. "

How does one use glide to download an image into a bitmap?

Kotlin's way -

fun Context.bitMapFromImgUrl(imageUrl: String, callBack: (bitMap: Bitmap) -> Unit) {
    GlideApp.with(this)
        .asBitmap()
        .load(imageUrl)
        .into(object : CustomTarget<Bitmap>() {
            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                callBack(resource)
            }

            override fun onLoadCleared(placeholder: Drawable?) {
                // this is called when imageView is cleared on lifecycle call or for
                // some other reason.
                // if you are referencing the bitmap somewhere else too other than this imageView
                // clear it here as you can no longer have the bitmap
            }
        })
}

Maximum number of records in a MySQL database table

Row Size Limits

The maximum row size for a given table is determined by several factors:
  • The internal representation of a MySQL table has a maximum row size limit of 65,535 bytes, even if the storage engine is capable of supporting larger rows. BLOB and TEXT columns only contribute 9 to 12 bytes toward the row size limit because their contents are stored separately from the rest of the row.

  • The maximum row size for an InnoDB table, which applies to data stored locally within a database page, is slightly less than half a page. For example, the maximum row size is slightly less than 8KB for the default 16KB InnoDB page size, which is defined by the innodb_page_size configuration option. “Limits on InnoDB Tables”.

  • If a row containing variable-length columns exceeds the InnoDB maximum row size, InnoDB selects variable-length columns for external off-page storage until the row fits within the InnoDB row size limit. The amount of data stored locally for variable-length columns that are stored off-page differs by row format. For more information, see “InnoDB Row Storage and Row Formats”.
  • Different storage formats use different amounts of page header and trailer data, which affects the amount of storage available for rows.

XSLT equivalent for JSON

It may be possible to use XSLT with JSON. Verson 3 of XPath(3.1) XSLT(3.0) and XQuery(3.1) supports JSON in some way. This seems to be available in the commercial version of Saxon, and might at some point be included in the HE version. https://www.saxonica.com/html/documentation/functions/fn/parse-json.html

-

What I would expect from an alternative solution:

I would want to be able input JSON to fetch a matching set of data, and output JSON or TEXT.

Access arbitrary properties and evaluate the values

Support for conditional logic

I would want the transformation scripts to be external from the tool, text based, and preferably a commonly used language.

Potential alternative?

I wonder if SQL could be a suitable alternative. https://docs.microsoft.com/en-us/sql/relational-databases/json/json-data-sql-server

It would be nice if the alternative tool could handle JSON and XML https://docs.microsoft.com/en-us/sql/relational-databases/xml/openxml-sql-server

I have not yet tried to convert the XSLT scripts I use to SQL, or fully evaluated this option yet, but I hope to look into it more soon. Just some thoughts so far.

initializing a Guava ImmutableMap

if the map is short you can do:

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

If it is longer then:

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

How to connect to a MySQL Data Source in Visual Studio

Installing the following packages:

adds MySQL Database to the data sources list (Visual Studio 2017)

How do you create an asynchronous method in C#?

One very simple way to make a method asynchronous is to use Task.Yield() method. As MSDN states:

You can use await Task.Yield(); in an asynchronous method to force the method to complete asynchronously.

Insert it at beginning of your method and it will then return immediately to the caller and complete the rest of the method on another thread.

private async Task<DateTime> CountToAsync(int num = 1000)
{
    await Task.Yield();
    for (int i = 0; i < num; i++)
    {
        Console.WriteLine("#{0}", i);
    }
    return DateTime.Now;
}

How to check if an integer is in a given range?

Try:

if (i>0 && i<100) {} 

it will work at least ;)

ConcurrentHashMap vs Synchronized HashMap

The short answer:

Both maps are thread-safe implementations of the Map interface. ConcurrentHashMap is implemented for higher throughput in cases where high concurrency is expected.

Brian Goetz's article on the idea behind ConcurrentHashMap is a very good read. Highly recommended.

BATCH file asks for file or folder

The /i switch might be what your after.

From xcopy /?

/I If destination does not exist and copying more than one file, assumes that destination must be a directory.

Right align and left align text in same HTML table cell

If you want them on separate lines do what Balon said. If you want them on the same lines, do:

<td>
  <div style="float:left;width:50%;">this is left</div>
  <div style="float:right;width:50%;">this is right</div>
</td>

How to mock void methods with Mockito

I think I've found a simpler answer to that question, to call the real method for just one method (even if it has a void return) you can do this:

Mockito.doCallRealMethod().when(<objectInstance>).<method>();
<objectInstance>.<method>();

Or, you could call the real method for all methods of that class, doing this:

<Object> <objectInstance> = mock(<Object>.class, Mockito.CALLS_REAL_METHODS);

How to initialize an array in Kotlin with values?

You can create an Int Array like this:

val numbers = IntArray(5, { 10 * (it + 1) })

5 is the Int Array size. the lambda function is the element init function. 'it' range in [0,4], plus 1 make range in [1,5]

origin function is:

 /**
 * An array of ints. When targeting the JVM, instances of this class are 
 * represented as `int[]`.
 * @constructor Creates a new array of the specified [size], with all elements 
 *  initialized to zero.
 */
 public class IntArray(size: Int) {
       /**
        * Creates a new array of the specified [size], where each element is 
        * calculated by calling the specified
        * [init] function. The [init] function returns an array element given 
        * its index.
        */
      public inline constructor(size: Int, init: (Int) -> Int)
  ...
 }

IntArray class defined in the Arrays.kt

Disable Input fields in reactive form

This worked for me: this.form.get('first').disable({onlySelf: true});

Cloudfront custom-origin distribution returns 502 "ERROR The request could not be satisfied." for some URLs

One more possible solution: I have a staging server that serves the site and the Cloudfront assets over HTTP. I had my origin set to "Match Viewer" instead of "HTTP Only". I also use the HTTPS Everywhere extension, which redirected all the http://*.cloudfront.net URLs to the https://* version. Since the staging server isn't available over SSL and Cloudfront was matching the viewer, it couldn't find the assets at https://example.com and cached a bunch of 502s instead.

How to remove selected commit log entries from a Git repository while keeping their changes?

You can use git cherry-pick for this. 'cherry-pick' will apply a commit onto the branch your on now.

then do

git rebase --hard <SHA1 of A>

then apply the D and E commits.

git cherry-pick <SHA1 of D>
git cherry-pick <SHA1 of E>

This will skip out the B and C commit. Having said that it might be impossible to apply the D commit to the branch without B, so YMMV.

How to get the sizes of the tables of a MySQL database?

SELECT 
    table_name AS "Table",  
    round(((data_length + index_length) / 1024 / 1024), 2) as size   
FROM information_schema.TABLES  
WHERE table_schema = "YOUR_DATABASE_NAME"  
ORDER BY size DESC; 

This sorts the sizes (DB Size in MB).

How to fix curl: (60) SSL certificate: Invalid certificate chain

Another cause of this can be duplicate keys in your KeyChain. I've seen this problem on two macs where there were duplicate "DigiCert High Assurance EV Root CA". One was in the login keychain, the other in the system one. Removing the certificate from the login keychain solved the problem.

This affected Safari browser as well as git on the command line.

Changing element style attribute dynamically using JavaScript

document.getElementById("xyz").setAttribute('style','padding-top:10px');

would also do the job.

How to use null in switch

You can't. You can use primitives (int, char, short, byte) and String (Strings in java 7 only) in switch. primitives can't be null.
Check i in separate condition before switch.

Retrieve WordPress root directory path?

I like @Omry Yadan's solution but I think it can be improved upon to use a loop in case you want to continue traversing up the directory tree until you find where wp-config.php actually lives. Of course, if you don't find it and end up in the server's root then all is lost and we return a sane value (false).

function wp_get_web_root() {

  $base = dirname(__FILE__);
  $path = false;

  while(!$path && '/' != $base) {
    if(@file_exists(dirname($base)).'/wp-config.php') {
      $path = dirname($base);
    } else {
      $base = dirname($base);
    }
  }

  return $path;
}

JavaScript: undefined !== undefined?

I'd like to post some important information about undefined, which beginners might not know.

Look at the following code:

 /* 
  * Consider there is no code above. 
  * The browser runs these lines only.
  */

   // var a;  
   // --- commented out to point that we've forgotten to declare `a` variable 

   if ( a === undefined ) {
       alert('Not defined');
   } else {
       alert('Defined: ' + a);
   }

   alert('Doing important job below');

If you run this code, where variable a HAS NEVER BEEN DECLARED using var, you will get an ERROR EXCEPTION and surprisingly see no alerts at all.

Instead of 'Doing important job below', your script will TERMINATE UNEXPECTEDLY, throwing unhandled exception on the very first line.


Here is the only bulletproof way to check for undefined using typeof keyword, which was designed just for such purpose:

   /* 
    * Correct and safe way of checking for `undefined`: 
    */

   if ( typeof a === 'undefined' ) {
       alert(
           'The variable is not declared in this scope, \n' +
           'or you are pointing to unexisting property, \n' +
           'or no value has been set yet to the variable, \n' + 
           'or the value set was `undefined`. \n' +
           '(two last cases are equivalent, don\'t worry if it blows out your mind.'
           );
   }

   /* 
    *  Use `typeof` for checking things like that
    */

This method works in all possible cases.

The last argument to use it is that undefined can be potentially overwritten in earlier versions of Javascript:

     /* @ Trollface @ */
        undefined = 2;
     /* Happy debuging! */  

Hope I was clear enough.

Convert HttpPostedFileBase to byte[]

As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:

MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();

It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.

For efficient purposes you could check whether the stream returned is already a MemoryStream:

byte[] data;
using (Stream inputStream = model.File.InputStream)
{
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
    {
        memoryStream = new MemoryStream();
        inputStream.CopyTo(memoryStream);
    }
    data = memoryStream.ToArray();
}

How to enable external request in IIS Express?

There are three changes you might need to make.

  1. Tell IIS Express itself to bind to all ip addresses and hostnames. In your .config file. Typically:
    • VS 2015: $(solutionDir)\.vs\config\applicationhost.config
    • < VS 2015: %userprofile%\My Documents\IISExpress\config\applicationhost.config

Find your site's binding element, and add

    <binding protocol="http" bindingInformation="*:8080:*" />
  1. Setup the bit of Windows called 'http.sys'. As an administrator, run the command:
    netsh http add urlacl url=http://*:8080/ user=everyone

Where everyone is a windows group. Use double quotes for groups with spaces like "Tout le monde".

  1. Allow IIS Express through Windows firewall.

    Start / Windows Firewall with Advanced Security / Inbound Rules / New Rule...

    Program %ProgramFiles%\IIS Express\iisexpress.exe
    OR Port 8080 TCP

Now when you start iisexpress.exe you should see a message such as

Successfully registered URL "http://*:8080/" for site "hello world" application "/"

Viewing all `git diffs` with vimdiff

git config --global diff.tool vimdiff
git config --global difftool.prompt false

Typing git difftool yields the expected behavior.

Navigation commands,

  • :qa in vim cycles to the next file in the changeset without saving anything.

Aliasing (example)

git config --global alias.d difftool

.. will let you type git d to invoke vimdiff.

Advanced use-cases,

  • By default, git calls vimdiff with the -R option. You can override it with git config --global difftool.vimdiff.cmd 'vimdiff "$LOCAL" "$REMOTE"'. That will open vimdiff in writeable mode which allows edits while diffing.
  • :wq in vim cycles to the next file in the changeset with changes saved.

Numpy, multiply array with scalar

You can multiply numpy arrays by scalars and it just works.

>>> import numpy as np
>>> np.array([1, 2, 3]) * 2
array([2, 4, 6])
>>> np.array([[1, 2, 3], [4, 5, 6]]) * 2
array([[ 2,  4,  6],
       [ 8, 10, 12]])

This is also a very fast and efficient operation. With your example:

>>> a_1 = np.array([1.0, 2.0, 3.0])
>>> a_2 = np.array([[1., 2.], [3., 4.]])
>>> b = 2.0
>>> a_1 * b
array([2., 4., 6.])
>>> a_2 * b
array([[2., 4.],
       [6., 8.]])

Sorting a Python list by two fields

employees.sort(key = lambda x:x[1])
employees.sort(key = lambda x:x[0])

We can also use .sort with lambda 2 times because python sort is in place and stable. This will first sort the list according to the second element, x[1]. Then, it will sort the first element, x[0] (highest priority).

employees[0] = Employee's Name
employees[1] = Employee's Salary

This is equivalent to doing the following: employees.sort(key = lambda x:(x[0], x[1]))

Handling JSON Post Request in Go

There are two reasons why json.Decoder should be preferred over json.Unmarshal - that are not addressed in the most popular answer from 2013:

  1. February 2018, go 1.10 introduced a new method json.Decoder.DisallowUnknownFields() which addresses the concern of detecting unwanted JSON-input
  2. req.Body is already an io.Reader. Reading its entire contents and then performing json.Unmarshal wastes resources if the stream was, say a 10MB block of invalid JSON. Parsing the request body, with json.Decoder, as it streams in would trigger an early parse error if invalid JSON was encountered. Processing I/O streams in realtime is the preferred go-way.

Addressing some of the user comments about detecting bad user input:

To enforce mandatory fields, and other sanitation checks, try:

d := json.NewDecoder(req.Body)
d.DisallowUnknownFields() // catch unwanted fields

// anonymous struct type: handy for one-time use
t := struct {
    Test *string `json:"test"` // pointer so we can test for field absence
}{}

err := d.Decode(&t)
if err != nil {
    // bad JSON or unrecognized json field
    http.Error(rw, err.Error(), http.StatusBadRequest)
    return
}

if t.Test == nil {
    http.Error(rw, "missing field 'test' from JSON object", http.StatusBadRequest)
    return
}

// optional extra check
if d.More() {
    http.Error(rw, "extraneous data after JSON object", http.StatusBadRequest)
    return
}

// got the input we expected: no more, no less
log.Println(*t.Test)

Playground

Typical output:

$ curl -X POST -d "{}" http://localhost:8082/strict_test

expected json field 'test'

$ curl -X POST -d "{\"Test\":\"maybe?\",\"Unwanted\":\"1\"}" http://localhost:8082/strict_test

json: unknown field "Unwanted"

$ curl -X POST -d "{\"Test\":\"oops\"}g4rB4g3@#$%^&*" http://localhost:8082/strict_test

extraneous data after JSON

$ curl -X POST -d "{\"Test\":\"Works\"}" http://localhost:8082/strict_test 

log: 2019/03/07 16:03:13 Works

Convert Java Object to JsonNode in Jackson

As of Jackson 1.6, you can use:

JsonNode node = mapper.valueToTree(map);

or

JsonNode node = mapper.convertValue(object, JsonNode.class);

Source: is there a way to serialize pojo's directly to treemodel?

How to change value of ArrayList element in java

I agree with Duncan ...I have tried it with mutable object but still get the same problem... I got a simple solution to this... use ListIterator instead Iterator and use set method of ListIterator

ListIterator<Integer> i = a.listIterator();
//changed the value of first element in List
Integer x =null;
        if(i.hasNext()) {
            x = i.next();
            x = Integer.valueOf(9);
        }
    //set method sets the recent iterated element in ArrayList
    i.set(x);
        //initialized the iterator again and print all the elements
        i = a.listIterator();
        while(i.hasNext())
        System.out.print(i.next());

But this constraints me to use this only for ArrayList only which can use ListIterator...i will have same problem with any other Collection

How to check if an user is logged in Symfony2 inside a controller?

If you are using security annotation from the SensioFrameworkExtraBundle, you can use a few expressions (that are defined in \Symfony\Component\Security\Core\Authorization\ExpressionLanguageProvider):

  • @Security("is_authenticated()"): to check that the user is authed and not anonymous
  • @Security("is_anonymous()"): to check if the current user is the anonymous user
  • @Security("is_fully_authenticated()"): equivalent to is_granted('IS_AUTHENTICATED_FULLY')
  • @Security("is_remember_me()"): equivalent to is_granted('IS_AUTHENTICATED_REMEMBERED')

How to embed images in email

Correct way of embedding images into Outlook and avoiding security problems is the next:

  1. Use interop for Outlook 2003;
  2. Create new email and set it save folder;
  3. Do not use base64 embedding, outlook 2007 does not support it; do not reference files on your disk, they won't be send; do not use word editor inspector because you will get security warnings on some machines;
  4. Attachment must have png/jpg extension. If it will have for instance tmp extension - Outlook will warn user;
  5. Pay attention how CID is generated without mapi;
  6. Do not access properties via getters or you will get security warnings on some machines.

    public static void PrepareEmail()
    {
        var attachFile = Path.Combine(
            Application.StartupPath, "mySuperImage.png"); // pay attention that image must not contain spaces, because Outlook cannot inline such images
    
        Microsoft.Office.Interop.Outlook.Application outlook = null;
        NameSpace space = null;
        MAPIFolder folder = null;
        MailItem mail = null;
        Attachment attachment = null;
        try
        {
            outlook = new Microsoft.Office.Interop.Outlook.Application();
            space = outlook.GetNamespace("MAPI");
            space.Logon(null, null, true, true);
    
            folder = space.GetDefaultFolder(OlDefaultFolders.olFolderSentMail);
            mail = (MailItem) outlook.CreateItem(OlItemType.olMailItem);
    
            mail.SaveSentMessageFolder = folder;
            mail.Subject = "Hi Everyone";
            mail.Attachments.Add(attachFile, OlAttachmentType.olByValue, 0, Type.Missing); 
            // Last Type.Missing - is for not to show attachment in attachments list.
    
            string attachmentId = Path.GetFileName(attachFile);
            mail.BodyFormat = OlBodyFormat.olFormatHTML;
    
             mail.HTMLBody = string.Format("<br/><img src=\'cid:{0}\' />", attachmentId);
    
            mail.Display(false);
        }
        finally
        {
            ReleaseComObject(outlook, space, folder, mail, attachment);
        }
    }
    

Passing parameter to controller action from a Html.ActionLink

You are using incorrect overload. You should use this overload

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    Object routeValues,
    Object htmlAttributes
) 

And the correct code would be

<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>

Note that extra parameter at the end. For the other overloads, visit LinkExtensions.ActionLink Method. As you can see there is no string, string, string, object overload that you are trying to use.

Automatically creating directories with file output

The os.makedirs function does this. Try the following:

import os
import errno

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

with open(filename, "w") as f:
    f.write("FOOBAR")

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


In Python 3.2+, there is a more elegant way that avoids the race condition above:

import os

filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")

how to copy only the columns in a DataTable to another DataTable?

The DataTable.Clone() method works great when you want to create a completely new DataTable, but there might be cases where you would want to add the schema columns from one DataTable to another existing DataTable.

For example, if you've derived a new subclass from DataTable, and want to import schema information into it, you couldn't use Clone().

E.g.:

public class CoolNewTable : DataTable {
   public void FillFromReader(DbDataReader reader) {
       // We want to get the schema information (i.e. columns) from the 
       // DbDataReader and 
       // import it into *this* DataTable, NOT a new one.
       DataTable schema = reader.GetSchemaTable(); 
       //GetSchemaTable() returns a DataTable with the columns we want.

       ImportSchema(this, schema); // <--- how do we do this?
   }
}

The answer is just to create new DataColumns in the existing DataTable using the schema table's columns as templates.

I.e. the code for ImportSchema would be something like this:

void ImportSchema(DataTable dest, DataTable source) {
    foreach(var c in source.Columns)
        dest.Columns.Add(c);
}

or, if you're using Linq:

void ImportSchema(DataTable dest, DataTable source) {
    var cols = source.Columns.Cast<DataColumn>().ToArray();
    dest.Columns.AddRange(cols);
}

This was just one example of a situation where you might want to copy schema/columns from one DataTable into another one without using Clone() to create a completely new DataTable. I'm sure I've come across several others as well.

changing the owner of folder in linux

Use chown to change ownership and chmod to change rights.

use the -R option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

For example

sudo chown -R username:group directory

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

sudo chown username:group directory

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

chgrp group_name file/directory_name

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

Missing artifact com.microsoft.sqlserver:sqljdbc4:jar:4.0

UPDATE

Microsoft now provide this artifact in maven central. See @nirmal's answer for further details: https://stackoverflow.com/a/41149866/1570834


ORIGINAL ANSWER

The issue is that Maven can't find this artifact in any of the configured maven repositories.

Unfortunately Microsoft doesn't make this artifact available via any maven repository. You need to download the jar from the Microsoft website, and then manually install it into your local maven repository.

You can do this with the following maven command:

mvn install:install-file -Dfile=sqljdbc4.jar -DgroupId=com.microsoft.sqlserver -DartifactId=sqljdbc4 -Dversion=4.0 -Dpackaging=jar

Then next time you run maven on your POM it will find the artifact.

Searching for Text within Oracle Stored Procedures

I allways use UPPER(text) like UPPER('%blah%')

setTimeout in React Native

You can bind this to your function by adding .bind(this) directly to the end of your function definition. You would rewrite your code block as:

setTimeout(function () {
  this.setState({ timePassed: true });
}.bind(this), 1000);

How do you set your pythonpath in an already-created virtualenv?

It's already answered here -> Is my virtual environment (python) causing my PYTHONPATH to break?

UNIX/LINUX

Add "export PYTHONPATH=/usr/local/lib/python2.0" this to ~/.bashrc file and source it by typing "source ~/.bashrc" OR ". ~/.bashrc".

WINDOWS XP

1) Go to the Control panel 2) Double click System 3) Go to the Advanced tab 4) Click on Environment Variables

In the System Variables window, check if you have a variable named PYTHONPATH. If you have one already, check that it points to the right directories. If you don't have one already, click the New button and create it.

PYTHON CODE

Alternatively, you can also do below your code:-

import sys
sys.path.append("/home/me/mypy") 

What permission do I need to access Internet from an Android application?

forget about adding the permission into the manifest Add this code as a method

public static boolean hasPermissions(Context context, String... permissions)
{
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null)
    {
        for (String permission : permissions)
        {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED)
            {
                return false;
            }
        }
    }
    return true;
}

and write this in your Main

int PERMISSION_ALL = 1;
    String[] PERMISSIONS = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_SMS, Manifest.permission.CAMERA};

    if (!hasPermissions(this, PERMISSIONS)) {
        ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
    }

Printing everything except the first field with awk

awk '{sub($1 FS,"")}7' YourFile

Remove the first field and separator, and print the result (7 is a non zero value so printing $0).

APR based Apache Tomcat Native library was not found on the java.library.path?

For Ubntu Users

 1. Install compilers
    #sudo apt-get install make
    #sudo apt-get install gcc

    2. Install openssl and development libraries
    #sudo apt-get install openssl
    #sudo apt-get install libssl-dev
    3. Install the APR package (Downloaded from http://apr.apache.org/)

    #tar -xzf apr-1.4.6.tar.gz
    #cd apr-1.4.6/
    #sudo ./configure
    #sudo make
    #sudo make install

    You should see the compiled file as
    /usr/local/apr/lib/libapr-1.a

    4. Download, compile and install Tomcat Native sourse package
    tomcat-native-1.1.27-src.tar.gz

    Extract the archive into some folder

    #tar -xzf tomcat-native-1.1.27-src.tar.gz
    #cd tomcat-native-1.1.27-src/jni/native
    #JAVA_HOME=/usr/lib/jvm/jdk1.7.0_21/
    #sudo ./configure --with-apr=/usr/local/apr --with-java-home=$JAVA_HOME
    #sudo make
    #sudo make install

    Now I have compiled Tomcat Native library in /usr/local/apr/libtcnative-1.so.0.1.27 and symbolic link file /usr/local/apr/@libtcnative-1.so pointed to the library

    5. Create or edit the $CATALINA_HOME/bin/setenv.sh file with following lines :
    export LD_LIBRARY_PATH='$LD_LIBRARY_PATH:/usr/local/apr/lib'

    6. Restart tomcat and see the desired result:

What is the difference between LATERAL and a subquery in PostgreSQL?

First, Lateral and Cross Apply is same thing. Therefore you may also read about Cross Apply. Since it was implemented in SQL Server for ages, you will find more information about it then Lateral.

Second, according to my understanding, there is nothing you can not do using subquery instead of using lateral. But:

Consider following query.

Select A.*
, (Select B.Column1 from B where B.Fk1 = A.PK and Limit 1)
, (Select B.Column2 from B where B.Fk1 = A.PK and Limit 1)
FROM A 

You can use lateral in this condition.

Select A.*
, x.Column1
, x.Column2
FROM A LEFT JOIN LATERAL (
  Select B.Column1,B.Column2,B.Fk1 from B  Limit 1
) x ON X.Fk1 = A.PK

In this query you can not use normal join, due to limit clause. Lateral or Cross Apply can be used when there is not simple join condition.

There are more usages for lateral or cross apply but this is most common one I found.

How to Display Selected Item in Bootstrap Button Dropdown Title

Another simple way (Bootstrap 4) to work with multiple dropdowns

    $('.dropdown-item').on('click',  function(){
        var btnObj = $(this).parent().siblings('button');
        $(btnObj).text($(this).text());
        $(btnObj).val($(this).text());
    });

rand() returns the same number each time the program is run

You are not seeding the number.

Use This:

#include <iostream>
#include <ctime>

using namespace std;

int main()
{
    srand(static_cast<unsigned int>(time(0)));
    cout << (rand() % 100) << endl;
    return 0;
}

You only need to seed it once though. Basically don't seed it every random number.

Try-catch speeding up my code?

Well, the way you're timing things looks pretty nasty to me. It would be much more sensible to just time the whole loop:

var stopwatch = Stopwatch.StartNew();
for (int i = 1; i < 100000000; i++)
{
    Fibo(100);
}
stopwatch.Stop();
Console.WriteLine("Elapsed time: {0}", stopwatch.Elapsed);

That way you're not at the mercy of tiny timings, floating point arithmetic and accumulated error.

Having made that change, see whether the "non-catch" version is still slower than the "catch" version.

EDIT: Okay, I've tried it myself - and I'm seeing the same result. Very odd. I wondered whether the try/catch was disabling some bad inlining, but using [MethodImpl(MethodImplOptions.NoInlining)] instead didn't help...

Basically you'll need to look at the optimized JITted code under cordbg, I suspect...

EDIT: A few more bits of information:

  • Putting the try/catch around just the n++; line still improves performance, but not by as much as putting it around the whole block
  • If you catch a specific exception (ArgumentException in my tests) it's still fast
  • If you print the exception in the catch block it's still fast
  • If you rethrow the exception in the catch block it's slow again
  • If you use a finally block instead of a catch block it's slow again
  • If you use a finally block as well as a catch block, it's fast

Weird...

EDIT: Okay, we have disassembly...

This is using the C# 2 compiler and .NET 2 (32-bit) CLR, disassembling with mdbg (as I don't have cordbg on my machine). I still see the same performance effects, even under the debugger. The fast version uses a try block around everything between the variable declarations and the return statement, with just a catch{} handler. Obviously the slow version is the same except without the try/catch. The calling code (i.e. Main) is the same in both cases, and has the same assembly representation (so it's not an inlining issue).

Disassembled code for fast version:

 [0000] push        ebp
 [0001] mov         ebp,esp
 [0003] push        edi
 [0004] push        esi
 [0005] push        ebx
 [0006] sub         esp,1Ch
 [0009] xor         eax,eax
 [000b] mov         dword ptr [ebp-20h],eax
 [000e] mov         dword ptr [ebp-1Ch],eax
 [0011] mov         dword ptr [ebp-18h],eax
 [0014] mov         dword ptr [ebp-14h],eax
 [0017] xor         eax,eax
 [0019] mov         dword ptr [ebp-18h],eax
*[001c] mov         esi,1
 [0021] xor         edi,edi
 [0023] mov         dword ptr [ebp-28h],1
 [002a] mov         dword ptr [ebp-24h],0
 [0031] inc         ecx
 [0032] mov         ebx,2
 [0037] cmp         ecx,2
 [003a] jle         00000024
 [003c] mov         eax,esi
 [003e] mov         edx,edi
 [0040] mov         esi,dword ptr [ebp-28h]
 [0043] mov         edi,dword ptr [ebp-24h]
 [0046] add         eax,dword ptr [ebp-28h]
 [0049] adc         edx,dword ptr [ebp-24h]
 [004c] mov         dword ptr [ebp-28h],eax
 [004f] mov         dword ptr [ebp-24h],edx
 [0052] inc         ebx
 [0053] cmp         ebx,ecx
 [0055] jl          FFFFFFE7
 [0057] jmp         00000007
 [0059] call        64571ACB
 [005e] mov         eax,dword ptr [ebp-28h]
 [0061] mov         edx,dword ptr [ebp-24h]
 [0064] lea         esp,[ebp-0Ch]
 [0067] pop         ebx
 [0068] pop         esi
 [0069] pop         edi
 [006a] pop         ebp
 [006b] ret

Disassembled code for slow version:

 [0000] push        ebp
 [0001] mov         ebp,esp
 [0003] push        esi
 [0004] sub         esp,18h
*[0007] mov         dword ptr [ebp-14h],1
 [000e] mov         dword ptr [ebp-10h],0
 [0015] mov         dword ptr [ebp-1Ch],1
 [001c] mov         dword ptr [ebp-18h],0
 [0023] inc         ecx
 [0024] mov         esi,2
 [0029] cmp         ecx,2
 [002c] jle         00000031
 [002e] mov         eax,dword ptr [ebp-14h]
 [0031] mov         edx,dword ptr [ebp-10h]
 [0034] mov         dword ptr [ebp-0Ch],eax
 [0037] mov         dword ptr [ebp-8],edx
 [003a] mov         eax,dword ptr [ebp-1Ch]
 [003d] mov         edx,dword ptr [ebp-18h]
 [0040] mov         dword ptr [ebp-14h],eax
 [0043] mov         dword ptr [ebp-10h],edx
 [0046] mov         eax,dword ptr [ebp-0Ch]
 [0049] mov         edx,dword ptr [ebp-8]
 [004c] add         eax,dword ptr [ebp-1Ch]
 [004f] adc         edx,dword ptr [ebp-18h]
 [0052] mov         dword ptr [ebp-1Ch],eax
 [0055] mov         dword ptr [ebp-18h],edx
 [0058] inc         esi
 [0059] cmp         esi,ecx
 [005b] jl          FFFFFFD3
 [005d] mov         eax,dword ptr [ebp-1Ch]
 [0060] mov         edx,dword ptr [ebp-18h]
 [0063] lea         esp,[ebp-4]
 [0066] pop         esi
 [0067] pop         ebp
 [0068] ret

In each case the * shows where the debugger entered in a simple "step-into".

EDIT: Okay, I've now looked through the code and I think I can see how each version works... and I believe the slower version is slower because it uses fewer registers and more stack space. For small values of n that's possibly faster - but when the loop takes up the bulk of the time, it's slower.

Possibly the try/catch block forces more registers to be saved and restored, so the JIT uses those for the loop as well... which happens to improve the performance overall. It's not clear whether it's a reasonable decision for the JIT to not use as many registers in the "normal" code.

EDIT: Just tried this on my x64 machine. The x64 CLR is much faster (about 3-4 times faster) than the x86 CLR on this code, and under x64 the try/catch block doesn't make a noticeable difference.

Freeze screen in chrome debugger / DevTools panel for popover inspection?

  1. Right click anywhere inside Elements Tab
  2. Choose Breakon... > subtree modifications
  3. Trigger the popup you want to see and it will freeze if it see changes in the DOM
  4. If you still don't see the popup, click Step over the next function(F10) button beside Resume(F8) in the upper top center of the chrome until you freeze the popup you want to see.

C#: New line and tab characters in strings

It depends on if you mean '\n' (linefeed) or '\r\n' (carriage return + linefeed). The former is not the Windows default and will not show properly in some text editors (like Notepad).

You can do

sb.Append(Environment.NewLine);
sb.Append("\t");

or

sb.Append("\r\n\t");

Encrypting & Decrypting a String in C#

UPDATE 23/Dec/2015: Since this answer seems to be getting a lot of upvotes, I've updated it to fix silly bugs and to generally improve the code based upon comments and feedback. See the end of the post for a list of specific improvements.

As other people have said, Cryptography is not simple so it's best to avoid "rolling your own" encryption algorithm.

You can, however, "roll your own" wrapper class around something like the built-in RijndaelManaged cryptography class.

Rijndael is the algorithmic name of the current Advanced Encryption Standard, so you're certainly using an algorithm that could be considered "best practice".

The RijndaelManaged class does indeed normally require you to "muck about" with byte arrays, salts, keys, initialization vectors etc. but this is precisely the kind of detail that can be somewhat abstracted away within your "wrapper" class.

The following class is one I wrote a while ago to perform exactly the kind of thing you're after, a simple single method call to allow some string-based plaintext to be encrypted with a string-based password, with the resulting encrypted string also being represented as a string. Of course, there's an equivalent method to decrypt the encrypted string with the same password.

Unlike the first version of this code, which used the exact same salt and IV values every time, this newer version will generate random salt and IV values each time. Since salt and IV must be the same between the encryption and decryption of a given string, the salt and IV is prepended to the cipher text upon encryption and extracted from it again in order to perform the decryption. The result of this is that encrypting the exact same plaintext with the exact same password gives and entirely different ciphertext result each time.

The "strength" of using this comes from using the RijndaelManaged class to perform the encryption for you, along with using the Rfc2898DeriveBytes function of the System.Security.Cryptography namespace which will generate your encryption key using a standard and secure algorithm (specifically, PBKDF2) based upon the string-based password you supply. (Note this is an improvement of the first version's use of the older PBKDF1 algorithm).

Finally, it's important to note that this is still unauthenticated encryption. Encryption alone provides only privacy (i.e. message is unknown to 3rd parties), whilst authenticated encryption aims to provide both privacy and authenticity (i.e. recipient knows message was sent by the sender).

Without knowing your exact requirements, it's difficult to say whether the code here is sufficiently secure for your needs, however, it has been produced to deliver a good balance between relative simplicity of implementation vs "quality". For example, if your "receiver" of an encrypted string is receiving the string directly from a trusted "sender", then authentication may not even be necessary.

If you require something more complex, and which offers authenticated encryption, check out this post for an implementation.

Here's the code:

using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Linq;

namespace EncryptStringSample
{
    public static class StringCipher
    {
        // This constant is used to determine the keysize of the encryption algorithm in bits.
        // We divide this by 8 within the code below to get the equivalent number of bytes.
        private const int Keysize = 256;

        // This constant determines the number of iterations for the password bytes generation function.
        private const int DerivationIterations = 1000;

        public static string Encrypt(string plainText, string passPhrase)
        {
            // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
            // so that the same Salt and IV values can be used when decrypting.  
            var saltStringBytes = Generate256BitsOfRandomEntropy();
            var ivStringBytes = Generate256BitsOfRandomEntropy();
            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = password.GetBytes(Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = 256;
                    symmetricKey.Mode = CipherMode.CBC;
                    symmetricKey.Padding = PaddingMode.PKCS7;
                    using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                            {
                                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                                cryptoStream.FlushFinalBlock();
                                // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                                var cipherTextBytes = saltStringBytes;
                                cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                                cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                                memoryStream.Close();
                                cryptoStream.Close();
                                return Convert.ToBase64String(cipherTextBytes);
                            }
                        }
                    }
                }
            }
        }

        public static string Decrypt(string cipherText, string passPhrase)
        {
            // Get the complete stream of bytes that represent:
            // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
            var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
            // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
            var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
            // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
            var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
            // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
            var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();

            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = password.GetBytes(Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = 256;
                    symmetricKey.Mode = CipherMode.CBC;
                    symmetricKey.Padding = PaddingMode.PKCS7;
                    using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream(cipherTextBytes))
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                            {
                                var plainTextBytes = new byte[cipherTextBytes.Length];
                                var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                                memoryStream.Close();
                                cryptoStream.Close();
                                return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                            }
                        }
                    }
                }
            }
        }

        private static byte[] Generate256BitsOfRandomEntropy()
        {
            var randomBytes = new byte[32]; // 32 Bytes will give us 256 bits.
            using (var rngCsp = new RNGCryptoServiceProvider())
            {
                // Fill the array with cryptographically secure random bytes.
                rngCsp.GetBytes(randomBytes);
            }
            return randomBytes;
        }
    }
}

The above class can be used quite simply with code similar to the following:

using System;

namespace EncryptStringSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter a password to use:");
            string password = Console.ReadLine();
            Console.WriteLine("Please enter a string to encrypt:");
            string plaintext = Console.ReadLine();
            Console.WriteLine("");

            Console.WriteLine("Your encrypted string is:");
            string encryptedstring = StringCipher.Encrypt(plaintext, password);
            Console.WriteLine(encryptedstring);
            Console.WriteLine("");

            Console.WriteLine("Your decrypted string is:");
            string decryptedstring = StringCipher.Decrypt(encryptedstring, password);
            Console.WriteLine(decryptedstring);
            Console.WriteLine("");

            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }
    }
}

(You can download a simple VS2013 sample solution (which includes a few unit tests) here).

UPDATE 23/Dec/2015: The list of specific improvements to the code are:

  • Fixed a silly bug where encoding was different between encrypting and decrypting. As the mechanism by which salt & IV values are generated has changed, encoding is no longer necessary.
  • Due to the salt/IV change, the previous code comment that incorrectly indicated that UTF8 encoding a 16 character string produces 32 bytes is no longer applicable (as encoding is no longer necessary).
  • Usage of the superseded PBKDF1 algorithm has been replaced with usage of the more modern PBKDF2 algorithm.
  • The password derivation is now properly salted whereas previously it wasn't salted at all (another silly bug squished).

7-zip commandline

7-Zip wants relative paths in the list file otherwise it will store only the filenames, causing duplicate file name error.

Assuming that your list contains full path names:

  • Edit the list file to remove drive prefix, C:\
  • Make sure you are in the root of the drive when you run 7Z to use the above list file.
  • Then it will store the paths and won't complain of the duplicate name. It wants relative paths in the list file.

If your list file has paths relative to another folder, you should be running 7Z from that folder.

Update: I noticed from another post above that the new 7-Zip has an -spf option that doesn't require the above steps. Not tested it yet but my steps are for earlier versions that do not have this option.

Convert an int to ASCII character

This will only work for int-digits 0-9, but your question seems to suggest that might be enough.

It works by adding the ASCII value of char '0' to the integer digit.

int i=6;
char c = '0'+i;  // now c is '6'

For example:

'0'+0 = '0'
'0'+1 = '1'
'0'+2 = '2'
'0'+3 = '3'

Edit

It is unclear what you mean, "work for alphabets"? If you want the 5th letter of the alphabet:

int i=5;
char c = 'A'-1 + i; // c is now 'E', the 5th letter.

Note that because in C/Ascii, A is considered the 0th letter of the alphabet, I do a minus-1 to compensate for the normally understood meaning of 5th letter.

Adjust as appropriate for your specific situation.
(and test-test-test! any code you write)

Sending JSON to PHP using ajax

You are tryng to send js array with js object format.

Instead of use

var a = new array();
a['something']=...

try:

var a = new Object();
a.something = ...

Remove CSS from a Div using JQuery

As a note, depending upon the property you may be able to set it to auto.

MySQL Workbench Edit Table Data is read only

MySQL will run in Read-Only mode when you fetch by joining two tables and columns from two tables are included in the result. Then you can't update the values directly.

Why, Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...?

The PHPUnit documentation says used to say to include/require PHPUnit/Framework.php, as follows:

require_once ('PHPUnit/Framework/TestCase.php');

UPDATE

As of PHPUnit 3.5, there is a built-in autoloader class that will handle this for you:

require_once 'PHPUnit/Autoload.php';

Thanks to Phoenix for pointing this out!

Does JSON syntax allow duplicate keys in an object?

From the standard (p. ii):

It is expected that other standards will refer to this one, strictly adhering to the JSON text format, while imposing restrictions on various encoding details. Such standards may require specific behaviours. JSON itself specifies no behaviour.

Further down in the standard (p. 2), the specification for a JSON object:

An object structure is represented as a pair of curly bracket tokens surrounding zero or more name/value pairs. A name is a string. A single colon token follows each name, separating the name from the value. A single comma token separates a value from a following name.

Diagram for JSON Object

It does not make any mention of duplicate keys being invalid or valid, so according to the specification I would safely assume that means they are allowed.

That most implementations of JSON libraries do not accept duplicate keys does not conflict with the standard, because of the first quote.

Here are two examples related to the C++ standard library. When deserializing some JSON object into a std::map it would make sense to refuse duplicate keys. But when deserializing some JSON object into a std::multimap it would make sense to accept duplicate keys as normal.

Better techniques for trimming leading zeros in SQL Server?

replace(ltrim(replace(Fieldname.TableName, '0', '')), '', '0')

The suggestion from Thomas G worked for our needs.

The field in our case was already string and only the leading zeros needed to be trimmed. Mostly it's all numeric but sometimes there are letters so the previous INT conversion would crash.

How to add a default include path for GCC in Linux?

Try setting C_INCLUDE_PATH (for C header files) or CPLUS_INCLUDE_PATH (for C++ header files).

As Ciro mentioned, CPATH will set the path for both C and C++ (and any other language).

More details in GCC's documentation.

How to change options of <select> with jQuery?

if we update <select> constantly and we need to save previous value :

var newOptions = {
    'Option 1':'value-1',
    'Option 2':'value-2'
};

var $el = $('#select');
var prevValue = $el.val();
$el.empty();
$.each(newOptions, function(key, value) {
   $el.append($('<option></option>').attr('value', value).text(key));
   if (value === prevValue){
       $el.val(value);
   }
});
$el.trigger('change');

How to use MySQL dump from a remote machine

Tried all the combinations here, but this worked for me:

mysqldump -u root -p --default-character-set=utf8mb4 [DATABASE TO BE COPIED NAME] > [NEW DATABASE NAME]

Plot size and resolution with R markdown, knitr, pandoc, beamer

I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:

```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```

Then all the images will be written as PDF files, and LaTeX will be happy.

Your second problem is you are mixing up the HTML units with LaTeX units in out.width / out.height. LaTeX and HTML are very different technologies. You should not expect \maxwidth to work in HTML, or 200px in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width / out.height (use fig.width / fig.height and let LaTeX use the original size).

Fastest way to set all values of an array?

As another option and for posterity I was looking into this recently and found a solution that allows a much shorter loop by handing some of the work off to the System class, which (if the JVM you're using is smart enough) can be turned into a memset operation:-

/*
 * initialize a smaller piece of the array and use the System.arraycopy 
 * call to fill in the rest of the array in an expanding binary fashion
 */
public static void bytefill(byte[] array, byte value) {
  int len = array.length;

  if (len > 0){
    array[0] = value;
  }

  //Value of i will be [1, 2, 4, 8, 16, 32, ..., len]
  for (int i = 1; i < len; i += i) {
    System.arraycopy(array, 0, array, i, ((len - i) < i) ? (len - i) : i);
  }
}

This solution was taken from the IBM research paper "Java server performance: A case study of building efficient, scalable Jvms" by R. Dimpsey, R. Arora, K. Kuiper.

Simplified explanation

As the comment suggests, this sets index 0 of the destination array to your value then uses the System class to copy one object i.e. the object at index 0 to index 1 then those two objects (index 0 and 1) into 2 and 3, then those four objects (0,1,2 and 3) into 4,5,6 and 7 and so on...

Efficiency (at the point of writing)

In a quick run through, grabbing the System.nanoTime() before and after and calculating a duration I came up with:-

  • This method : 332,617 - 390,262 ('highest - lowest' from 10 tests)
  • Float[] n = new Float[array.length]; //Fill with null : 666,650
  • Setting via loop : 3,743,488 - 9,767,744 ('highest - lowest' from 10 tests)
  • Arrays.fill : 12,539,336

The JVM and JIT compilation

It should be noted that as the JVM and JIT evolves, this approach may well become obsolete as library and runtime optimisations could reach or even exceed these numbers simply using fill(). At the time of writing, this was the fastest option I had found. It has been mentioned this might not be the case now but I have not checked. This is the beauty and the curse of Java.

Twitter Bootstrap tabs not working: when I click on them nothing happens

Just copy the script tag for adding the bootstrap.js from the head section to the end of the body. Then everything should work fine even without the scripts to activate the tabs.

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

Ok - my case was not strictly related to this question, but I ended up on this page when Googling for the same exception; I queried an SQL database with LINQ when I got this exception.

private Table<SubscriptionModel> m_subscriptionsSql;
var query = from SubscriptionModel subscription in m_subscriptionsSql ...

Turned out I forgot to initialize my Table instance variable, that I used in the LINQ query.

m_subscriptionsSql = GetTable<SubscriptionModel>();

jquery get height of iframe content when loaded

This is my ES6 friendly no-jquery take

document.querySelector('iframe').addEventListener('load', function() {
    const iframeBody = this.contentWindow.document.body;
    const height = Math.max(iframeBody.scrollHeight, iframeBody.offsetHeight);
    this.style.height = `${height}px`;
});

Where does PHP's error log reside in XAMPP?

Look in your configuration file and search for the error_log setting. Or use phpinfo() to find this setting.

What are DDL and DML?

DML is abbreviation of Data Manipulation Language. It is used to retrieve, store, modify, delete, insert and update data in database.

Examples: SELECT, UPDATE, INSERT statements


DDL is abbreviation of Data Definition Language. It is used to create and modify the structure of database objects in database.

Examples: CREATE, ALTER, DROP statements

Visit this site for more info: http://blog.sqlauthority.com/2008/01/15/sql-server-what-is-dml-ddl-dcl-and-tcl-introduction-and-examples/

maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

You could also use an extra function like:

    function checkFileType(filename, typeRegEx) {
        if (filename.length < 4 || typeRegEx.length < 1) return false;
        var filenameParts = filename.split('.');
        if (filenameParts.length < 2) return false;
        var fileExtension = filenameParts[filenameParts.length - 1];
        return typeRegEx.test('.' + fileExtension);
    }

BAT file to map to network drive without running as admin

This .vbs code creates a .bat file with the current mapped network drives. Then, just put the created file into the machine which you want to re-create the mappings and double-click it. It will try to create all mappings using the same drive letters (errors can occur if any letter is in use). This method also can be used as a backup of the current mappings. Save the code bellow as a .vbs file (e.g. Mappings.vbs) and double-click it.

' ********** My Code **********
Set wshShell = CreateObject( "WScript.Shell" )

' ********** Get ComputerName
strComputer = wshShell.ExpandEnvironmentStrings( "%COMPUTERNAME%" )

' ********** Get Domain 
sUserDomain = createobject("wscript.network").UserDomain

Set Connect = GetObject("winmgmts://"&strComputer)
Set WshNetwork = WScript.CreateObject("WScript.Network")
Set oDrives = WshNetwork.EnumNetworkDrives
Set oPrinters = WshNetwork.EnumPrinterConnections

' ********** Current Path
sCurrentPath = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)

' ********** Blank the report message
strMsg = ""

' ********** Set objects 
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objWbem = GetObject("winmgmts:")
Set objRegistry = GetObject("winmgmts://" & strComputer & "/root/default:StdRegProv")

' ********** Get UserName
sUser = CreateObject("WScript.Network").UserName

' ********** Print user and computer
'strMsg = strMsg & "    User: " & sUser & VbCrLf
'strMsg = strMsg & "Computer: " & strComputer & VbCrLf & VbCrLf

strMsg = strMsg & "###  COPIED FROM " & strComputer & " ###" & VbCrLf& VbCrLf
strMsg = strMsg & "@echo off" & vbCrLf

For i = 0 to oDrives.Count - 1 Step 2
    strMsg = strMsg & "net use " & oDrives.Item(i) & " " & oDrives.Item(i+1) & " /user:" & sUserDomain & "\" & sUser & " /persistent:yes" & VbCrLf
Next
strMsg = strMsg & ":exit" & VbCrLf
strMsg = strMsg & "@pause" & VbCrLf

' ********** write the file to disk.
strDirectory = sCurrentPath 
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(strDirectory) Then
    ' Procede
Else
    Set objFolder = objFSO.CreateFolder(strDirectory)
End if

' ********** Calculate date serial for filename **********
intMonth = month(now)
if intMonth < 10 then
    strThisMonth = "0" & intMonth
else
    strThisMonth = intMOnth
end if
intDay = Day(now)
if intDay < 10 then
    strThisDay = "0" & intDay
else
    strThisDay = intDay
end if
strFilenameDateSerial = year(now) & strThisMonth & strThisDay
    sFileName = strDirectory & "\" & strComputer & "_" & sUser & "_MappedDrives" & "_" & strFilenameDateSerial & ".bat"
    Set objFile = objFSO.CreateTextFile(sFileName,True) 
objFile.Write strMsg & vbCrLf

' ********** Ask to view file
strFinish = "End: A .bat was generated. " & VbCrLf & "Copy the generated file  (" & sFileName & ")  into the machine where you want to recreate the mappings and double-click it." & VbCrLf & VbCrLf 
MsgBox(strFinish)

How to make the background image to fit into the whole page without repeating using plain css?

background:url(bgimage.jpg) no-repeat; background-size: cover;

This did the trick

C# nullable string error

System.String is a reference type and already "nullable".

Nullable<T> and the ? suffix are for value types such as Int32, Double, DateTime, etc.

What's the difference between <b> and <strong>, <i> and <em>?

I'm going to hazard a historical and practical hot take here:

Yes, according to specifications, <strong> had a semantic meaning in HTML4 and <b> had a strictly presentational meaning.

Yes, when HTML5 came along, new semantic meaning that was slightly different was introduced for b and i.

Yes, the W3C recommends — basically — TL,DR; don't use b and i.

You should always bear in mind that the content of a b element may not always be bold, and that of an i element may not always be italic. The actual style is dependent on the CSS style definitions. You should also bear in mind that bold and italic may not be the preferred style for content in certain languages. You should not use b and i tags if there is a more descriptive and relevant tag available.

BUT:

The real world internet has massive loads of existing HTML that is never going to get updated. The real world internet has to account for content generated and copy and pasted between a vast network of software and CMS systems that all have different developer teams and were built in different eras.

So if you're writing HTML or building a system that writes HTML for other people — sure — definitely use <strong> instead of <b> to mean "strongly emphasized" because it's more semantically correct.

But really, the on-the-ground reality is that the semantic and stylistic meaning of <strong> and <b> have merged over time out of necessity.

If I'm building a CMS that allows any pasting of styled text, I need to plan both for people who are pasting in <b> and mean "strongly emphasized" and for people who are pasting in <strong> and mean "make this text bold". It might not be "right", but it's how the real world works at this moment in time.

And so, if I'm writing a stylesheet for that site, I'm probably going to end up writing some styles that look like this:

b,
strong {
  font-weight: 700;
  /* ... more styles here */
}

i,
em {
  font-style: italic;
  /* ... more styles here */
}

Or, I'm going to rely on the browser defaults, which do the same thing as the code above in every modern browser I know of.

Or, I might be one of probably millions of sites that use normalize.css, which takes care to ensure that b and strong are treated the same.

There's such a massive ocean of HTML out there in the world already that works off of this expectation, I just can't imagine that b will EVER be depreciated in favor of strong or that browsers will ever start displaying them differently by default.

So that's it. That's my hot take on semantics, history and the real world. Are b/i and strong/em the same? No. Will they probably both exist and be treated as identical in almost every situation until the collapse of modern civilization? I think, yes.

Difference between virtual and abstract methods

Virtual methods have an implementation and provide the derived classes with the option of overriding it. Abstract methods do not provide an implementation and force the derived classes to override the method.

So, abstract methods have no actual code in them, and subclasses HAVE TO override the method. Virtual methods can have code, which is usually a default implementation of something, and any subclasses CAN override the method using the override modifier and provide a custom implementation.

public abstract class E
{
    public abstract void AbstractMethod(int i);

    public virtual void VirtualMethod(int i)
    {
        // Default implementation which can be overridden by subclasses.
    }
}

public class D : E
{
    public override void AbstractMethod(int i)
    {
        // You HAVE to override this method
    }
    public override void VirtualMethod(int i)
    {
        // You are allowed to override this method.
    }
}

Only get hash value using md5sum (without filename)

md5="$(md5sum "${my_iso_file}")"
md5="${md5%% *}" # remove the first space and everything after it
echo "${md5}"

Check if property has attribute

This can now be done without expression trees and extension methods in a type safe manner with the new C# feature nameof() like this:

Attribute.IsDefined(typeof(YourClass).GetProperty(nameof(YourClass.Id)), typeof(IsIdentity));

nameof() was introduced in C# 6

Creating a singleton in Python

You probably never need a singleton in Python. Just define all your data and functions in a module and you have a de facto singleton:

import datetime
file_name=None

def set_file_name(new_file_name: str):
    global file_name
    file_name=new_file_name

def write(message: str):
    global file_name
    if file_name:
        with open(file_name, 'a+') as f:
            f.write("{} {}\n".format(datetime.datetime.now(), message))
    else:
        print("LOG: {}", message)

To use:

    import log
    log.set_file_name("debug.log")
    log.write("System starting")
    ...

If you really absolutely have to have a singleton class then I'd go with:

    class My_Singleton(object):
        def foo(self):
            pass

    my_singleton = My_Singleton()

To use:

    from mysingleton import my_singleton
    my_singleton.foo()

where mysingleton.py is your filename that My_Singleton is defined in. This works because after the first time a file is imported, Python doesn't re-execute the code.

get value from DataTable

You can try changing it to this:

If myTableData.Rows.Count > 0 Then
  For i As Integer = 0 To myTableData.Rows.Count - 1
    ''Dim DataType() As String = myTableData.Rows(i).Item(1)
    ListBox2.Items.Add(myTableData.Rows(i)(1))
  Next
End If

Note: Your loop needs to be one less than the row count since it's a zero-based index.

How to convert an integer to a string in any base?

def dec_to_radix(input, to_radix=2, power=None):
    if not isinstance(input, int):
        raise TypeError('Not an integer!')
    elif power is None:
        power = 1

    if input == 0:
        return 0
    else:
        remainder = input % to_radix**power
        digit = str(int(remainder/to_radix**(power-1)))
        return int(str(dec_to_radix(input-remainder, to_radix, power+1)) + digit)

def radix_to_dec(input, from_radix):
    if not isinstance(input, int):
        raise TypeError('Not an integer!')
    return sum(int(digit)*(from_radix**power) for power, digit in enumerate(str(input)[::-1]))

def radix_to_radix(input, from_radix=10, to_radix=2, power=None):
    dec = radix_to_dec(input, from_radix)
    return dec_to_radix(dec, to_radix, power)

Save Screen (program) output to a file

A different answer if you need to save the output of your whole scrollback buffer from an already actively running screen:

Ctrl-a [ g SPACE G $ >.

This will save your whole buffer to /tmp/screen-exchange

What is the difference between static_cast<> and C style casting?

In short:

  1. static_cast<>() gives you a compile time checking ability, C-Style cast doesn't.
  2. static_cast<>() is more readable and can be spotted easily anywhere inside a C++ source code, C_Style cast is'nt.
  3. Intentions are conveyed much better using C++ casts.

More Explanation:

The static cast performs conversions between compatible types. It is similar to the C-style cast, but is more restrictive. For example, the C-style cast would allow an integer pointer to point to a char.

char c = 10;       // 1 byte
int *p = (int*)&c; // 4 bytes

Since this results in a 4-byte pointer ( a pointer to 4-byte datatype) pointing to 1 byte of allocated memory, writing to this pointer will either cause a run-time error or will overwrite some adjacent memory.

*p = 5; // run-time error: stack corruption

In contrast to the C-style cast, the static cast will allow the compiler to check that the pointer and pointee data types are compatible, which allows the programmer to catch this incorrect pointer assignment during compilation.

int *q = static_cast<int*>(&c); // compile-time error

You can also check this page on more explanation on C++ casts : Click Here

What are the differences between the different saving methods in Hibernate?

This link explains in good manner :

http://www.stevideter.com/2008/12/07/saveorupdate-versus-merge-in-hibernate/

We all have those problems that we encounter just infrequently enough that when we see them again, we know we’ve solved this, but can’t remember how.

The NonUniqueObjectException thrown when using Session.saveOrUpdate() in Hibernate is one of mine. I’ll be adding new functionality to a complex application. All my unit tests work fine. Then in testing the UI, trying to save an object, I start getting an exception with the message “a different object with the same identifier value was already associated with the session.” Here’s some example code from Java Persistence with Hibernate.

            Session session = sessionFactory1.openSession();
            Transaction tx = session.beginTransaction();
            Item item = (Item) session.get(Item.class, new Long(1234));
            tx.commit();
            session.close(); // end of first session, item is detached

            item.getId(); // The database identity is "1234"
            item.setDescription("my new description");
            Session session2 = sessionFactory.openSession();
            Transaction tx2 = session2.beginTransaction();
            Item item2 = (Item) session2.get(Item.class, new Long(1234));
            session2.update(item); // Throws NonUniqueObjectException
            tx2.commit();
            session2.close();

To understand the cause of this exception, it’s important to understand detached objects and what happens when you call saveOrUpdate() (or just update()) on a detached object.

When we close an individual Hibernate Session, the persistent objects we are working with are detached. This means the data is still in the application’s memory, but Hibernate is no longer responsible for tracking changes to the objects.

If we then modify our detached object and want to update it, we have to reattach the object. During that reattachment process, Hibernate will check to see if there are any other copies of the same object. If it finds any, it has to tell us it doesn’t know what the “real” copy is any more. Perhaps other changes were made to those other copies that we expect to be saved, but Hibernate doesn’t know about them, because it wasn’t managing them at the time.

Rather than save possibly bad data, Hibernate tells us about the problem via the NonUniqueObjectException.

So what are we to do? In Hibernate 3, we have merge() (in Hibernate 2, use saveOrUpdateCopy()). This method will force Hibernate to copy any changes from other detached instances onto the instance you want to save, and thus merges all the changes in memory before the save.

        Session session = sessionFactory1.openSession();
        Transaction tx = session.beginTransaction();
        Item item = (Item) session.get(Item.class, new Long(1234));
        tx.commit();
        session.close(); // end of first session, item is detached

        item.getId(); // The database identity is "1234"
        item.setDescription("my new description");
        Session session2 = sessionFactory.openSession();
        Transaction tx2 = session2.beginTransaction();
        Item item2 = (Item) session2.get(Item.class, new Long(1234));
        Item item3 = session2.merge(item); // Success!
        tx2.commit();
        session2.close();

It’s important to note that merge returns a reference to the newly updated version of the instance. It isn’t reattaching item to the Session. If you test for instance equality (item == item3), you’ll find it returns false in this case. You will probably want to work with item3 from this point forward.

It’s also important to note that the Java Persistence API (JPA) doesn’t have a concept of detached and reattached objects, and uses EntityManager.persist() and EntityManager.merge().

I’ve found in general that when using Hibernate, saveOrUpdate() is usually sufficient for my needs. I usually only need to use merge when I have objects that can have references to objects of the same type. Most recently, the cause of the exception was in the code validating that the reference wasn’t recursive. I was loading the same object into my session as part of the validation, causing the error.

Where have you encountered this problem? Did merge work for you or did you need another solution? Do you prefer to always use merge, or prefer to use it only as needed for specific cases

How to copy a dictionary and only edit the copy

i ran into a peculiar behavior when trying to deep copy dictionary property of class w/o assigning it to variable

new = copy.deepcopy(my_class.a) doesn't work i.e. modifying new modifies my_class.a

but if you do old = my_class.a and then new = copy.deepcopy(old) it works perfectly i.e. modifying new does not affect my_class.a

I am not sure why this happens, but hope it helps save some hours! :)

Import Certificate to Trusted Root but not to Personal [Command Line]

If there are multiple certificates in a pfx file (key + corresponding certificate and a CA certificate) then this command worked well for me:

certutil -importpfx c:\somepfx.pfx this works but still a password is needed to be typed in manually for private key. Including -p and "password" cause error too many arguments for certutil on XP

Easy way to dismiss keyboard?

Quick tip on how to dismiss the keyboard in iOS when a user touches anywhere on the screen outside of the UITextField or keyboard. Considering how much real estate the iOS keyboard can take up, it makes sense to have an easy and intuitive way for your users to dismiss the keyboard.

Here's a link

What is the difference between single and double quotes in SQL?

A simple rule for us to remember what to use in which case:

  • [S]ingle quotes are for [S]trings ; [D]ouble quotes are for [D]atabase identifiers;

In MySQL and MariaDB, the ` (backtick) symbol is the same as the " symbol. You can use " when your SQL_MODE has ANSI_QUOTES enabled.

How can I sort generic list DESC and ASC?

With Linq

var ascendingOrder = li.OrderBy(i => i);
var descendingOrder = li.OrderByDescending(i => i);

Without Linq

li.Sort((a, b) => a.CompareTo(b)); // ascending sort
li.Sort((a, b) => b.CompareTo(a)); // descending sort

Note that without Linq, the list itself is being sorted. With Linq, you're getting an ordered enumerable of the list but the list itself hasn't changed. If you want to mutate the list, you would change the Linq methods to something like

li = li.OrderBy(i => i).ToList();

Insert multiple rows with one query MySQL

$servername = "localhost";

$username = "username";

$password = "password";

$dbname = "myDB";


// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]');";

$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', '[email protected]');";

$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')";


 if ($conn->multi_query($sql) === TRUE) {

  echo "New records created successfully";

 } else {

   echo "Error: " . $sql . "<br>" . $conn->error;

}

$conn->close();

Source W3schools

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

If you're using the PageFactory pattern or already have a reference to your WebElement, then you probably want to set the attribute, using your existing reference to the WebElement. (Rather than doing a document.getElementById(...) in your javascript)

The following sample allows you to set the attribute, using your existing WebElement reference.

Code Snippet

import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.FindBy;

public class QuickTest {

    RemoteWebDriver driver;

    @FindBy(id = "foo")
    private WebElement username;

    public void exampleUsage(RemoteWebDriver driver) {
        setAttribute(username, "attr", "10");
        setAttribute(username, "value", "bar");
    }

    public void setAttribute(WebElement element, String attName, String attValue) {
        driver.executeScript("arguments[0].setAttribute(arguments[1], arguments[2]);", 
                element, attName, attValue);
    }
}

Convert char array to single int?

Ascii string to integer conversion is done by the atoi() function.

Spring expected at least 1 bean which qualifies as autowire candidate for this dependency

If there is an interface anywhere in the ThreadProvider hierarchy try putting the name of the Interface as the type of your service provider, eg. if you have say this structure:

public class ThreadProvider implements CustomInterface{
...
}

Then in your controller try this:

@Controller
public class ChiusuraController {

    @Autowired
    private CustomInterface chiusuraProvider;
}

The reason why this is happening is, in your first case when you DID NOT have ChiusuraProvider extend ThreadProvider Spring probably was underlying creating a CGLIB based proxy for you(to handle the @Transaction).

When you DID extend from ThreadProvider assuming that ThreadProvider extends some interface, Spring in that case creates a Java Dynamic Proxy based Proxy, which would appear to be an implementation of that interface instead of being of ChisuraProvider type.

If you absolutely need to use ChisuraProvider you can try AspectJ as an alternative or force CGLIB based proxy in the case with ThreadProvider also this way:

<aop:aspectj-autoproxy proxy-target-class="true"/>

Here is some more reference on this from the Spring Reference site: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/classic-aop-spring.html#classic-aop-pfb

How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

Note: This answer was for a previous version of this question where the question asker was trying to use JavaScript to apply css styles… which can simply be done with CSS.

A simple css-only solution.

For applying basic styles, CSS is simpler and more performant that JS solutions 99% of the time. (Though more modern CSS-in-JS solutions — eg. React Components, etc — are arguably more maintainable.)

Run this code snippet to see it in action…

_x000D_
_x000D_
.hover-button .hover-button--on,_x000D_
.hover-button:hover .hover-button--off {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.hover-button:hover .hover-button--on {_x000D_
  display: inline;_x000D_
}
_x000D_
<button class='hover-button'>_x000D_
  <span class='hover-button--off'>Default</span>_x000D_
  <span class='hover-button--on'>Hover!</span>_x000D_
</button>
_x000D_
_x000D_
_x000D_

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

That particular package does not include assemblies for dotnet core, at least not at present. You may be able to build it for core yourself with a few tweaks to the project file, but I can't say for sure without diving into the source myself.

Get keys from HashMap in Java

To get Key and its value

e.g

private Map<String, Integer> team1 = new HashMap<String, Integer>();
  team1.put("United", 5);
  team1.put("Barcelona", 6);
    for (String key:team1.keySet()){
                     System.out.println("Key:" + key +" Value:" + team1.get(key)+" Count:"+Collections.frequency(team1, key));// Get Key and value and count
                }

Will print: Key: United Value:5 Key: Barcelona Value:6

How to get the current working directory in Java?

System.getProperty("java.class.path")

Convert an image to grayscale in HTML/CSS

Maybe this way help you

img {
    -webkit-filter: grayscale(100%); /* Chrome, Safari, Opera */
    filter: grayscale(100%);
}

w3schools.org

Converting HTML to XML

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

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

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

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

Sorting an IList in C#

You can use LINQ:

using System.Linq;

IList<Foo> list = new List<Foo>();
IEnumerable<Foo> sortedEnum = list.OrderBy(f=>f.Bar);
IList<Foo> sortedList = sortedEnum.ToList();

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:

JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'

The error message is pretty straightforward: getComputedStyle expects an Element as its first argument, and something else was passed to it.

If what you are really asking for is help with debugging your skin, you should make more of an effort to isolate the error.

adding classpath in linux

It's always advised to never destructively destroy an existing classpath unless you have a good reason.

The following line preserves the existing classpath and adds onto it.

export CLASSPATH="$CLASSPATH:foo.jar:../bar.jar"

How to check if a Java 8 Stream is empty?

I would simply use:

stream.count()>0

Performance differences between ArrayList and LinkedList

In a LinkedList the elements have a reference to the element before and after it. In an ArrayList the data structure is just an array.

  1. A LinkedList needs to iterate over N elements to get the Nth element. An ArrayList only needs to return element N of the backing array.

  2. The backing array needs to either be reallocated for the new size and the array copied over or every element after the deleted element needs to be moved up to fill the empty space. A LinkedList just needs to set the previous reference on the element after the removed to the one before the removed and the next reference on the element before the removed element to the element after the removed element. Longer to explain, but faster to do.

  3. Same reason as deletion here.

jQuery - passing value from one input to another

Get input1 data to send them to input2 immediately

<div>
<label>Input1</label>
 <input type="text" id="input1" value="">
</div>

</br>
<label>Input2</label>
<input type="text" id="input2" value="">

<script type="text/javascript">
        $(document).ready(function () {
            $("#input1").keyup(function () {
                var value = $(this).val();
                $("#input2").val(value);
            });
        });
</script>

How can I use the $index inside a ng-repeat to enable a class and show a DIV?

As johnnyynnoj mentioned ng-repeat creates a new scope. I would in fact use a function to set the value. See plunker

JS:

$scope.setSelected = function(selected) {
  $scope.selected = selected;
}

HTML:

{{ selected }}

<ul>
  <li ng-class="{current: selected == 100}">
     <a href ng:click="setSelected(100)">ABC</a>
  </li>
  <li ng-class="{current: selected == 101}">
     <a href ng:click="setSelected(101)">DEF</a>
  </li>
  <li ng-class="{current: selected == $index }" 
      ng-repeat="x in [4,5,6,7]">
     <a href ng:click="setSelected($index)">A{{$index}}</a>
  </li>
</ul>

<div  
  ng:show="selected == 100">
  100        
</div>
<div  
  ng:show="selected == 101">
  101        
</div>
<div ng-repeat="x in [4,5,6,7]" 
  ng:show="selected == $index">
  {{ $index }}        
</div>

UINavigationBar custom back button without title

 // add left bar button item

try this code:

- (void)viewDidLoad
{ 
    [super viewDidLoad];

   UIImage* image_back = [UIImage imageNamed:@"your_leftarrowImage.png"];
    CGRect backframe = CGRectMake(250, 9, 15,21);
    UIButton *backbutton = [[UIButton alloc] initWithFrame:backframe];
    [backbutton setBackgroundImage:image_back forState:UIControlStateNormal];
    [backbutton addTarget:self action:@selector(Btn_back:)
         forControlEvents:UIControlEventTouchUpInside];
    [backbutton setShowsTouchWhenHighlighted:YES];
    UIBarButtonItem *backbarbutton =[[UIBarButtonItem alloc] initWithCustomView:backbutton];
    self.navigationItem.leftBarButtonItem=backbarbutton;
    [backbutton release];

}
-(IBAction)Btn_back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];

}

A Generic error occurred in GDI+ in Bitmap.Save method

I had a different issue with the same exception.

In short:

Make sure that the Bitmap's object Stream is not being disposed before calling .Save .

Full story:

There was a method that returned a Bitmap object, built from a MemoryStream in the following way:

private Bitmap getImage(byte[] imageBinaryData){
    .
    .
    .
    Bitmap image;
    using (var stream = new MemoryStream(imageBinaryData))
    {
        image = new Bitmap(stream);
    }
    return image;
}

then someone used the returned image to save it as a file

image.Save(path);

The problem was that the original stream was already disposed when trying to save the image, throwing the GDI+ exeption.

A fix to this problem was to return the Bitmap without disposing the stream itself but the returned Bitmap object.

private Bitmap getImage(byte[] imageBinaryData){
   .
   .
   .
   Bitmap image;
   var stream = new MemoryStream(imageBinaryData))
   image = new Bitmap(stream);

   return image;
}

then:

using (var image = getImage(binData))
{
   image.Save(path);
}

How to check whether a file is empty or not?

if you have the file object, then

>>> import os
>>> with open('new_file.txt') as my_file:
...     my_file.seek(0, os.SEEK_END) # go to end of file
...     if my_file.tell(): # if current position is truish (i.e != 0)
...         my_file.seek(0) # rewind the file for later use 
...     else:
...         print "file is empty"
... 
file is empty

How to declare a variable in a PostgreSQL query

True, there is no vivid and unambiguous way to declare a single-value variable, what you can do is

with myVar as (select "any value really")

then, to get access to the value stored in this construction, you do

(select * from myVar)

for example

with var as (select 123)    
... where id = (select * from var)

Get file name from URL

One liner:

new File(uri.getPath).getName

Complete code (in a scala REPL):

import java.io.File
import java.net.URI

val uri = new URI("http://example.org/file.txt?whatever")

new File(uri.getPath).getName
res18: String = file.txt

Note: URI#gePath is already intelligent enough to strip off query parameters and the protocol's scheme. Examples:

new URI("http://example.org/hey/file.txt?whatever").getPath
res20: String = /hey/file.txt

new URI("hdfs:///hey/file.txt").getPath
res21: String = /hey/file.txt

new URI("file:///hey/file.txt").getPath
res22: String = /hey/file.txt

How to reliably open a file in the same directory as a Python script

Ok here is what I do

sys.argv is always what you type into the terminal or use as the file path when executing it with python.exe or pythonw.exe

For example you can run the file text.py several ways, they each give you a different answer they always give you the path that python was typed.

    C:\Documents and Settings\Admin>python test.py
    sys.argv[0]: test.py
    C:\Documents and Settings\Admin>python "C:\Documents and Settings\Admin\test.py"
    sys.argv[0]: C:\Documents and Settings\Admin\test.py

Ok so know you can get the file name, great big deal, now to get the application directory you can know use os.path, specifically abspath and dirname

    import sys, os
    print os.path.dirname(os.path.abspath(sys.argv[0]))

That will output this:

   C:\Documents and Settings\Admin\

it will always output this no matter if you type python test.py or python "C:\Documents and Settings\Admin\test.py"

The problem with using __file__ Consider these two files test.py

import sys
import os

def paths():
        print "__file__: %s" % __file__
        print "sys.argv: %s" % sys.argv[0]

        a_f = os.path.abspath(__file__)
        a_s = os.path.abspath(sys.argv[0])

        print "abs __file__: %s" % a_f
        print "abs sys.argv: %s" % a_s

if __name__ == "__main__":
    paths()

import_test.py

import test
import sys

test.paths()

print "--------"
print __file__
print sys.argv[0]

Output of "python test.py"

C:\Documents and Settings\Admin>python test.py
__file__: test.py
sys.argv: test.py
abs __file__: C:\Documents and Settings\Admin\test.py
abs sys.argv: C:\Documents and Settings\Admin\test.py

Output of "python test_import.py"

C:\Documents and Settings\Admin>python test_import.py
__file__: C:\Documents and Settings\Admin\test.pyc
sys.argv: test_import.py
abs __file__: C:\Documents and Settings\Admin\test.pyc
abs sys.argv: C:\Documents and Settings\Admin\test_import.py
--------
test_import.py
test_import.py

So as you can see file gives you always the python file it is being run from, where as sys.argv[0] gives you the file that you ran from the interpreter always. Depending on your needs you will need to choose which one best fits your needs.

INSERT INTO...SELECT for all MySQL columns

Addition to Mark Byers answer :

Sometimes you also want to insert Hardcoded details else there may be Unique constraint fail etc. So use following in such situation where you override some values of the columns.

INSERT INTO matrimony_domain_details (domain, type, logo_path)
SELECT 'www.example.com', type, logo_path
FROM matrimony_domain_details
WHERE id = 367

Here domain value is added by me me in Hardcoded way to get rid from Unique constraint.

Is not an enclosing class Java

No need to make the nested class as static but it must be public

public class Test {
    public static void main(String[] args) {
        Shape shape = new Shape();
        Shape s = shape.new Shape.ZShape();
    }
}

What is the difference between URI, URL and URN?

URI (Uniform Resource Identifier) according to Wikipedia:

a string of characters used to identify a resource.

URL (Uniform Resource Locator) is a URI that implies an interaction mechanism with resource. for example https://www.google.com specifies the use of HTTP as the interaction mechanism. Not all URIs need to convey interaction-specific information.

URN (Uniform Resource Name) is a specific form of URI that has urn as it's scheme. For more information about the general form of a URI refer to https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Syntax

IRI (International Resource Identifier) is a revision to the definition of URI that allows us to use international characters in URIs.

Javascript Uncaught Reference error Function is not defined

Change the wrapping from "onload" to "No wrap - in <body>"

The function defined has a different scope.

jQuery UI - Draggable is not a function?

Make sure your code follows this order-

_x000D_
_x000D_
<script src="jquery.min.js"></script>_x000D_
<script src="jquery-ui/jquery-ui.js"></script>
_x000D_
_x000D_
_x000D_

Where could I buy a valid SSL certificate?

Let's Encrypt is a free, automated, and open certificate authority made by the Internet Security Research Group (ISRG). It is sponsored by well-known organisations such as Mozilla, Cisco or Google Chrome. All modern browsers are compatible and trust Let's Encrypt.

All certificates are free (even wildcard certificates)! For security reasons, the certificates expire pretty fast (after 90 days). For this reason, it is recommended to install an ACME client, which will handle automatic certificate renewal.

There are many clients you can use to install a Let's Encrypt certificate:

Let’s Encrypt uses the ACME protocol to verify that you control a given domain name and to issue you a certificate. To get a Let’s Encrypt certificate, you’ll need to choose a piece of ACME client software to use. - https://letsencrypt.org/docs/client-options/

Letsencrypt add domain to existing certificate

this worked for me

 sudo letsencrypt certonly -a webroot --webroot-path=/var/www/html -d
 domain.com -d www.domain.com

numpy.where() detailed, step-by-step explanation / examples

After fiddling around for a while, I figured things out, and am posting them here hoping it will help others.

Intuitively, np.where is like asking "tell me where in this array, entries satisfy a given condition".

>>> a = np.arange(5,10)
>>> np.where(a < 8)       # tell me where in a, entries are < 8
(array([0, 1, 2]),)       # answer: entries indexed by 0, 1, 2

It can also be used to get entries in array that satisfy the condition:

>>> a[np.where(a < 8)] 
array([5, 6, 7])          # selects from a entries 0, 1, 2

When a is a 2d array, np.where() returns an array of row idx's, and an array of col idx's:

>>> a = np.arange(4,10).reshape(2,3)
array([[4, 5, 6],
       [7, 8, 9]])
>>> np.where(a > 8)
(array(1), array(2))

As in the 1d case, we can use np.where() to get entries in the 2d array that satisfy the condition:

>>> a[np.where(a > 8)] # selects from a entries 0, 1, 2

array([9])


Note, when a is 1d, np.where() still returns an array of row idx's and an array of col idx's, but columns are of length 1, so latter is empty array.

How should I escape commas and speech marks in CSV files so they work in Excel?

We eventually found the answer to this.

Excel will only respect the escaping of commas and speech marks if the column value is NOT preceded by a space. So generating the file without spaces like this...

Reference,Title,Description
1,"My little title","My description, which may contain ""speech marks"" and commas."
2,"My other little title","My other description, which may also contain ""speech marks"" and commas."

... fixed the problem. Hope this helps someone!

Return multiple values in JavaScript?

Best way for this is

function a(){
     var d=2;
     var c=3;
     var f=4;
     return {d:d,c:c,f:f}
}

Then use

a().f

return 4

in ES6 you can use this code

function a(){
      var d=2;
      var c=3;
      var f=4;
      return {d,c,f}
}

Error: free(): invalid next size (fast):

I encountered the same problem, even though I did not make any dynamic memory allocation in my program, but I was accessing a vector's index without allocating memory for it. So, if the same case, better allocate some memory using resize() and then access vector elements.