Programs & Examples On #Qt3

For issues relating to using the Qt framework, version 3.

Java Regex Capturing Groups

The issue you're having is with the type of quantifier. You're using a greedy quantifier in your first group (index 1 - index 0 represents the whole Pattern), which means it'll match as much as it can (and since it's any character, it'll match as many characters as there are in order to fulfill the condition for the next groups).

In short, your 1st group .* matches anything as long as the next group \\d+ can match something (in this case, the last digit).

As per the 3rd group, it will match anything after the last digit.

If you change it to a reluctant quantifier in your 1st group, you'll get the result I suppose you are expecting, that is, the 3000 part.

Note the question mark in the 1st group.

String line = "This order was placed for QT3000! OK?";
Pattern pattern = Pattern.compile("(.*?)(\\d+)(.*)");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
    System.out.println("group 1: " + matcher.group(1));
    System.out.println("group 2: " + matcher.group(2));
    System.out.println("group 3: " + matcher.group(3));
}

Output:

group 1: This order was placed for QT
group 2: 3000
group 3: ! OK?

More info on Java Pattern here.

Finally, the capturing groups are delimited by round brackets, and provide a very useful way to use back-references (amongst other things), once your Pattern is matched to the input.

In Java 6 groups can only be referenced by their order (beware of nested groups and the subtlety of ordering).

In Java 7 it's much easier, as you can use named groups.

Update just one gem with bundler

bundler update --source gem-name will update the revision hash in Gemfile.lock which you can compare with the last commit hash of that git branch (master by default).

GIT remote: [email protected]:organization/repo-name.git revision: c810f4a29547b60ca8106b7a6b9a9532c392c954

can be found at github.com/organization/repo-name/commits/c810f4a2 (I used shorthand 8 character commit hash for the url)

How to debug (only) JavaScript in Visual Studio?

For debugging JavaScript code in VS2015, there is no need for

  1. Enabling script debugging in IE Options -> Advanced tab
  2. Writing debugger statement in JavaScript code

Attaching IE didn't work, but here is a workaround.

Select IE

enter image description here

and press F5. This will attach both worker process and IE as shown here- enter image description here

If you are not interested in debugging server code, detach it from Processes window. enter image description here

You will still face the slowness when you press F5 and all your server code compiles and loads up in VS. Note that you can detach and attach again the IE instance launched from VS. JavaScript breakpoints are hit the same way they are in server side code.

Alternative for <blink>

The solution below is interesting because it can be applied across multiple elements concomitantly and does not trigger an error when the element no longer exists on the page. The secret is that it is called passing as a parameter a function in which you must return the elements you want to be affected by the blink. Then this function is called back with each blink. HTML file below:

<!doctype>
<html>
    <head>
        <style>
            .blink {color: red}
        </style>
    </head>
    <body>
        <h1>Blink test</h1>
        <p>
            Brazil elected President <span class="blink">Bolsonaro</span> because he 
            was the only candidate who did not promise <span class="blink">free things</span>
            to the population. Previous politicians created an image that would 
            bring many benefits, but in the end, the state has been getting more and 
            more <span class="blink">burdened</span>. Brazil voted for the 
            realistic idea that <span class="blink">there is no free lunch</span>.
        </p>
    </body>
    <script>
    var blink =
        {
            interval_in_miliseconds:
                400,
            on:
                true,
            function_wich_returns_the_elements: 
                [],
            activate:
                function(function_wich_returns_the_elements)
                {
                    this.function_wich_returns_the_elements = function_wich_returns_the_elements;
                    setInterval(blink.change, blink.interval_in_miliseconds);
                },
            change:
                function()
                {   
                    blink.on = !blink.on;
                    var i, elements = [];
                    for (i in blink.function_wich_returns_the_elements)
                    {
                        elements = elements.concat(blink.function_wich_returns_the_elements[i]());
                    }
                    for (i in elements)
                    {
                        if (elements[i])
                        {
                            elements[i].style.opacity = blink.on ? 1 : .2;
                        }
                    }
                }
        };
    blink.activate
    (
        [
            function()
            {
                var 
                    i,
                    node_collection = document.getElementsByClassName('blink'),
                    elements = [];
                for (i = 0; i < node_collection.length; i++)
                {
                    elements.push(node_collection[i]);
                }
                return elements;
            }
        ]
    );
    </script>
</html>

What's the best CRLF (carriage return, line feed) handling strategy with Git?

--- UPDATE 3 --- (does not conflict with UPDATE 2)

Considering the case that windows users prefer working on CRLF and linux/mac users prefer working on LF on text files. Providing the answer from the perspective of a repository maintainer:

For me the best strategy(less problems to solve) is: keep all text files with LF inside git repo even if you are working on a windows-only project. Then give the freedom to clients to work on the line-ending style of their preference, provided that they pick a core.autocrlf property value that will respect your strategy (LF on repo) while staging files for commit.

Staging is what many people confuse when trying to understand how newline strategies work. It is essential to undestand the following points before picking the correct value for core.autocrlf property:

  • Adding a text file for commit (staging it) is like copying the file to another place inside .git/ sub-directory with converted line-endings (depending on core.autocrlf value on your client config). All this is done locally.
  • setting core.autocrlf is like providing an answer to the question (exact same question on all OS):
    • "Should git-client a. convert LF-to-CRLF when checking-out (pulling) the repo changes from the remote or b. convert CRLF-to-LF when adding a file for commit?" and the possible answers (values) are:
    • false: "do none of the above",
    • input: "do only b"
    • true: "do a and and b"
    • note that there is NO "do only a"

Fortunately

  • git client defaults (windows: core.autocrlf: true, linux/mac: core.autocrlf: false) will be compatible with LF-only-repo strategy.
    Meaning: windows clients will by default convert to CRLF when checking-out the repository and convert to LF when adding for commit. And linux clients will by default not do any conversions. This theoretically keeps your repo lf-only.

Unfortunately:

  • There might be GUI clients that do not respect the git core.autocrlf value
  • There might be people that don't use a value to respect your lf-repo strategy. E.g. they use core.autocrlf=false and add a file with CRLF for commit.

To detect ASAP non-lf text files committed by the above clients you can follow what is described on --- update 2 ---: (git grep -I --files-with-matches --perl-regexp '\r' HEAD, on a client compiled using: --with-libpcre flag)

And here is the catch:. I as a repo maintainer keep a git.autocrlf=input so that I can fix any wrongly committed files just by adding them again for commit. And I provide a commit text: "Fixing wrongly committed files".

As far as .gitattributes is concearned. I do not count on it, because there are more ui clients that do not understand it. I only use it to provide hints for text and binary files, and maybe flag some exceptional files that should everywhere keep the same line-endings:

*.java          text !eol # Don't do auto-detection. Treat as text (don't set any eol rule. use client's)
*.jpg           -text     # Don't do auto-detection. Treat as binary
*.sh            text eol=lf # Don't do auto-detection. Treat as text. Checkout and add with eol=lf
*.bat           text eol=crlf # Treat as text. Checkout and add with eol=crlf

Question: But why are we interested at all in newline handling strategy?

Answer: To avoid a single letter change commit, appear as a 5000-line change, just because the client that performed the change auto-converted the full file from crlf to lf (or the opposite) before adding it for commit. This can be rather painful when there is a conflict resolution involved. Or it could in some cases be the cause of unreasonable conflicts.


--- UPDATE 2 ---

The dafaults of git client will work in most cases. Even if you only have windows only clients, linux only clients or both. These are:

  • windows: core.autocrlf=true means convert lines to CRLF on checkout and convert lines to LF when adding files.
  • linux: core.autocrlf=input means don't convert lines on checkout (no need to since files are expected to be committed with LF) and convert lines to LF (if needed) when adding files. (-- update3 -- : Seems that this is false by default, but again it is fine)

The property can be set in different scopes. I would suggest explicitly setting in the --global scope, to avoid some IDE issues described at the end.

git config core.autocrlf
git config --global core.autocrlf
git config --system core.autocrlf
git config --local core.autocrlf
git config --show-origin core.autocrlf

Also I would strongly discourage using on windows git config --global core.autocrlf false (in case you have windows only clients) in contrast to what is proposed to git documentation. Setting to false will commit files with CRLF in the repo. But there is really no reason. You never know whether you will need to share the project with linux users. Plus it's one extra step for each client that joins the project instead of using defaults.

Now for some special cases of files (e.g. *.bat *.sh) which you want them to be checked-out with LF or with CRLF you can use .gitattributes

To sum-up for me the best practice is:

  • Make sure that every non-binary file is committed with LF on git repo (default behaviour).
  • Use this command to make sure that no files are committed with CRLF: git grep -I --files-with-matches --perl-regexp '\r' HEAD (Note: on windows clients works only through git-bash and on linux clients only if compiled using --with-libpcre in ./configure).
  • If you find any such files by executing the above command, correct them. This in involves (at least on linux):
    • set core.autocrlf=input (--- update 3 --)
    • change the file
    • revert the change(file is still shown as changed)
    • commit it
  • Use only the bare minimum .gitattributes
  • Instruct the users to set the core.autocrlf described above to its default values.
  • Do not count 100% on the presence of .gitattributes. git-clients of IDEs may ignore them or treat them differrently.

As said some things can be added in git attributes:

# Always checkout with LF
*.sh            text eol=lf
# Always checkout with CRLF
*.bat           text eol=crlf

I think some other safe options for .gitattributes instead of using auto-detection for binary files:

  • -text (e.g for *.zip or *.jpg files: Will not be treated as text. Thus no line-ending conversions will be attempted. Diff might be possible through conversion programs)
  • text !eol (e.g. for *.java,*.html: Treated as text, but eol style preference is not set. So client setting is used.)
  • -text -diff -merge (e.g for *.hugefile: Not treated as text. No diff/merge possible)

--- PREVIOUS UPDATE ---

One painful example of a client that will commit files wrongly:

netbeans 8.2 (on windows), will wrongly commit all text files with CRLFs, unless you have explicitly set core.autocrlf as global. This contradicts to the standard git client behaviour, and causes lots of problems later, while updating/merging. This is what makes some files appear different (although they are not) even when you revert.
The same behaviour in netbeans happens even if you have added correct .gitattributes to your project.

Using the following command after a commit, will at least help you detect early whether your git repo has line ending issues: git grep -I --files-with-matches --perl-regexp '\r' HEAD

I have spent hours to come up with the best possible use of .gitattributes, to finally realize, that I cannot count on it.
Unfortunately, as long as JGit-based editors exist (which cannot handle .gitattributes correctly), the safe solution is to force LF everywhere even on editor-level.

Use the following anti-CRLF disinfectants.

Parsing JSON array into java.util.List with Gson

I was able to get the list mapping to work with just using @SerializedName for all fields.. no logic around Type was necessary.

Running the code - in step #4 below - through the debugger, I am able to observe that the List<ContentImage> mGalleryImages object populated with the JSON data

Here's an example:

1. The JSON

   {
    "name": "Some House",
    "gallery": [
      {
        "description": "Nice 300sqft. den.jpg",
        "photo_url": "image/den.jpg"
      },
      {
        "description": "Floor Plan",
        "photo_url": "image/floor_plan.jpg"
      }
    ]
  }

2. Java class with the List

public class FocusArea {

    @SerializedName("name")
    private String mName;

    @SerializedName("gallery")
    private List<ContentImage> mGalleryImages;
}

3. Java class for the List items

public class ContentImage {

    @SerializedName("description")
    private String mDescription;

    @SerializedName("photo_url")
    private String mPhotoUrl;

    // getters/setters ..
}

4. The Java code that processes the JSON

    for (String key : focusAreaKeys) {

        JsonElement sectionElement = sectionsJsonObject.get(key);
        FocusArea focusArea = gson.fromJson(sectionElement, FocusArea.class);
    }

Matplotlib 2 Subplots, 1 Colorbar

You can simplify Joe Kington's code using the axparameter of figure.colorbar() with a list of axes. From the documentation:

ax

None | parent axes object(s) from which space for a new colorbar axes will be stolen. If a list of axes is given they will all be resized to make room for the colorbar axes.

import numpy as np
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, ncols=2)
for ax in axes.flat:
    im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)

fig.colorbar(im, ax=axes.ravel().tolist())

plt.show()

1

Start/Stop and Restart Jenkins service on Windows

Small hints for routine work.

Create a bat file, name it and use for exact run/stop/restart Jenkins service

#!/bin/bash
# go to Jenkins folder
cd C:\Program Files (x86)\Jenkins

#to stop:
jenkins.exe stop

#to start:
#jenkins.exe start

#to restart:
#jenkins.exe restart

How to identify all stored procedures referring a particular table

In management studio you can just right click to table and click to 'View Dependencies' enter image description here

than you can see a list of Objects that have dependencies with your table :enter image description here

How to manage a redirect request after a jQuery Ajax call

I resolved this issue like this:

Add a middleware to process response, if it is a redirect for an ajax request, change the response to a normal response with the redirect url.

class AjaxRedirect(object):
  def process_response(self, request, response):
    if request.is_ajax():
      if type(response) == HttpResponseRedirect:
        r = HttpResponse(json.dumps({'redirect': response['Location']}))
        return r
    return response

Then in ajaxComplete, if the response contains redirect, it must be a redirect, so change the browser's location.

$('body').ajaxComplete(function (e, xhr, settings) {
   if (xhr.status == 200) {
       var redirect = null;
       try {
           redirect = $.parseJSON(xhr.responseText).redirect;
           if (redirect) {
               window.location.href = redirect.replace(/\?.*$/, "?next=" + window.location.pathname);
           }
       } catch (e) {
           return;
       }
   }
}

Getting a POST variable

In addition to using Request.Form and Request.QueryString and depending on your specific scenario, it may also be useful to check the Page's IsPostBack property.

if (Page.IsPostBack)
{
  // HTTP Post
}
else
{
  // HTTP Get
}

How to query first 10 rows and next time query other 10 rows from table

SET @rownum = 0; 
SELECT sub.*, sub.rank as Rank
FROM
(
   SELECT *,  (@rownum := @rownum + 1) as rank
   FROM msgtable 
   WHERE cdate = '18/07/2012'
) sub
WHERE rank BETWEEN ((@PageNum - 1) * @PageSize + 1)
  AND (@PageNum * @PageSize)

Every time you pass the parameters @PageNum and the @PageSize to get the specific page you want. For exmple the first 10 rows would be @PageNum = 1 and @PageSize = 10

How do I create a new line in Javascript?

Try to write your code between the HTML pre tag.

%matplotlib line magic causes SyntaxError in Python script

If you include the following code at the top of your script, matplotlib will run inline when in an IPython environment (like jupyter, hydrogen atom plugin...), and it will still work if you launch the script directly via command line (matplotlib won't run inline, and the charts will open in a pop-ups as usual).

from IPython import get_ipython
ipy = get_ipython()
if ipy is not None:
    ipy.run_line_magic('matplotlib', 'inline')

path.join vs path.resolve with __dirname

const absolutePath = path.join(__dirname, some, dir);

vs.

const absolutePath = path.resolve(__dirname, some, dir);

path.join will concatenate __dirname which is the directory name of the current file concatenated with values of some and dir with platform-specific separator.

Whereas

path.resolve will process __dirname, some and dir i.e. from right to left prepending it by processing it.

If any of the values of some or dir corresponds to a root path then the previous path will be omitted and process rest by considering it as root

In order to better understand the concept let me explain both a little bit more detail as follows:-

The path.join and path.resolve are two different methods or functions of the path module provided by nodejs.

Where both accept a list of paths but the difference comes in the result i.e. how they process these paths.

path.join concatenates all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path. While the path.resolve() process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.

When no arguments supplied

The following example will help you to clearly understand both concepts:-

My filename is index.js and the current working directory is E:\MyFolder\Pjtz\node

const path = require('path');

console.log("path.join() : ", path.join());
// outputs .
console.log("path.resolve() : ", path.resolve());
// outputs current directory or equivalent to __dirname

Result

? node index.js
path.join() :  .
path.resolve() :  E:\MyFolder\Pjtz\node

path.resolve() method will output the absolute path whereas the path.join() returns . representing the current working directory if nothing is provided

When some root path is passed as arguments

const path=require('path');

console.log("path.join() : " ,path.join('abc','/bcd'));
console.log("path.resolve() : ",path.resolve('abc','/bcd'));

Result i

? node index.js
path.join() :  abc\bcd
path.resolve() :  E:\bcd

path.join() only concatenates the input list with platform-specific separator while the path.resolve() process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.

Add click event on div tag using javascript

Try this:

 var div = document.getElementsByClassName('drill_cursor')[0];

 div.addEventListener('click', function (event) {
     alert('Hi!');
 });

What REST PUT/POST/DELETE calls should return by a convention?

Overall, the conventions are “think like you're just delivering web pages”.

For a PUT, I'd return the same view that you'd get if you did a GET immediately after; that would result in a 200 (well, assuming the rendering succeeds of course). For a POST, I'd do a redirect to the resource created (assuming you're doing a creation operation; if not, just return the results); the code for a successful create is a 201, which is really the only HTTP code for a redirect that isn't in the 300 range.

I've never been happy about what a DELETE should return (my code currently produces an HTTP 204 and an empty body in this case).

How to send cookies in a post request with the Python Requests library?

If you want to pass the cookie to the browser, you have to append to the headers to be sent back. If you're using wsgi:

import requests
...


def application(environ, start_response):
    cookie = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}
    response_headers = [('Content-type', 'text/plain')]
    response_headers.append(('Set-Cookie',cookie))
...

    return [bytes(post_env),response_headers]

I'm successfully able to authenticate with Bugzilla and TWiki hosted on the same domain my python wsgi script is running by passing auth user/password to my python script and pass the cookies to the browser. This allows me to open the Bugzilla and TWiki pages in the same browser and be authenticated. I'm trying to do the same with SuiteCRM but i'm having trouble with SuiteCRM accepting the session cookies obtained from the python script even though it has successfully authenticated.

Convert NaN to 0 in javascript

_x000D_
_x000D_
    var i = [NaN, 1,2,3];

    var j = i.map(i =>{ return isNaN(i) ? 0 : i});
    
    console.log(j)
_x000D_
_x000D_
_x000D_

With block equivalent in C#?

hmm. I have never used VB.net in any depth, so I'm making an assumption here, but I think the 'using' block might be close to what you want.

using defines a block scope for a variable, see the example below

using ( int temp = someFunction(param1) ) {
   temp++;  // this works fine
}

temp++; // this blows up as temp is out of scope here and has been disposed

Here is an article from Microsoft that explains a bit more


EDIT: yeah, this answer is wrong - the original assumption was incorrect. VB's 'WITH' is more like the new C# object initialisers:

var yourVariable = new yourObject { param1 = 20, param2 = "some string" };

Adjust table column width to content size

If you want the table to still be 100% then set one of the columns to have a width:100%; That will extend that column to fill the extra space and allow the other columns to keep their auto width :)

'No JUnit tests found' in Eclipse

junit4 require that test classname should be use Test as suffix.

How to update (append to) an href in jquery?

Here is what i tried to do to add parameter in the url which contain the specific character in the url.

jQuery('a[href*="google.com"]').attr('href', function(i,href) {
        //jquery date addition
        var requiredDate = new Date();
        var numberOfDaysToAdd = 60;
        requiredDate.setDate(requiredDate.getDate() + numberOfDaysToAdd); 
        //var convertedDate  = requiredDate.format('d-M-Y');
        //var newDate = datepicker.formatDate('yy/mm/dd', requiredDate );
        //console.log(requiredDate);

        var month   = requiredDate.getMonth()+1;
        var day     = requiredDate.getDate();

        var output = requiredDate.getFullYear() + '/' + ((''+month).length<2 ? '0' : '') + month + '/' + ((''+day).length<2 ? '0' : '') + day;
        //

Working Example Click

RegEx for Javascript to allow only alphanumeric

A little bit late, but this worked for me:

/[^a-z A-Z 0-9]+/g

a-z : anything from a to z.

A-Z : anything from A to Z (upper case).

0-9 : any number from 0 to 9.

It will allow anything inside square brackets, so let's say you want to allow any other character, for example, "/" and "#", the regex would be something like this:

/[^a-z A-Z 0-9 / #]+/g

This site will help you to test your regex before coding. https://regex101.com/

Feel free to modify and add anything you want into the brackets. Regards :)

How is OAuth 2 different from OAuth 1?

I see great answers up here but what I miss were some diagrams and since I had to work with Spring Framework I came across their explanation.

I find the following diagrams very useful. They illustrate the difference in communication between parties with OAuth2 and OAuth1.


OAuth 2

enter image description here


OAuth 1

enter image description here

Unable to preventDefault inside passive event listener

I am getting this issue when using owl carousal and scrolling the images.

So get solved just adding below CSS in your page.

.owl-carousel {
-ms-touch-action: pan-y;
touch-action: pan-y;
}

or

.owl-carousel {
-ms-touch-action: none;
touch-action: none;
}

Set the text in a span

$('.ui-icon-circle-triangle-w').text('<<');

Finding last index of a string in Oracle

Use -1 as the start position:

INSTR('JD-EQ-0001', '-', -1)

Change image size with JavaScript

Once you have a reference to your image, you can set its height and width like so:

var yourImg = document.getElementById('yourImgId');
if(yourImg && yourImg.style) {
    yourImg.style.height = '100px';
    yourImg.style.width = '200px';
}

In the html, it would look like this:

<img src="src/to/your/img.jpg" id="yourImgId" alt="alt tags are key!"/>

How to copy a file to a remote server in Python using SCP or SSH?

fabric could be used to upload files vis ssh:

#!/usr/bin/env python
from fabric.api import execute, put
from fabric.network import disconnect_all

if __name__=="__main__":
    import sys
    # specify hostname to connect to and the remote/local paths
    srcdir, remote_dirname, hostname = sys.argv[1:]
    try:
        s = execute(put, srcdir, remote_dirname, host=hostname)
        print(repr(s))
    finally:
        disconnect_all()

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

My two cents: came across the same error message in RHEL7.3 while running the openssl command with root CA certificate. The reason being, while downloading the certificate from AD server, Encoding was selected as DER instead of Base64. Once the proper version of encoding was selected for the new certificate download, error was resolved

Hope this helps for new users :-)

python - find index position in list based of partial string

Your idea to use enumerate() was correct.

indices = []
for i, elem in enumerate(mylist):
    if 'aa' in elem:
        indices.append(i)

Alternatively, as a list comprehension:

indices = [i for i, elem in enumerate(mylist) if 'aa' in elem]

Create hyperlink to another sheet

This macro adds a hyperlink to the worksheet with the same name, I also modify the range to be more flexible, just change the first cell in the code. Works like a charm

Sub hyper()
 Dim cl As Range
 Dim nS As String

 Set MyRange = Sheets("Sheet1").Range("B16")
 Set MyRange = Range(MyRange, MyRange.End(xlDown))

 For Each cl In MyRange
  nS = cl.Value
  cl.Hyperlinks.Add Anchor:=cl, Address:="", SubAddress:="'" & nS & "'" & "!B16", TextToDisplay:=nS
 Next
End Sub

How to use executeReader() method to retrieve the value of just one cell

It is not recommended to use DataReader and Command.ExecuteReader to get just one value from the database. Instead, you should use Command.ExecuteScalar as following:

String sql = "SELECT ColumnNumber FROM learer WHERE learer.id = " + index;
SqlCommand cmd = new SqlCommand(sql,conn);
learerLabel.Text = (String) cmd.ExecuteScalar();

Here is more information about Connecting to database and managing data.

How to set table name in dynamic SQL query?

Building on a previous answer by @user1172173 that addressed SQL Injection vulnerabilities, see below:

CREATE PROCEDURE [dbo].[spQ_SomeColumnByCustomerId](
@CustomerId int,
@SchemaName varchar(20),
@TableName nvarchar(200)) AS
SET Nocount ON
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @ParameterDefinition AS NVARCHAR(100)
DECLARE @Table_ObjectId int;
DECLARE @Schema_ObjectId int;
DECLARE @Schema_Table_SecuredFromSqlInjection NVARCHAR(125)

SET @Table_ObjectId = OBJECT_ID(@TableName)
SET @Schema_ObjectId = SCHEMA_ID(@SchemaName)
SET @Schema_Table_SecuredFromSqlInjection = SCHEMA_NAME(@Schema_ObjectId) + '.' + OBJECT_NAME(@Table_ObjectId)

SET @SQLQuery = N'SELECT TOP 1 ' + @Schema_Table_SecuredFromSqlInjection + '.SomeColumn 
FROM dbo.Customer 
INNER JOIN ' + @Schema_Table_SecuredFromSqlInjection + ' 
ON dbo.Customer.Customerid = ' + @Schema_Table_SecuredFromSqlInjection + '.CustomerId 
WHERE dbo.Customer.CustomerID = @CustomerIdParam 
ORDER BY ' + @Schema_Table_SecuredFromSqlInjection + '.SomeColumn DESC' 
SET @ParameterDefinition =  N'@CustomerIdParam INT'

EXECUTE sp_executesql @SQLQuery, @ParameterDefinition, @CustomerIdParam = @CustomerId; RETURN

Postgres ERROR: could not open file for reading: Permission denied

for macbook first i opened terminal then type

open /tmp

or in finder directory you directly enter command+shift+g then type /tmp in go to the folder.

it opens temp folder in finder. then i paste copied csv file into this folder.then again i go to postgres terminal and typed below command and then it is copied my csv data into db table

\copy recharge_operator FROM '/private/tmp/operator.csv' DELIMITER ',' CSV;

How do you create a hidden div that doesn't create a line break or horizontal space?

Consider using <span> to isolate small segments of markup to be styled without breaking up layout. This would seem to be more idiomatic than trying to force a <div> not to display itself--if in fact the checkbox itself cannot be styled in the way you want.

What is VanillaJS?

The plain and simple answer is yes, VanillaJS === JavaScript, as prescribed by Dr B. Eich.

Copy data from another Workbook through VBA

I had the same question but applying the provided solutions changed the file to write in. Once I selected the new excel file, I was also writing in that file and not in my original file. My solution for this issue is below:

Sub GetData()

    Dim excelapp As Application
    Dim source As Workbook
    Dim srcSH1 As Worksheet
    Dim sh As Worksheet
    Dim path As String
    Dim nmr As Long
    Dim i As Long

    nmr = 20

    Set excelapp = New Application

    With Application.FileDialog(msoFileDialogOpen)
        .AllowMultiSelect = False
        .Filters.Add "Excel Files", "*.xlsx; *.xlsm; *.xls; *.xlsb", 1
        .Show
        path = .SelectedItems.Item(1)
    End With

    Set source = excelapp.Workbooks.Open(path)
    Set srcSH1 = source.Worksheets("Sheet1")
    Set sh = Sheets("Sheet1")

    For i = 1 To nmr
        sh.Cells(i, "A").Value = srcSH1.Cells(i, "A").Value
    Next i

End Sub

With excelapp a new application will be called. The with block sets the path for the external file. Finally, I set the external Workbook with source and srcSH1 as a Worksheet within the external sheet.

Adding Only Untracked Files

Lot of good tips here, but inside Powershell I could not get it to work.

I am a .NET developer and we mainly still use Windows OS as we haven't made use of .Net core and cross platform so much, so my everyday use with Git is in a Windows environment, where the shell used is more often Powershell and not Git bash.

The following procedure can be followed to create an aliased function for adding untracked files in a Git repository.

Inside your $profile file of Powershell (in case it is missing - you can run: New-Item $Profile)

notepad $Profile

Now add this Powershell method:

function AddUntracked-Git() {
 &git ls-files -o --exclude-standard | select | foreach { git add $_ }
}

Save the $profile file and reload it into Powershell. Then reload your $profile file with: . $profile

This is similar to the source command in *nix environments IMHO.

So next time you, if you are developer using Powershell in Windows against Git repo and want to just include untracked files you can run:

AddUntracked-Git

This follows the Powershell convention where you have verb-nouns.

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") 

How to Remove Line Break in String

None of the other answers (with one exception, see my edit) handle the case where there are multiple trailing carriage returns. If the goal is to make a function similar to "Trim" that removes carriage returns as well as spaces, you'll probably want it to be robust enough to remove as many as there are and not just one. Also, I'd recommend avoiding the use of the "Left" or "Right" functions in VBA since they do not exist in VB.Net. It may be necessary at some point to convert an Office VBA Macro to a VSTO COM Add-In so it's a good habit to avoid the use of functions that only exist in VBA.

Function RemoveTrailingWhiteSpace(s As String) As String
    RemoveTrailingWhiteSpace = s
    Dim StrLen As Long
    StrLen = Len(RemoveTrailingWhiteSpace)
    While (StrLen > 0 And (Mid(RemoveTrailingWhiteSpace, StrLen) = vbCr Or Mid(RemoveTrailingWhiteSpace, StrLen) = vbLf) Or Mid(RemoveTrailingWhiteSpace, StrLen) = " ")
        RemoveTrailingWhiteSpace = Mid(RemoveTrailingWhiteSpace, 1, StrLen - 1)
        StrLen = Len(RemoveTrailingWhiteSpace)
    Wend
End Function

Edit: I should clarify that there is another answer listed here that trims carriage returns and white space from both ends of the string, but it looked far more convoluted. This can be done fairly concisely.

Connect to mysql on Amazon EC2 from a remote server

Log into AWS Management Console. Navigate to RDS then select the db instance and go to "security Groups". Adding CIDR/IP under the security group fixed the problem.

How to recover just deleted rows in mysql?

No this is not possible. The only solution will be to have regular backups. This is very important.

Entity Framework - Linq query with order by and group by

You can try to cast the result of GroupBy and Take into an Enumerable first then process the rest (building on the solution provided by NinjaNye

var groupByReference = (from m in context.Measurements
                              .GroupBy(m => m.Reference)
                              .Take(numOfEntries).AsEnumerable()
                               .Select(g => new {Creation = g.FirstOrDefault().CreationTime, 
                                             Avg = g.Average(m => m.CreationTime.Ticks),
                                                Items = g })
                              .OrderBy(x => x.Creation)
                              .ThenBy(x => x.Avg)
                              .ToList() select m);

Your sql query would look similar (depending on your input) this

SELECT TOP (3) [t1].[Reference] AS [Key]
FROM (
    SELECT [t0].[Reference]
    FROM [Measurements] AS [t0]
    GROUP BY [t0].[Reference]
    ) AS [t1]
GO

-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref1'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]
GO

-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref2'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]

Python Socket Multiple Clients

This program will open 26 sockets where you would be able to connect a lot of TCP clients to it.

#!usr/bin/python
from thread import *
import socket
import sys

def clientthread(conn):
    buffer=""
    while True:
        data = conn.recv(8192)
        buffer+=data
        print buffer
    #conn.sendall(reply)
    conn.close()

def main():
    try:
        host = '192.168.1.3'
        port = 6666
        tot_socket = 26
        list_sock = []
        for i in range(tot_socket):
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
            s.bind((host, port+i))
            s.listen(10)
            list_sock.append(s)
            print "[*] Server listening on %s %d" %(host, (port+i))

        while 1:
            for j in range(len(list_sock)):
                conn, addr = list_sock[j].accept()
                print '[*] Connected with ' + addr[0] + ':' + str(addr[1])
                start_new_thread(clientthread ,(conn,))
        s.close()

    except KeyboardInterrupt as msg:
        sys.exit(0)


if __name__ == "__main__":
    main()

Remove ':hover' CSS behavior from element

One method to do this is to add:

pointer-events: none;

to the element, you want to disable hover on.

(Note: this also disables javascript events on that element too, click events will actually fall through to the element behind ).

Browser Support ( 98.12% as of Jan 1, 2021 )

This seems to be much cleaner

_x000D_
_x000D_
/**
 * This allows you to disable hover events for any elements
*/
.disabled {
  pointer-events: none;  /* <----------- */
  opacity: 0.2;
}

.button {
  border-radius: 30px;
  padding: 10px 15px;
  border: 2px solid #000;
  color: #FFF;
  background: #2D2D2D;
  text-shadow: 1px 1px 0px #000;
  cursor: pointer;
  display: inline-block;
  margin: 10px;
}

.button-red:hover {
  background: red;
}

.button-green:hover {
  background:green;  
}
_x000D_
<div class="button button-red">I'm a red button hover over me</div>

<br />

<div class="button button-green">I'm a green button hover over me</div>

<br />

<div class="button button-red disabled">I'm a disabled red button</div>

<br />

<div class="button button-green disabled">I'm a disabled green button</div>
_x000D_
_x000D_
_x000D_

Set a default parameter value for a JavaScript function

Just to showcase my skills too (lol), above function can written even without having named arguments as below:

ES5 and above

function foo() {
    a = typeof arguments[0] !== 'undefined' ? a : 42;
    b = typeof arguments[1] !== 'undefined' ? b : 'default_b';
    ...
}

ES6 and above

function foo(...rest) {
    a = typeof rest[0] !== 'undefined' ? a : 42;
    b = typeof rest[1] !== 'undefined' ? b : 'default_b';
    ...
}

Meaning of $? (dollar question mark) in shell scripts

Minimal POSIX C exit status example

To understand $?, you must first understand the concept of process exit status which is defined by POSIX. In Linux:

  • when a process calls the exit system call, the kernel stores the value passed to the system call (an int) even after the process dies.

    The exit system call is called by the exit() ANSI C function, and indirectly when you do return from main.

  • the process that called the exiting child process (Bash), often with fork + exec, can retrieve the exit status of the child with the wait system call

Consider the Bash code:

$ false
$ echo $?
1

The C "equivalent" is:

false.c

#include <stdlib.h> /* exit */

int main(void) {
    exit(1);
}

bash.c

#include <unistd.h> /* execl */
#include <stdlib.h> /* fork */
#include <sys/wait.h> /* wait, WEXITSTATUS */
#include <stdio.h> /* printf */

int main(void) {
    if (fork() == 0) {
        /* Call false. */
        execl("./false", "./false", (char *)NULL);
    }
    int status;
    /* Wait for a child to finish. */
    wait(&status);
    /* Status encodes multiple fields,
     * we need WEXITSTATUS to get the exit status:
     * http://stackoverflow.com/questions/3659616/returning-exit-code-from-child
     **/
    printf("$? = %d\n", WEXITSTATUS(status));
}

Compile and run:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o bash bash.c
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o false false.c
./bash

Output:

$? = 1

In Bash, when you hit enter, a fork + exec + wait happens like above, and bash then sets $? to the exit status of the forked process.

Note: for built-in commands like echo, a process need not be spawned, and Bash just sets $? to 0 to simulate an external process.

Standards and documentation

POSIX 7 2.5.2 "Special Parameters" http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_05_02 :

? Expands to the decimal exit status of the most recent pipeline (see Pipelines).

man bash "Special Parameters":

The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed. [...]

? Expands to the exit status of the most recently executed foreground pipeline.

ANSI C and POSIX then recommend that:

  • 0 means the program was successful

  • other values: the program failed somehow.

    The exact value could indicate the type of failure.

    ANSI C does not define the meaning of any vaues, and POSIX specifies values larger than 125: What is the meaning of "POSIX"?

Bash uses exit status for if

In Bash, we often use the exit status $? implicitly to control if statements as in:

if true; then
  :
fi

where true is a program that just returns 0.

The above is equivalent to:

true
result=$?
if [ $result = 0 ]; then
  :
fi

And in:

if [ 1 = 1 ]; then
  :
fi

[ is just an program with a weird name (and Bash built-in that behaves like it), and 1 = 1 ] its arguments, see also: Difference between single and double square brackets in Bash

Can a Windows batch file determine its own file name?

You can get the file name, but you can also get the full path, depending what you place between the '%~' and the '0'. Take your pick from

d -- drive
p -- path
n -- file name
x -- extension
f -- full path

E.g., from inside c:\tmp\foo.bat, %~nx0 gives you "foo.bat", whilst %~dpnx0 gives "c:\tmp\foo.bat". Note the pieces are always assembled in canonical order, so if you get cute and try %~xnpd0, you still get "c:\tmp\foo.bat"

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO

Same pdo error in sql query while trying to insert into database value from multidimential array:

$sql = "UPDATE test SET field=arr[$s][a] WHERE id = $id";
$sth = $db->prepare($sql);    
$sth->execute();

Extracting array arr[$s][a] from sql query, using instead variable containing it fixes the problem.

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

I got this error when sending a GET request with postman. The request required no parameters. My mistake was I had a blank line in the request body.

What is a unix command for deleting the first N characters of a line?

I think awk would be the best tool for this as it can both filter and perform the necessary string manipulation functions on filtered lines:

tail -f logfile | awk '/org.springframework/ {print substr($0, 6)}'

or

tail -f logfile | awk '/org.springframework/ && sub(/^.{5}/,"",$0)'

Best way to find the intersection of multiple sets?

As of 2.6, set.intersection takes arbitrarily many iterables.

>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s3 = set([2, 4, 6])
>>> s1 & s2 & s3
set([2])
>>> s1.intersection(s2, s3)
set([2])
>>> sets = [s1, s2, s3]
>>> set.intersection(*sets)
set([2])

Iterating over JSON object in C#

This worked for me, converts to nested JSON to easy to read YAML

    string JSONDeserialized {get; set;}
    public int indentLevel;

    private bool JSONDictionarytoYAML(Dictionary<string, object> dict)
    {
        bool bSuccess = false;
        indentLevel++;

        foreach (string strKey in dict.Keys)
        {
            string strOutput = "".PadLeft(indentLevel * 3) + strKey + ":";
            JSONDeserialized+="\r\n" + strOutput;

            object o = dict[strKey];
            if (o is Dictionary<string, object>)
            {
                JSONDictionarytoYAML((Dictionary<string, object>)o);
            }
            else if (o is ArrayList)
            {
                foreach (object oChild in ((ArrayList)o))
                {
                    if (oChild is string)
                    {
                        strOutput = ((string)oChild);
                        JSONDeserialized += strOutput + ",";
                    }
                    else if (oChild is Dictionary<string, object>)
                    {
                        JSONDictionarytoYAML((Dictionary<string, object>)oChild);
                        JSONDeserialized += "\r\n";  
                    }
                }
            }
            else
            {
                strOutput = o.ToString();
                JSONDeserialized += strOutput;
            }
        }

        indentLevel--;

        return bSuccess;

    }

usage

        Dictionary<string, object> JSONDic = new Dictionary<string, object>();
        JavaScriptSerializer js = new JavaScriptSerializer();

          try {

            JSONDic = js.Deserialize<Dictionary<string, object>>(inString);
            JSONDeserialized = "";

            indentLevel = 0;
            DisplayDictionary(JSONDic); 

            return JSONDeserialized;

        }
        catch (Exception)
        {
            return "Could not parse input JSON string";
        }

Docker command can't connect to Docker daemon

After installing docker on Ubuntu, I ran the following command:

sudo service docker start

Have you tried it?

How to get form input array into PHP array

They are already in arrays: $name is an array, as is $email

So all you need to do is add a bit of processing to attack both arrays:

$name = $_POST['name'];
$email = $_POST['account'];

foreach( $name as $key => $n ) {
  print "The name is ".$n." and email is ".$email[$key].", thank you\n";
}

To handle more inputs, just extend the pattern:

$name = $_POST['name'];
$email = $_POST['account'];
$location = $_POST['location'];

foreach( $name as $key => $n ) {
  print "The name is ".$n.", email is ".$email[$key].
        ", and location is ".$location[$key].". Thank you\n";
}

Can JavaScript connect with MySQL?

Yes. There is an HTTP plugin for MySQL.

http://blog.ulf-wendel.de/2014/mysql-5-7-http-plugin-mysql/

I'm just googling about it now, which led me to this stackoverflow question. You should be able to AJAX a MySQL database now or in the near future (they claim it's not ready for production).

jQuery Find and List all LI elements within a UL within a specific DIV

var column1RelArray = [];
$('#column1 li').each(function(){
    column1RelArray.push($(this).attr('rel'));
});

or fp style

var column1RelArray = $('#column1 li').map(function(){ 
    return $(this).attr('rel'); 
});

How to render an array of objects in React?

Try this:

_x000D_
_x000D_
class First extends React.Component {
  constructor (props){
    super(props);

  }

  render() {
     const data =[{"name":"test1"},{"name":"test2"}];
    const listItems = data.map((d) => <li key={d.name}>{d.name}</li>;
    
    return (
      <div>
      {listItems}
      </div>
    );
  }
} 
_x000D_
_x000D_
_x000D_

Can I avoid the native fullscreen video player with HTML5 on iPhone or android?

In iOS 10+

Apple enabled the attribute playsinline in all browsers on iOS 10, so this works seamlessly:

<video src="file.mp4" playsinline>

In iOS 8 and iOS 9

Short answer: use iphone-inline-video, it enables inline playback and syncs the audio.

Long answer: You can work around this issue by simulating the playback by skimming the video instead of actually .play()'ing it.

Git push rejected "non-fast-forward"

Here is another solution to resolve this issue

>git pull
>git commit -m "any meaning full message"
>git push

Change Spinner dropdown icon

I have had a lot of difficulty with this as I have a custom spinner, if I setBackground then the Drawable would stretch. My solution to this was to add a drawable to the right of the Spinner TextView. Heres a code snippet from my Custom Spinner. The trick is to Override getView and customize the Textview as you wish.

public class NoTextSpinnerArrayAdapter extends ArrayAdapter<String> {

    private String text = "0";

    public NoTextSpinnerArrayAdapter(Context context, int textViewResourceId, List<String> objects) {
        super(context, textViewResourceId, objects);
    }

    public void updateText(String text){
        this.text = text;
        notifyDataSetChanged();
    }

    public String getText(){
        return text;
    }

    @NonNull
    public View getView(int position, View convertView, @NonNull ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        TextView textView = view.findViewById(android.R.id.text1);
        textView.setCompoundDrawablePadding(16);
        textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_menu_white_24dp, 0);

        textView.setGravity(Gravity.END);
        textView.setText(text);
        return view;
    }
}

You also need to set the Spinner background to transparent:

<lifeunlocked.valueinvestingcheatsheet.views.SelectAgainSpinner
            android:id="@+id/saved_tickers_spinner"
            android:background="@android:color/transparent"
            android:layout_width="60dp"
            android:layout_height="match_parent"
            tools:layout_editor_absoluteX="248dp"
            tools:layout_editor_absoluteY="16dp" />

and my custom spinner if you want it....

public class SelectAgainSpinner extends android.support.v7.widget.AppCompatSpinner {
    public SelectAgainSpinner(Context context) {
        super(context);
    }

    public SelectAgainSpinner(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

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

    @Override
    public void setPopupBackgroundDrawable(Drawable background) {
        super.setPopupBackgroundDrawable(background);
    }

    @Override
    public void setSelection(int position, boolean animate) {
        boolean sameSelected = position == getSelectedItemPosition();
        super.setSelection(position, animate);
        if (sameSelected) {
            // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
            if (getOnItemSelectedListener() != null) {
                getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
            }
        }
    }

    @Override
    public void setSelection(int position) {
        boolean sameSelected = position == getSelectedItemPosition();
        super.setSelection(position);
        if (sameSelected) {
            // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
            if (getOnItemSelectedListener() != null) {
                getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
            }
        }
    }
}

response.sendRedirect() from Servlet to JSP does not seem to work

Since you already have sent some data,

System.out.println("going to demo.jsp");

you won't be able to send a redirect.

fatal: 'origin' does not appear to be a git repository

This does not answer your question, but I faced a similar error message but due to a different reason. Allow me to make my post for the sake of information collection.

I have a git repo on a network drive. Let's call this network drive RAID. I cloned this repo on my local machine (LOCAL) and on my number crunching cluster (CRUNCHER). For convenience I mounted the user directory of my account on CRUNCHER on my local machine. So, I can manipulate files on CRUNCHER without the need to do the work in an SSH terminal.

Today, I was modifying files in the repo on CRUNCHER via my local machine. At some point I decided to commit the files, so a did a commit. Adding the modified files and doing the commit worked as I expected, but when I called git push I got an error message similar to the one posted in the question.

The reason was, that I called push from within the repo on CRUNCHER on LOCAL. So, all paths in the config file were plain wrong.

When I realized my fault, I logged onto CRUNCHER via Terminal and was able to push the commit.

Feel free to comment if my explanation can't be understood, or you find my post superfluous.

Why there is this "clear" class before footer?

Most likely, as mentioned by others, it is a class carrying the css values:

.clear{clear: both;} 

in order to prevent any more page elements from extending into the footer element. It is a quick and easy way of making sure that pages with columns of varying heights don't cause the footer to render oddly, by possibly setting its top position at the end of a shorter column.

In many cases it is not necessary, but if you are using best-practice standards it is a good idea to use, if you are floating page elements left and right. It functions with page elements similar to the way a horizontal rule works with text, to ensure proper and complete sepperation.

How can I introduce multiple conditions in LIKE operator?

If your parameter value is not fixed or your value can be null based on business you can try the following approach.

DECLARE @DrugClassstring VARCHAR(MAX);
SET @DrugClassstring = 'C3,C2'; -- You can pass null also

---------------------------------------------

IF @DrugClassstring IS NULL 
    SET @DrugClassstring = 'C3,C2,C4,C5,RX,OT'; -- If null you can set your all conditional case that will return for all
SELECT dn.drugclass_FK , dn.cdrugname
FROM drugname AS dn
INNER JOIN dbo.SplitString(@DrugClassstring, ',') class ON dn.drugclass_FK = class.[Name] -- SplitString is a a function

SplitString function

SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
ALTER FUNCTION [dbo].[SplitString](@stringToSplit VARCHAR(MAX),
                                   @delimeter     CHAR(1)      = ',')
RETURNS @returnList TABLE([Name] [NVARCHAR](500))
AS
     BEGIN

         --It's use in report sql, before any change concern to everyone

         DECLARE @name NVARCHAR(255);
         DECLARE @pos INT;
         WHILE CHARINDEX(@delimeter, @stringToSplit) > 0
             BEGIN
                 SELECT @pos = CHARINDEX(@delimeter, @stringToSplit);
                 SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1);
                 INSERT INTO @returnList
                        SELECT @name;
                 SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos);
             END;
         INSERT INTO @returnList
                SELECT @stringToSplit;
         RETURN;
     END;

Replace last occurrence of character in string

_x000D_
_x000D_
    // Define variables_x000D_
    let haystack = 'I do not want to replace this, but this'_x000D_
    let needle = 'this'_x000D_
    let replacement = 'hey it works :)'_x000D_
    _x000D_
    // Reverse it_x000D_
    haystack = Array.from(haystack).reverse().join('')_x000D_
    needle = Array.from(needle).reverse().join('')_x000D_
    replacement = Array.from(replacement).reverse().join('')_x000D_
    _x000D_
    // Make the replacement_x000D_
    haystack = haystack.replace(needle, replacement)_x000D_
    _x000D_
    // Reverse it back_x000D_
    let results = Array.from(haystack).reverse().join('')_x000D_
    console.log(results)_x000D_
    // 'I do not want to replace this, but hey it works :)'
_x000D_
_x000D_
_x000D_

How to use XPath preceding-sibling correctly

I also like to build locators from up to bottom like:

//div[contains(@class,'btn-group')][./button[contains(.,'Arcade Reader')]]/button[@name='settings']

It's pretty simple, as we just search btn-group with button[contains(.,'Arcade Reader')] and get it's button[@name='settings']

That's just another option to build xPath locators

What is the profit of searching wrapper element: you can return it by method (example in java) and just build selenium constructions like:

getGroupByName("Arcade Reader").find("button[name='settings']");
getGroupByName("Arcade Reader").find("button[name='delete']");

or even simplify more

getGroupButton("Arcade Reader", "delete").click();

getContext is not a function

Actually we get this error also when we create canvas in javascript as below.

document.createElement('canvas');

Here point to be noted we have to provide argument name correctly as 'canvas' not anything else.

Thanks

ORA-01652 Unable to extend temp segment by in tablespace

I found the solution to this. There is a temporary tablespace called TEMP which is used internally by database for operations like distinct, joins,etc. Since my query(which has 4 joins) fetches almost 50 million records the TEMP tablespace does not have that much space to occupy all data. Hence the query fails even though my tablespace has free space.So, after increasing the size of TEMP tablespace the issue was resolved. Hope this helps someone with the same issue. Thanks :)

AJAX POST and Plus Sign ( + ) -- How to Encode?

In JavaScript try:

encodeURIComponent() 

and in PHP:

urldecode($_POST['field']);

node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

in .mjs files we for now don't have __dirname

hence

res.sendFile('index.html', { root: '.' })

Capturing a form submit with jquery and .submit

Just a tip: Remember to put the code detection on document.ready, otherwise it might not work. That was my case.

Android webview slow

I tried all the proposals to fix the render performance problem in my phonegap app. But nothing realy worked.

Finally, after a whole day of searching, I made it. I set within the tag (not the tag) of my AndroidManifest

<application android:hardwareAccelerated="false" ...

Now the app behaves in the same fast way as my webbrowser. Seems like, if hardware acceleration is not always the best feature...

The detailed problem I had: https://stackoverflow.com/a/24467920/3595386

Need to find element in selenium by css

You can describe your css selection like cascading style sheet dows:

protected override void When()
{
   SUT.Browser.FindElements(By.CssSelector("#carousel > a.tiny.button"))
}

jquery Ajax call - data parameters are not being passed to MVC Controller action

  var json = {"ListID" : "1", "ItemName":"test"};
    $.ajax({
            url: url,
            type: 'POST',        
            data: username, 
            cache:false,
            beforeSend: function(xhr) {  
                xhr.setRequestHeader("Accept", "application/json");  
                xhr.setRequestHeader("Content-Type", "application/json");  
            },       
            success:function(response){
             console.log("Success")
            },
              error : function(xhr, status, error) {
            console.log("error")
            }
);

Target class controller does not exist - Laravel 8

Happened to me when I passing null to the middleware function

Route::middleware(null)->group(function () {
    Route::get('/some-path', [SomeController::class, 'search']);
});

Passing [] for no middleware works or probably just remove the middleware call if not using middleware :D

How to remove index.php from URLs?

I tried everything on the post but nothing had worked. I then changed the .htaccess snippet that ErJab put up to read:

RewriteRule ^(.*)$ 'folder_name'/index.php/$1 [L]

The above line fixed it for me. where *folder_name* is the magento root folder.

Hope this helps!

Return True, False and None in Python

It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return statement. When the code goes down that path, the function ends with no value returned, and so returns None.

Updated: It sounds like your code looks like this:

def b(self, p, data): 
    current = p 
    if current.data == data: 
        return True 
    elif current.data == 1:
        return False 
    else: 
        self.b(current.next, data)

That else clause is your None path. You need to return the value that the recursive call returns:

    else:
        return self.b(current.next, data)

BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.

Is there a WebSocket client implemented for Python?

  1. Take a look at the echo client under http://code.google.com/p/pywebsocket/ It's a Google project.
  2. A good search in github is: https://github.com/search?type=Everything&language=python&q=websocket&repo=&langOverride=&x=14&y=29&start_value=1 it returns clients and servers.
  3. Bret Taylor also implemented web sockets over Tornado (Python). His blog post at: Web Sockets in Tornado and a client implementation API is shown at tornado.websocket in the client side support section.

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

I got this same error when installing to an actual device. More information and a solution to loading the missing libraries to the device can be found at the following site:

Fixing the INSTALL_FAILED_MISSING_SHARED_LIBRARY Error

To set this up correctly, there are 2 key files that need to be copied to the system:

com.google.android.maps.xml

com.google.android.maps.jar

These files are located in the any of these google app packs:

http://android.d3xt3...0120-signed.zip

http://goo-inside.me...0120-signed.zip

http://android.local...0120-signed.zip

These links no longer work, but you can find the files in the android sdk if you have Google Maps API v1

After unzipping any of these files, you want to copy the files to your system, like-ah-so:

adb remount

adb push system/etc/permissions/com.google.android.maps.xml /system/etc/permissions

adb push system/framework/com.google.android.maps.jar /system/framework

adb reboot

GROUP_CONCAT comma separator - MySQL

Looks like you're missing the SEPARATOR keyword in the GROUP_CONCAT function.

GROUP_CONCAT(artists.artistname SEPARATOR '----')

The way you've written it, you're concatenating artists.artistname with the '----' string using the default comma separator.

PSEXEC, access denied errors

I still use psexec, even on win 10. Replace the psexec.exe in the Windows 10's win32 folder with the older version to work -> I use version 2.11.0.0. The Windows 10 version I was using would only run .bat files as background/hidden process on the remote computer. Took a whole day to figure this out.

Adding the registry key from above to the remote computer helps as well:

   reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f

Single vs Double quotes (' vs ")

If it's all the same, perhaps using single-quotes is better since it doesn't require holding down the shift key. Fewer keystrokes == less chance of RSI.

A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error

Actually,,i found a simple answer,, Jst adding the object to String Builder instead of String worked ;)

StringBuilder jsonString= new StringBuilder.append("http://www.json-.com/j/cglqaRcMSW?=4");    
JSON json= new JSON(jsonString.toString);

onclick on a image to navigate to another page using Javascript

Because it makes these things so easy, you could consider using a JavaScript library like jQuery to do this:

<script>
    $(document).ready(function() {
        $('img.thumbnail').click(function() {
            window.location.href = this.id + '.html';
        });
    });
</script>

Basically, it attaches an onClick event to all images with class thumbnail to redirect to the corresponding HTML page (id + .html). Then you only need the images in your HTML (without the a elements), like this:

<img src="bottle.jpg" alt="bottle" class="thumbnail" id="bottle" />
<img src="glass.jpg" alt="glass" class="thumbnail" id="glass" />

onchange event for html.dropdownlist

If you don't want jquery then you can do it with javascript :-

@Html.DropDownList("Sortby", new SelectListItem[] 
{ 
     new SelectListItem() { Text = "Newest to Oldest", Value = "0" }, 
     new SelectListItem() { Text = "Oldest to Newest", Value = "1" }},
     new { @onchange="callChangefunc(this.value)" 
});

<script>
    function callChangefunc(val){
        window.location.href = "/Controller/ActionMethod?value=" + val;
    }
</script>

Best practice to call ConfigureAwait for all server-side code

Update: ASP.NET Core does not have a SynchronizationContext. If you are on ASP.NET Core, it does not matter whether you use ConfigureAwait(false) or not.

For ASP.NET "Full" or "Classic" or whatever, the rest of this answer still applies.

Original post (for non-Core ASP.NET):

This video by the ASP.NET team has the best information on using async on ASP.NET.

I had read that it is more performant since it doesn't have to switch thread contexts back to the original thread context.

This is true with UI applications, where there is only one UI thread that you have to "sync" back to.

In ASP.NET, the situation is a bit more complex. When an async method resumes execution, it grabs a thread from the ASP.NET thread pool. If you disable the context capture using ConfigureAwait(false), then the thread just continues executing the method directly. If you do not disable the context capture, then the thread will re-enter the request context and then continue to execute the method.

So ConfigureAwait(false) does not save you a thread jump in ASP.NET; it does save you the re-entering of the request context, but this is normally very fast. ConfigureAwait(false) could be useful if you're trying to do a small amount of parallel processing of a request, but really TPL is a better fit for most of those scenarios.

However, with ASP.NET Web Api, if your request is coming in on one thread, and you await some function and call ConfigureAwait(false) that could potentially put you on a different thread when you are returning the final result of your ApiController function.

Actually, just doing an await can do that. Once your async method hits an await, the method is blocked but the thread returns to the thread pool. When the method is ready to continue, any thread is snatched from the thread pool and used to resume the method.

The only difference ConfigureAwait makes in ASP.NET is whether that thread enters the request context when resuming the method.

I have more background information in my MSDN article on SynchronizationContext and my async intro blog post.

Index all *except* one item in python

The simplest way I found was:

mylist[:x] + mylist[x+1:]

that will produce your mylist without the element at index x.

Example

mylist = [0, 1, 2, 3, 4, 5]
x = 3
mylist[:x] + mylist[x+1:]

Result produced

mylist = [0, 1, 2, 4, 5]

How to test an Internet connection with bash?

Execute the following command to check whether a web site is up, and what status message the web server is showing:

curl -Is http://www.google.com | head -1 HTTP/1.1 200 OK

Status code ‘200 OK’ means that the request has succeeded and a website is reachable.

Link to "pin it" on pinterest without generating a button

I Found some code for wordpress:

 <script type="text/javascript">

    function insert_pinterest($content) {
        global $post;
        $posturl = urlencode(get_permalink()); //Get the post URL
        $pinspan = '<span class="pinterest-button">';
     $pinurl = '';
     $pinend = '</span>';
        $pattern = '//i';
        $replacement = $pinspan.$pinurl.'$2.$3'.$pindescription.$pinfinish.''.$pinend;
        $content = preg_replace( $pattern, $replacement, $content );
        //Fix the link problem
        $newpattern = '/<span class="pinterest-button"><\/a><\/span><\/a>/i';
     $replacement = '';
     $content = preg_replace( $newpattern, $replacement, $content );
     return $content;
    }
    add_filter( 'the_content', 'insert_pinterest' );

    </script>

Then you put the following in your PHP:

<?php $pinterestimage = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' ); ?>
<a href="http://pinterest.com/pin/create/button/?url=<?php echo urlencode(get_permalink($post->ID)); ?>&media=<?php echo $pinterestimage[0]; ?>&description=<?php the_title(); ?>">Pin It</a>

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

The solution is running this command:

set OPENSSL_CONF=C:\OpenSSL-Win32\bin\openssl.cfg   

or

set OPENSSL_CONF=[path-to-OpenSSL-install-dir]\bin\openssl.cfg

in the command prompt before using openssl command.

Let openssl know for sure where to find its .cfg file.

Alternatively you could set the same variable OPENSSL_CONF in the Windows environment variables.

NOTE: This can happen when using the OpenSSL binary distribution from Shining Light Productions (a compiled + installer version of the official OpenSSL that is free to download & use). This distribution is "semi-officially" linked from OpenSSL's site as a "service primarily for operating systems where there are no pre-compiled OpenSSL packages".

Where and how is the _ViewStart.cshtml layout file linked?

From ScottGu's blog:

Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:

The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:

Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).

Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.

This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.

Also see this.


In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".

Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.

Wikipedia

There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.

Is it worth using Python's re.compile?

I agree with Honest Abe that the match(...) in the given examples are different. They are not a one-to-one comparisons and thus, outcomes are vary. To simplify my reply, I use A, B, C, D for those functions in question. Oh yes, we are dealing with 4 functions in re.py instead of 3.

Running this piece of code:

h = re.compile('hello')                   # (A)
h.match('hello world')                    # (B)

is same as running this code:

re.match('hello', 'hello world')          # (C)

Because, when looked into the source re.py, (A + B) means:

h = re._compile('hello')                  # (D)
h.match('hello world')

and (C) is actually:

re._compile('hello').match('hello world')

So, (C) is not the same as (B). In fact, (C) calls (B) after calling (D) which is also called by (A). In other words, (C) = (A) + (B). Therefore, comparing (A + B) inside a loop has same result as (C) inside a loop.

George's regexTest.py proved this for us.

noncompiled took 4.555 seconds.           # (C) in a loop
compiledInLoop took 4.620 seconds.        # (A + B) in a loop
compiled took 2.323 seconds.              # (A) once + (B) in a loop

Everyone's interest is, how to get the result of 2.323 seconds. In order to make sure compile(...) only get called once, we need to store the compiled regex object in memory. If we are using a class, we could store the object and reuse when every time our function get called.

class Foo:
    regex = re.compile('hello')
    def my_function(text)
        return regex.match(text)

If we are not using class (which is my request today), then I have no comment. I'm still learning to use global variable in Python, and I know global variable is a bad thing.

One more point, I believe that using (A) + (B) approach has an upper hand. Here are some facts as I observed (please correct me if I'm wrong):

  1. Calls A once, it will do one search in the _cache followed by one sre_compile.compile() to create a regex object. Calls A twice, it will do two searches and one compile (because the regex object is cached).

  2. If the _cache get flushed in between, then the regex object is released from memory and Python need to compile again. (someone suggest that Python won't recompile.)

  3. If we keep the regex object by using (A), the regex object will still get into _cache and get flushed somehow. But our code keep a reference on it and the regex object will not be released from memory. Those, Python need not to compile again.

  4. The 2 seconds differences in George's test compiledInLoop vs compiled is mainly the time required to build the key and search the _cache. It doesn't mean the compile time of regex.

  5. George's reallycompile test show what happen if it really re-do the compile every time: it will be 100x slower (he reduced the loop from 1,000,000 to 10,000).

Here are the only cases that (A + B) is better than (C):

  1. If we can cache a reference of the regex object inside a class.
  2. If we need to calls (B) repeatedly (inside a loop or multiple times), we must cache the reference to regex object outside the loop.

Case that (C) is good enough:

  1. We cannot cache a reference.
  2. We only use it once in a while.
  3. In overall, we don't have too many regex (assume the compiled one never get flushed)

Just a recap, here are the A B C:

h = re.compile('hello')                   # (A)
h.match('hello world')                    # (B)
re.match('hello', 'hello world')          # (C)

Thanks for reading.

How to determine MIME type of file in android?

Solution September 2020

Using Kotlin

fun File.getMimeType(context: Context): String? {
    if (this.isDirectory) {
        return null
    }

    fun fallbackMimeType(uri: Uri): String? {
        return if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
            context.contentResolver.getType(uri)
        } else {
            val extension = MimeTypeMap.getFileExtensionFromUrl(uri.toString())
            MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase(Locale.getDefault()))
        }
    }

    fun catchUrlMimeType(): String? {
        val uri = Uri.fromFile(this)

        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val path = Paths.get(uri.toString())
            try {
                Files.probeContentType(path) ?: fallbackMimeType(uri)
            } catch (ignored: IOException) {
                fallbackMimeType(uri)
            }
        } else {
            fallbackMimeType(uri)
        }
    }

    return try {
        URLConnection.guessContentTypeFromStream(this.inputStream()) ?: catchUrlMimeType()
    } catch (ignored: IOException) {
        catchUrlMimeType()
    }
}

That seems like the best option as it combines the previous answers.

First it tries to get the type using URLConnection.guessContentTypeFromStream but if this fails or returns null it tries to get the mimetype on Android O and above using

java.nio.file.Files
java.nio.file.Paths

Otherwise if the Android Version is below O or the method fails it returns the type using ContentResolver and MimeTypeMap

What are all codecs and formats supported by FFmpeg?

The formats and codecs supported by your build of ffmpeg can vary due the version, how it was compiled, and if any external libraries, such as libx264, were supported during compilation.

Formats (muxers and demuxers):

List all formats:

ffmpeg -formats

Display options specific to, and information about, a particular muxer:

ffmpeg -h muxer=matroska

Display options specific to, and information about, a particular demuxer:

ffmpeg -h demuxer=gif

Codecs (encoders and decoders):

List all codecs:

ffmpeg -codecs

List all encoders:

ffmpeg -encoders

List all decoders:

ffmpeg -decoders

Display options specific to, and information about, a particular encoder:

ffmpeg -h encoder=mpeg4

Display options specific to, and information about, a particular decoder:

ffmpeg -h decoder=aac

Reading the results

There is a key near the top of the output that describes each letter that precedes the name of the format, encoder, decoder, or codec:

$ ffmpeg -encoders
[…]
Encoders:
 V..... = Video
 A..... = Audio
 S..... = Subtitle
 .F.... = Frame-level multithreading
 ..S... = Slice-level multithreading
 ...X.. = Codec is experimental
 ....B. = Supports draw_horiz_band
 .....D = Supports direct rendering method 1
 ------
[…]
 V.S... mpeg4                MPEG-4 part 2

In this example V.S... indicates that the encoder mpeg4 is a Video encoder and supports Slice-level multithreading.

Also see

What is a codec and how does it differ from a format?

Why is the GETDATE() an invalid identifier

getdate() for MS-SQL, sysdate for Oracle server

How to trigger a file download when clicking an HTML button or JavaScript

You can hide the download link and make the button click it.

<button onclick="document.getElementById('link').click()">Download!</button>
<a id="link" href="file.doc" download hidden></a>

mongodb group values by multiple fields

Below query will provide exactly the same result as given in the desired response:

db.books.aggregate([
    {
        $group: {
            _id: { addresses: "$addr", books: "$book" },
            num: { $sum :1 }
        }
    },
    {
        $group: {
            _id: "$_id.addresses",
            bookCounts: { $push: { bookName: "$_id.books",count: "$num" } }
        }
    },
    {
        $project: {
            _id: 1,
            bookCounts:1,
            "totalBookAtAddress": {
                "$sum": "$bookCounts.count"
            }
        }
    }

]) 

The response will be looking like below:

/* 1 */
{
    "_id" : "address4",
    "bookCounts" : [
        {
            "bookName" : "book3",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 2 */
{
    "_id" : "address90",
    "bookCounts" : [
        {
            "bookName" : "book33",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 3 */
{
    "_id" : "address15",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 4 */
{
    "_id" : "address3",
    "bookCounts" : [
        {
            "bookName" : "book9",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 5 */
{
    "_id" : "address5",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 6 */
{
    "_id" : "address1",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 3
        },
        {
            "bookName" : "book5",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 4
},

/* 7 */
{
    "_id" : "address2",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 2
        },
        {
            "bookName" : "book5",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 3
},

/* 8 */
{
    "_id" : "address77",
    "bookCounts" : [
        {
            "bookName" : "book11",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 9 */
{
    "_id" : "address9",
    "bookCounts" : [
        {
            "bookName" : "book99",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
}

Using getopts to process long and short command line options

#!/bin/bash
while getopts "abc:d:" flag
do
  case $flag in
    a) echo "[getopts:$OPTIND]==> -$flag";;
    b) echo "[getopts:$OPTIND]==> -$flag";;
    c) echo "[getopts:$OPTIND]==> -$flag $OPTARG";;
    d) echo "[getopts:$OPTIND]==> -$flag $OPTARG";;
  esac
done

shift $((OPTIND-1))
echo "[otheropts]==> $@"

exit

.

#!/bin/bash
until [ -z "$1" ]; do
  case $1 in
    "--dlong")
      shift
      if [ "${1:1:0}" != "-" ]
      then
        echo "==> dlong $1"
        shift
      fi;;
    *) echo "==> other $1"; shift;;
  esac
done
exit

What is the best way to get the count/length/size of an iterator?

If all you have is the iterator, then no, there is no "better" way. If the iterator comes from a collection you could as that for size.

Keep in mind that Iterator is just an interface for traversing distinct values, you would very well have code such as this

    new Iterator<Long>() {
        final Random r = new Random();
        @Override
        public boolean hasNext() {
            return true;
        }

        @Override
        public Long next() {
            return r.nextLong();
        }

        @Override
        public void remove() {
            throw new IllegalArgumentException("Not implemented");
        }
    };

or

    new Iterator<BigInteger>() {
        BigInteger next = BigInteger.ZERO;

        @Override
        public boolean hasNext() {
            return true;
        }

        @Override
        public BigInteger next() {
            BigInteger current = next;
            next = next.add(BigInteger.ONE);
            return current;
        }

        @Override
        public void remove() {
            throw new IllegalArgumentException("Not implemented");
        }
    }; 

What is the difference between persist() and merge() in JPA and Hibernate?

The most important difference is this:

  • In case of persist method, if the entity that is to be managed in the persistence context, already exists in persistence context, the new one is ignored. (NOTHING happened)

  • But in case of merge method, the entity that is already managed in persistence context will be replaced by the new entity (updated) and a copy of this updated entity will return back. (from now on any changes should be made on this returned entity if you want to reflect your changes in persistence context)

Show all current locks from get_lock

Starting with MySQL 5.7, the performance schema exposes all metadata locks, including locks related to the GET_LOCK() function.

See http://dev.mysql.com/doc/refman/5.7/en/metadata-locks-table.html

How to find the minimum value of a column in R?

If you need minimal value for particular column

min(data[,2])

Note: R considers NA both the minimum and maximum value so if you have NA's in your column, they return: NA. To remedy, use:

min(data[,2], na.rm=T)

Error:java: javacTask: source release 8 requires target release 1.8

  1. File > Settings > Build, Execution, Deployment > Compiler > Java Compiler
  2. Change Target bytecode version to 1.8 of the module that you are working for.

If you are using Maven

Add the compiler plugin to pom.xml under the top-level project node:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

(Hoisted from the comments.)

Note: If you don't mind reimporting your project, then the only thing you really need to do is change the pom and reimport the project, then IntelliJ will pick up the correct settings and you don't have to manually change them.

Run text file as commands in Bash

cat /path/* | bash

OR

cat commands.txt | bash

Error: Cannot find module html

Use

res.sendFile()

instead of

res.render().

What your trying to do is send a whole file.

This worked for me.

Resize image with javascript canvas (smoothly)

I created a reusable Angular service to handle high quality resizing of images / canvases for anyone who's interested: https://gist.github.com/transitive-bullshit/37bac5e741eaec60e983

The service includes two solutions because they both have their own pros / cons. The lanczos convolution approach is higher quality at the cost of being slower, whereas the step-wise downscaling approach produces reasonably antialiased results and is significantly faster.

Example usage:

angular.module('demo').controller('ExampleCtrl', function (imageService) {
  // EXAMPLE USAGE
  // NOTE: it's bad practice to access the DOM inside a controller, 
  // but this is just to show the example usage.

  // resize by lanczos-sinc filter
  imageService.resize($('#myimg')[0], 256, 256)
    .then(function (resizedImage) {
      // do something with resized image
    })

  // resize by stepping down image size in increments of 2x
  imageService.resizeStep($('#myimg')[0], 256, 256)
    .then(function (resizedImage) {
      // do something with resized image
    })
})

Syncing Android Studio project with Gradle files

EDIT

Starting with Android Studio 3.1, you should go to:

File -> Sync Project with Gradle Files


OLD

Clicking the button 'Sync Project With Gradle Files' should do the trick:

Tools -> Android -> Sync Project with Gradle Files

If that fails, try running 'Rebuild project':

Build -> Rebuild Project

Mark error in form using Bootstrap

Generally showing the error near where the error occurs is best. i.e. if someone has an error with entering their email, you highlight the email input box.

This article has a couple good examples. http://uxdesign.smashingmagazine.com/2011/05/27/getting-started-with-defensive-web-design/

Also twitter bootstrap has some nice styling that helps with that (scroll down to the Validation states section) http://twitter.github.com/bootstrap/base-css.html#forms

Highlighting each input box is a bit more complicated, so the easy way would be to just put an bootstrap alert at the top with details of what the user did wrong. http://twitter.github.com/bootstrap/components.html#alerts

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

I have resolved this Gradle caching issue like below.

In case anyone using MacBook then below is the steps I used to resolve this issue.

  1. There is a hidden Gradle folder. By using the below command we can open the hidden Gradle folder and remove the file called gradle.properties

shortcut (? + shift + G) then enter this inside popup window ~/.gradle/ press enter

file to be removed -> gradle.properties

  1. Then go back to the android studio and sync your project with Gradle files.

Multiple conditions in WHILE loop

You need to change || to && so that both conditions must be true to enter the loop.

while(myChar != 'n' && myChar != 'N')

Target a css class inside another css class

I use div instead of tables and am able to target classes within the main class, as below:

CSS

.main {
    .width: 800px;
    .margin: 0 auto;
    .text-align: center;
}
.main .table {
    width: 80%;
}
.main .row {
   / ***something ***/
}
.main .column {
    font-size: 14px;
    display: inline-block;
}
.main .left {
    width: 140px;
    margin-right: 5px;
    font-size: 12px;
}
.main .right {
    width: auto;
    margin-right: 20px;
    color: #fff;
    font-size: 13px;
    font-weight: normal;
}

HTML

<div class="main">
    <div class="table">
        <div class="row">
            <div class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>
        </div>
    </div>
</div>

If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:

.main #red { color: red; }

<div class="main">
    <div class="table">
        <div class="row">
            <div id="red" class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>
        </div>
    </div>
</div>

How do I get the name of the active user via the command line in OS X?

Via here

Checking the owner of /dev/console seems to work well.

stat -f "%Su" /dev/console

How to check if user input is not an int value

try this code [updated]:

Scanner scan = null;
       int range, smallest = 0, input;

     for(;;){
         boolean error=false;
        scan = new Scanner(System.in);
        System.out.print("Enter an integer between 1-100:  ");


            if(!scan.hasNextInt()) {
                System.out.println("Invalid input!");                      
                continue;
            }
         range = scan.nextInt();
            if(range < 1) {
                System.out.println("Invalid input!");
                error=true;
            }
        if(error)
        {
        //do nothing
        }
        else
        {
       break;
        }

        }
             for(int ii = 1; ii <= range; ii++) {
            scan = new Scanner(System.in);
            System.out.print("Enter value " + ii + ": ");

            if(!scan.hasNextInt()) {
                System.out.println("Invalid input!"); 
               ii--;
                continue;
            } 
        }

Set size of HTML page and browser window

You could try:

<html>
    <head>
        <style>
            #main {
                width: 500; /*Set to whatever*/
                height: 500;/*Set to whatever*/
            }
        </style>
    </head>
    <body id="main">
    </body>
</html>

How to disable Google asking permission to regularly check installed apps on my phone?

On Android 5.1 Lollipop for my device, click on the Google Settings icon > Security > Scan device for security threats .

Note that Google Settings is separated from the Settings app itself.

How to clear text area with a button in html using javascript?

<input type="button" value="Clear" onclick="javascript: functionName();" >

you just need to set the onclick event, call your desired function on this onclick event.

function functionName()
{
    $("#output").val("");
}

Above function will set the value of text area to empty string.

PHP - count specific array values

To count a value in a two dimensional array, here is the useful snippet to process and get count of a particular value-

    <?php
    
    $list = [
      ['id' => 1, 'userId' => 5],
      ['id' => 2, 'userId' => 5],
      ['id' => 3, 'userId' => 6],
    ];

    $userId = 5;
    
    echo array_count_values(array_column($list, 'userId'))[$userId]; // outputs: 2
    

How to parse a query string into a NameValueCollection in .NET

A lot of the answers are providing custom examples because of the accepted answer's dependency on System.Web. From the Microsoft.AspNet.WebApi.Client NuGet package there is a UriExtensions.ParseQueryString, method that can also be used:

var uri = new Uri("https://stackoverflow.com/a/22167748?p1=6&p2=7&p3=8");
NameValueCollection query = uri.ParseQueryString();

So if you want to avoid the System.Web dependency and don't want to roll your own, this is a good option.

Split a List into smaller lists of N size

List<int> orginalList =new List<int>(){1,2,3,4,5,6,7,8,9,10,12};
Dictionary<int,List<int>> dic = new Dictionary <int,List<int>> ();
int batchcount = orginalList.Count/2; //To List into two 2 parts if you 
 want three give three
List<int> lst = new List<int>();
for (int i=0;i<orginalList.Count; i++)
{
lst.Add(orginalList[i]);
if (i % batchCount == 0 && i!=0)
{
Dic.Add(threadId, lst);
lst = new List<int>();**strong text**
threadId++;
}
}
if(lst.Count>0)
Dic.Add(threadId, lst); //in case if any dayleft 
foreach(int BatchId in Dic.Keys)
{
  Console.Writeline("BatchId:"+BatchId);
  Console.Writeline('Batch Count:"+Dic[BatchId].Count);
}

Create SQL identity as primary key?

Simple change to syntax is all that is needed:

 create table ImagenesUsuario (
   idImagen int not null identity(1,1) primary key
 )

By explicitly using the "constraint" keyword, you can give the primary key constraint a particular name rather than depending on SQL Server to auto-assign a name:

 create table ImagenesUsuario (
   idImagen int not null identity(1,1) constraint pk_ImagenesUsario primary key
 )

Add the "CLUSTERED" keyword if that makes the most sense based on your use of the table (i.e., the balance of searches for a particular idImagen and amount of writing outweighs the benefits of clustering the table by some other index).

How to override trait function and call it from the overridden function?

If the class implements the method directly, it will not use the traits version. Perhaps what you are thinking of is:

trait A {
    function calc($v) {
        return $v+1;
    }
}

class MyClass {
    function calc($v) {
        return $v+2;
    }
}

class MyChildClass extends MyClass{
}

class MyTraitChildClass extends MyClass{
    use A;
}

print (new MyChildClass())->calc(2); // will print 4

print (new MyTraitChildClass())->calc(2); // will print 3

Because the child classes do not implement the method directly, they will first use that of the trait if there otherwise use that of the parent class.

If you want, the trait can use method in the parent class (assuming you know the method would be there) e.g.

trait A {
    function calc($v) {
        return parent::calc($v*3);
    }
}
// .... other code from above
print (new MyTraitChildClass())->calc(2); // will print 8 (2*3 + 2)

You can also provide for ways to override, but still access the trait method as follows:

trait A {
    function trait_calc($v) {
        return $v*3;
    }
}

class MyClass {
    function calc($v) {
        return $v+2;
    }
}


class MyTraitChildClass extends MyClass{
    use A {
      A::trait_calc as calc;
    }
}


class MySecondTraitChildClass extends MyClass{
    use A {
      A::trait_calc as calc;
    }

    public function calc($v) {
      return $this->trait_calc($v)+.5;
    }
}


print (new MyTraitChildClass())->calc(2); // will print 6
echo "\n";
print (new MySecondTraitChildClass())->calc(2); // will print 6.5

You can see it work at http://sandbox.onlinephpfunctions.com/code/e53f6e8f9834aea5e038aec4766ac7e1c19cc2b5

How do I compile a .c file on my Mac?

In 2017, this will do it:

cc myfile.c

How to create a HashMap with two keys (Key-Pair, Value)?

If they are two integers you can try a quick and dirty trick: Map<String, ?> using the key as i+"#"+j.

If the key i+"#"+j is the same as j+"#"+i try min(i,j)+"#"+max(i,j).

Test a weekly cron job

I'd use a lock file and then set the cron job to run every minute. (use crontab -e and * * * * * /path/to/job) That way you can just keep editing the files and each minute they'll be tested out. Additionally, you can stop the cronjob by just touching the lock file.

    #!/bin/sh
    if [ -e /tmp/cronlock ]
    then
        echo "cronjob locked"
        exit 1
    fi

    touch /tmp/cronlock
    <...do your regular cron here ....>
    rm -f /tmp/cronlock

Returning Promises from Vuex actions

TL:DR; return promises from you actions only when necessary, but DRY chaining the same actions.

For a long time I also though that returning actions contradicts the Vuex cycle of uni-directional data flow.

But, there are EDGE CASES where returning a promise from your actions might be "necessary".

Imagine a situation where an action can be triggered from 2 different components, and each handles the failure case differently. In that case, one would need to pass the caller component as a parameter to set different flags in the store.

Dumb example

Page where the user can edit the username in navbar and in /profile page (which contains the navbar). Both trigger an action "change username", which is asynchronous. If the promise fails, the page should only display an error in the component the user was trying to change the username from.

Of course it is a dumb example, but I don't see a way to solve this issue without duplicating code and making the same call in 2 different actions.

Validate form field only on submit or user input

You can use angularjs form state form.$submitted. Initially form.$submitted value will be false and will became true after successful form submit.

How do pointer-to-pointer's work in C? (and when might you use them?)

A pointer-to-a-pointer is used when a reference to a pointer is required. For example, when you wish to modify the value (address pointed to) of a pointer variable declared in a calling function's scope inside a called function.

If you pass a single pointer in as an argument, you will be modifying local copies of the pointer, not the original pointer in the calling scope. With a pointer to a pointer, you modify the latter.

Get user's non-truncated Active Directory groups from command line

GPRESULT is the right command, but it cannot be run without parameters. /v or verbose option is difficult to manage without also outputting to a text file. E.G. I recommend using

gpresult /user myAccount /v > C:\dev\me.txt--Ensure C:\Dev\me.txt exists

Another option is to display summary information only which may be entirely visible in the command window:

gpresult /user myAccount /r

The accounts are listed under the heading:

The user is a part of the following security groups
---------------------------------------------------

Turning Sonar off for certain code

You can annotate a class or a method with SuppressWarnings

@java.lang.SuppressWarnings("squid:S00112")

squid:S00112 in this case is a Sonar issue ID. You can find this ID in the Sonar UI. Go to Issues Drilldown. Find an issue you want to suppress warnings on. In the red issue box in your code is there a Rule link with a definition of a given issue. Once you click that you will see the ID at the top of the page.

Can I do a max(count(*)) in SQL?

it's from this site - http://sqlzoo.net/3.htm 2 possible solutions:

with TOP 1 a ORDER BY ... DESC:

SELECT yr, COUNT(title) 
FROM actor 
JOIN casting ON actor.id=actorid
JOIN movie ON movie.id=movieid
WHERE name = 'John Travolta'
GROUP BY yr
HAVING count(title)=(SELECT TOP 1 COUNT(title) 
FROM casting 
JOIN movie ON movieid=movie.id 
JOIN actor ON actor.id=actorid
WHERE name='John Travolta'
GROUP BY yr
ORDER BY count(title) desc)

with MAX:

SELECT yr, COUNT(title) 
FROM actor  
JOIN casting ON actor.id=actorid    
JOIN movie ON movie.id=movieid
WHERE name = 'John Travolta'
GROUP BY yr
HAVING 
    count(title)=
        (SELECT MAX(A.CNT) 
            FROM (SELECT COUNT(title) AS CNT FROM actor 
                JOIN casting ON actor.id=actorid
                JOIN movie ON movie.id=movieid
                    WHERE name = 'John Travolta'
                    GROUP BY (yr)) AS A)

Git command to show which specific files are ignored by .gitignore

Notes:


Also interesting (mentioned in qwertymk's answer), you can also use the git check-ignore -v command, at least on Unix (doesn't work in a CMD Windows session)

git check-ignore *
git check-ignore -v *

The second one displays the actual rule of the .gitignore which makes a file to be ignored in your git repo.
On Unix, using "What expands to all files in current directory recursively?" and a bash4+:

git check-ignore **/*

(or a find -exec command)

Note: https://stackoverflow.com/users/351947/Rafi B. suggests in the comments to avoid the (risky) globstar:

git check-ignore -v $(find . -type f -print)

Make sure to exclude the files from the .git/ subfolder though.


Original answer 42009)

git ls-files -i

should work, except its source code indicates:

if (show_ignored && !exc_given) {
                fprintf(stderr, "%s: --ignored needs some exclude pattern\n",
                        argv[0]);

exc_given ?

It turns out it need one more parameter after the -i to actually list anything:

Try:

git ls-files -i --exclude-from=[Path_To_Your_Global].gitignore

(but that would only list your cached (non-ignored) object, with a filter, so that is not quite what you want)


Example:

$ cat .git/ignore
# ignore objects and archives, anywhere in the tree.
*.[oa]
$ cat Documentation/.gitignore
# ignore generated html files,
*.html
# except foo.html which is maintained by hand
!foo.html
$ git ls-files --ignored \
    --exclude='Documentation/*.[0-9]' \
    --exclude-from=.git/ignore \
    --exclude-per-directory=.gitignore

Actually, in my 'gitignore' file (called 'exclude'), I find a command line that could help you:

F:\prog\git\test\.git\info>type exclude
# git ls-files --others --exclude-from=.git/info/exclude
# Lines that start with '#' are comments.
# For a project mostly in C, the following would be a good set of
# exclude patterns (uncomment them if you want to use them):
# *.[oa]
# *~

So....

git ls-files --ignored --exclude-from=.git/info/exclude
git ls-files -i --exclude-from=.git/info/exclude

git ls-files --others --ignored --exclude-standard
git ls-files -o -i --exclude-standard

should do the trick.

(Thanks to honzajde pointing out in the comments that git ls-files -o -i --exclude-from... does not include cached files: only git ls-files -i --exclude-from... (without -o) does.)

As mentioned in the ls-files man page, --others is the important part, in order to show you non-cached, non-committed, normally-ignored files.

--exclude_standard is not just a shortcut, but a way to include all standard "ignored patterns" settings.

exclude-standard
Add the standard git exclusions: .git/info/exclude, .gitignore in each directory, and the user's global exclusion file.

Assign multiple values to array in C

Exactly, you nearly got it:

GLfloat coordinates[8] = {1.0f, ..., 0.0f};

Remove certain characters from a string

UPDATE yourtable 
SET field_or_column =REPLACE ('current string','findpattern', 'replacepattern') 
WHERE 1

UNION with WHERE clause

NOTE: While my advice was true many years ago, Oracle's optimizer has improved so that the location of the where definitely no longer matters here. However preferring UNION ALL vs UNION will always be true, and portable SQL should avoid depending on optimizations that may not be in all databases.

Short answer, you want the WHERE before the UNION and you want to use UNION ALL if at all possible. If you are using UNION ALL then check the EXPLAIN output, Oracle might be smart enough to optimize the WHERE condition if it is left after.

The reason is the following. The definition of a UNION says that if there are duplicates in the two data sets, they have to be removed. Therefore there is an implicit GROUP BY in that operation, which tends to be slow. Worse yet, Oracle's optimizer (at least as of 3 years ago, and I don't think it has changed) doesn't try to push conditions through a GROUP BY (implicit or explicit). Therefore Oracle has to construct larger data sets than necessary, group them, and only then gets to filter. Thus prefiltering wherever possible is officially a Good Idea. (This is, incidentally, why it is important to put conditions in the WHERE whenever possible instead of leaving them in a HAVING clause.)

Furthermore if you happen to know that there won't be duplicates between the two data sets, then use UNION ALL. That is like UNION in that it concatenates datasets, but it doesn't try to deduplicate data. This saves an expensive grouping operation. In my experience it is quite common to be able to take advantage of this operation.

Since UNION ALL does not have an implicit GROUP BY in it, it is possible that Oracle's optimizer knows how to push conditions through it. I don't have Oracle sitting around to test, so you will need to test that yourself.

SQL not a single-group group function

Well the problem simply-put is that the SUM(TIME) for a specific SSN on your query is a single value, so it's objecting to MAX as it makes no sense (The maximum of a single value is meaningless).

Not sure what SQL database server you're using but I suspect you want a query more like this (Written with a MSSQL background - may need some translating to the sql server you're using):

SELECT TOP 1 SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
ORDER BY 2 DESC

This will give you the SSN with the highest total time and the total time for it.

Edit - If you have multiple with an equal time and want them all you would use:

SELECT
SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
HAVING SUM(TIME)=(SELECT MAX(SUM(TIME)) FROM downloads GROUP BY SSN))

android set button background programmatically

Using setBackgroundColor() affects the style. So, declare a new style of the same properties with respect to the previous button, with a a different color.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/green"/>
<corners android:radius="10dp"/>
</shape>

Now, use OnClick method.

location.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            location.setBackgroundResource(R.drawable.green);

        }
    });

this changes the button but looks similar to changing the background.

how to convert a string date to date format in oracle10g

You need to use the TO_DATE function.

SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;

How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

SCRIPT

 <script type="text/javascript">
    $(function(){
        $("#gender").val("Male").attr("selected","selected");
    });
 </script>

HTML

<select id="gender" selected="selected">
    <option>--Select--</option>
    <option value="1">Male</option>
    <option value="2">Female</option>
</select>

Click Here More Details

Percentage Height HTML 5/CSS

You can use 100vw / 100vh. CSS3 gives us viewport-relative units. 100vw means 100% of the viewport width. 100vh; 100% of the height.

    <div style="display:flex; justify-content: space-between;background-color: lightyellow; width:100%; height:85vh">
        <div style="width:70%; height: 100%; border: 2px dashed red"></div>
        <div style="width:30%; height: 100%; border: 2px dashed red"></div>
    </div>

How to delete a workspace in Perforce (using p4v)?

It could also be done without a visual client with the following small script.

$ cat ~/bin/pdel

#!/bin/sh

#Todo: add error handling

( p4 -c $1 client -o | perl -pne 's/\blocked\s//' | p4 -c $1  client -i ) && p4 client -d $1

How to get element by class name?

you can use

getElementsByClassName

suppose you have some elements and applied a class name 'test', so, you can get elements like as following

var tests = document.getElementsByClassName('test');

its returns an instance NodeList, or its superset: HTMLCollection (FF).

Read more

How to pass multiple checkboxes using jQuery ajax post

Could use the following and then explode the post result explode(",", $_POST['data']); to give an array of results.

var data = new Array();
$("input[name='checkBoxesName']:checked").each(function(i) {
    data.push($(this).val());
});

How do I abort/cancel TPL Tasks?

You can use a CancellationToken to control whether the task gets cancelled. Are you talking about aborting it before it's started ("nevermind, I already did this"), or actually interrupting it in middle? If the former, the CancellationToken can be helpful; if the latter, you will probably need to implement your own "bail out" mechanism and check at appropriate points in the task execution whether you should fail fast (you can still use the CancellationToken to help you, but it's a little more manual).

MSDN has an article about cancelling Tasks: http://msdn.microsoft.com/en-us/library/dd997396.aspx

Regex that matches integers in between whitespace or start/end of string only

^([+-]?[0-9]\d*|0)$

will accept numbers with leading "+", leading "-" and leadings "0"

Use of PUT vs PATCH methods in REST API real life scenarios

To conclude the discussion on the idempotency, I should note that one can define idempotency in the REST context in two ways. Let's first formalize a few things:

A resource is a function with its codomain being the class of strings. In other words, a resource is a subset of String × Any, where all the keys are unique. Let's call the class of the resources Res.

A REST operation on resources, is a function f(x: Res, y: Res): Res. Two examples of REST operations are:

  • PUT(x: Res, y: Res): Res = x, and
  • PATCH(x: Res, y: Res): Res, which works like PATCH({a: 2}, {a: 1, b: 3}) == {a: 2, b: 3}.

(This definition is specifically designed to argue about PUT and POST, and e.g. doesn't make much sense on GET and POST, as it doesn't care about persistence).

Now, by fixing x: Res (informatically speaking, using currying), PUT(x: Res) and PATCH(x: Res) are univariate functions of type Res ? Res.

  1. A function g: Res ? Res is called globally idempotent, when g ? g == g, i.e. for any y: Res, g(g(y)) = g(y).

  2. Let x: Res a resource, and k = x.keys. A function g = f(x) is called left idempotent, when for each y: Res, we have g(g(y))|? == g(y)|?. It basically means that the result should be same, if we look at the applied keys.

So, PATCH(x) is not globally idempotent, but is left idempotent. And left idempotency is the thing that matters here: if we patch a few keys of the resource, we want those keys to be same if we patch it again, and we don't care about the rest of the resource.

And when RFC is talking about PATCH not being idempotent, it is talking about global idempotency. Well, it's good that it's not globally idempotent, otherwise it would have been a broken operation.


Now, Jason Hoetger's answer is trying to demonstrate that PATCH is not even left idempotent, but it's breaking too many things to do so:

  • First of all, PATCH is used on a set, although PATCH is defined to work on maps / dictionaries / key-value objects.
  • If someone really wants to apply PATCH to sets, then there is a natural translation that should be used: t: Set<T> ? Map<T, Boolean>, defined with x in A iff t(A)(x) == True. Using this definition, patching is left idempotent.
  • In the example, this translation was not used, instead, the PATCH works like a POST. First of all, why is an ID generated for the object? And when is it generated? If the object is first compared to the elements of the set, and if no matching object is found, then the ID is generated, then again the program should work differently ({id: 1, email: "[email protected]"} must match with {email: "[email protected]"}, otherwise the program is always broken and the PATCH cannot possibly patch). If the ID is generated before checking against the set, again the program is broken.

One can make examples of PUT being non-idempotent with breaking half of the things that are broken in this example:

  • An example with generated additional features would be versioning. One may keep record of the number of changes on a single object. In this case, PUT is not idempotent: PUT /user/12 {email: "[email protected]"} results in {email: "...", version: 1} the first time, and {email: "...", version: 2} the second time.
  • Messing with the IDs, one may generate a new ID every time the object is updated, resulting in a non-idempotent PUT.

All the above examples are natural examples that one may encounter.


My final point is, that PATCH should not be globally idempotent, otherwise won't give you the desired effect. You want to change the email address of your user, without touching the rest of the information, and you don't want to overwrite the changes of another party accessing the same resource.

Find the unique values in a column and then sort them

You can also use the drop_duplicates() instead of unique()

df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].drop_duplicates()
a.sort()
print a

References with text in LaTeX

Have a look to this wiki: LaTeX/Labels and Cross-referencing:

The hyperref package automatically includes the nameref package, and a similarly named command. It inserts text corresponding to the section name, for example:

\section{MyFirstSection}
\label{marker}
\section{MySecondSection} In section \nameref{marker} we defined...

Unicode character for "X" cancel / close?

there's another one not mentioned here - nice thin - if you need that kind of look for your project: ╳

&#x2573; or decimal: &#9587;

Set background color of WPF Textbox in C# code

textBox1.Background = Brushes.Blue;
textBox1.Foreground = Brushes.Yellow;

WPF Foreground and Background is of type System.Windows.Media.Brush. You can set another color like this:

using System.Windows.Media;

textBox1.Background = Brushes.White;
textBox1.Background = new SolidColorBrush(Colors.White);
textBox1.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0, 0));
textBox1.Background = System.Windows.SystemColors.MenuHighlightBrush;

What is the use of a cursor in SQL Server?

Cursor itself is an iterator (like WHILE). By saying iterator I mean a way to traverse the record set (aka a set of selected data rows) and do operations on it while traversing. Operations could be INSERT or DELETE for example. Hence you can use it for data retrieval for example. Cursor works with the rows of the result set sequentially - row by row. A cursor can be viewed as a pointer to one row in a set of rows and can only reference one row at a time, but can move to other rows of the result set as needed.

This link can has a clear explanation of its syntax and contains additional information plus examples.

Cursors can be used in Sprocs too. They are a shortcut that allow you to use one query to do a task instead of several queries. However, cursors recognize scope and are considered undefined out of the scope of the sproc and their operations execute within a single procedure. A stored procedure cannot open, fetch, or close a cursor that was not declared in the procedure.

Storing Python dictionaries

My use case was to save multiple JSON objects to a file and marty's answer helped me somewhat. But to serve my use case, the answer was not complete as it would overwrite the old data every time a new entry was saved.

To save multiple entries in a file, one must check for the old content (i.e., read before write). A typical file holding JSON data will either have a list or an object as root. So I considered that my JSON file always has a list of objects and every time I add data to it, I simply load the list first, append my new data in it, and dump it back to a writable-only instance of file (w):

def saveJson(url,sc): # This function writes the two values to the file
    newdata = {'url':url,'sc':sc}
    json_path = "db/file.json"

    old_list= []
    with open(json_path) as myfile:  # Read the contents first
        old_list = json.load(myfile)
    old_list.append(newdata)

    with open(json_path,"w") as myfile:  # Overwrite the whole content
        json.dump(old_list, myfile, sort_keys=True, indent=4)

    return "success"

The new JSON file will look something like this:

[
    {
        "sc": "a11",
        "url": "www.google.com"
    },
    {
        "sc": "a12",
        "url": "www.google.com"
    },
    {
        "sc": "a13",
        "url": "www.google.com"
    }
]

NOTE: It is essential to have a file named file.json with [] as initial data for this approach to work

PS: not related to original question, but this approach could also be further improved by first checking if our entry already exists (based on one or multiple keys) and only then append and save the data.

Parse usable Street Address, City, State, Zip from a string

I've done a lot of work on this kind of parsing. Because there are errors you won't get 100% accuracy, but there are a few things you can do to get most of the way there, and then do a visual BS test. Here's the general way to go about it. It's not code, because it's pretty academic to write it, there's no weirdness, just lots of string handling.

(Now that you've posted some sample data, I've made some minor changes)

  1. Work backward. Start from the zip code, which will be near the end, and in one of two known formats: XXXXX or XXXXX-XXXX. If this doesn't appear, you can assume you're in the city, state portion, below.
  2. The next thing, before the zip, is going to be the state, and it'll be either in a two-letter format, or as words. You know what these will be, too -- there's only 50 of them. Also, you could soundex the words to help compensate for spelling errors.
  3. before that is the city, and it's probably on the same line as the state. You could use a zip-code database to check the city and state based on the zip, or at least use it as a BS detector.
  4. The street address will generally be one or two lines. The second line will generally be the suite number if there is one, but it could also be a PO box.
  5. It's going to be near-impossible to detect a name on the first or second line, though if it's not prefixed with a number (or if it's prefixed with an "attn:" or "attention to:" it could give you a hint as to whether it's a name or an address line.

I hope this helps somewhat.

How to drop a table if it exists?

A better visual and easy way, if you are using Visual Studio, just open from menu bar,

View -> SQL Server Object Explorer

it should open like shown here

enter image description here

Select and Right Click the Table you wish to delete, then delete. Such a screen should be displayed. Click Update Database to confirm.

enter image description here

This method is very safe as it gives you the feedback and will warn of any relations of the deleted table with other tables.

C# removing items from listbox

You can do it in 1 line, by using Linq

listBox1.Cast<ListItem>().Where(p=>p.Text.Contains("OBJECT")).ToList().ForEach(listBox1.Items.Remove);

How to access the first property of a Javascript object?

var obj = { first: 'someVal' };
obj[Object.keys(obj)[0]]; //returns 'someVal'

Using this you can access also other properties by indexes. Be aware tho! Object.keys return order is not guaranteed as per ECMAScript however unofficially it is by all major browsers implementations, please read https://stackoverflow.com/a/23202095 for details on this.

How to check if object has been disposed in C#

A good way is to derive from TcpClient and override the Disposing(bool) method:

class MyClient : TcpClient {
    public bool IsDead { get; set; }
    protected override void Dispose(bool disposing) {
        IsDead = true;
        base.Dispose(disposing);
    }
}

Which won't work if the other code created the instance. Then you'll have to do something desperate like using Reflection to get the value of the private m_CleanedUp member. Or catch the exception.

Frankly, none is this is likely to come to a very good end. You really did want to write to the TCP port. But you won't, that buggy code you can't control is now in control of your code. You've increased the impact of the bug. Talking to the owner of that code and working something out is by far the best solution.

EDIT: A reflection example:

using System.Reflection;
public static bool SocketIsDisposed(Socket s)
{
   BindingFlags bfIsDisposed = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty;
   // Retrieve a FieldInfo instance corresponding to the field
   PropertyInfo field = s.GetType().GetProperty("CleanedUp", bfIsDisposed);
   // Retrieve the value of the field, and cast as necessary
   return (bool)field.GetValue(s, null);
}

How to search for rows containing a substring?

Well, you can always try WHERE textcolumn LIKE "%SUBSTRING%" - but this is guaranteed to be pretty slow, as your query can't do an index match because you are looking for characters on the left side.

It depends on the field type - a textarea usually won't be saved as VARCHAR, but rather as (a kind of) TEXT field, so you can use the MATCH AGAINST operator.

To get the columns that don't match, simply put a NOT in front of the like: WHERE textcolumn NOT LIKE "%SUBSTRING%".

Whether the search is case-sensitive or not depends on how you stock the data, especially what COLLATION you use. By default, the search will be case-insensitive.

Updated answer to reflect question update:

I say that doing a WHERE field LIKE "%value%" is slower than WHERE field LIKE "value%" if the column field has an index, but this is still considerably faster than getting all values and having your application filter. Both scenario's:

1/ If you do SELECT field FROM table WHERE field LIKE "%value%", MySQL will scan the entire table, and only send the fields containing "value".

2/ If you do SELECT field FROM table and then have your application (in your case PHP) filter only the rows with "value" in it, MySQL will also scan the entire table, but send all the fields to PHP, which then has to do additional work. This is much slower than case #1.

Solution: Please do use the WHERE clause, and use EXPLAIN to see the performance.

Google Maps: how to get country, state/province/region, city given a lat/long value?

@Szkíta Had a great solution by creating a function that gets the address parts in a named array. Here is a compiled solution for those who want to use plain JavaScript.

Function to convert results to the named array:

function getAddressParts(obj) {

    var address = [];

    obj.address_components.forEach( function(el) {
        address[el.types[0]] = el.short_name;
    });

    return address;

} //getAddressParts()

Geocode the LAT/LNG values:

geocoder.geocode( { 'location' : latlng }, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {
        var addressParts =  getAddressParts(results[0]);

        // the city
        var city = addressParts.locality;

        // the state
        var state = addressParts.administrative_area_level_1;
    }

});

How to find a Java Memory Leak

You can find out by measuring memory usage size after calling garbage collector multiple times:

Runtime runtime = Runtime.getRuntime();

while(true) {
    ...
    if(System.currentTimeMillis() % 4000 == 0){
        System.gc();
        float usage = (float) (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024;
        System.out.println("Used memory: " + usage + "Mb");
    }

}

If the output numbers were equal, there is no memory leak in your application, but if you saw difference between the numbers of memory usage (increasing numbers), there is memory leak in your project. For example:

Used memory: 14.603279Mb
Used memory: 14.737213Mb
Used memory: 14.772224Mb
Used memory: 14.802681Mb
Used memory: 14.840599Mb
Used memory: 14.900841Mb
Used memory: 14.942261Mb
Used memory: 14.976143Mb

Note that sometimes it takes some time to release memory by some actions like streams and sockets. You should not judge by first outputs, You should test it in a specific amount of time.

Finding a branch point with Git?

After a lot of research and discussions, it's clear there's no magic bullet that would work in all situations, at least not in the current version of Git.

That's why I wrote a couple of patches that add the concept of a tail branch. Each time a branch is created, a pointer to the original point is created too, the tail ref. This ref gets updated every time the branch is rebased.

To find out the branch point of the devel branch, all you have to do is use devel@{tail}, that's it.

https://github.com/felipec/git/commits/fc/tail

What does "&" at the end of a linux command mean?

I don’t know for sure but I’m reading a book right now and what I am getting is that a program need to handle its signal ( as when I press CTRL-C). Now a program can use SIG_IGN to ignore all signals or SIG_DFL to restore the default action.

Now if you do $ command & then this process running as background process simply ignores all signals that will occur. For foreground processes these signals are not ignored.

How do I store the select column in a variable?

This is how to assign a value to a variable:

SELECT @EmpID = Id
  FROM dbo.Employee

However, the above query is returning more than one value. You'll need to add a WHERE clause in order to return a single Id value.

Spring Boot JPA - configuring auto reconnect

As some people already pointed out, spring-boot 1.4+, has specific namespaces for the four connections pools. By default, hikaricp is used in spring-boot 2+. So you will have to specify the SQL here. The default is SELECT 1. Here's what you would need for DB2 for example: spring.datasource.hikari.connection-test-query=SELECT current date FROM sysibm.sysdummy1

Caveat: If your driver supports JDBC4 we strongly recommend not setting this property. This is for "legacy" drivers that do not support the JDBC4 Connection.isValid() API. This is the query that will be executed just before a connection is given to you from the pool to validate that the connection to the database is still alive. Again, try running the pool without this property, HikariCP will log an error if your driver is not JDBC4 compliant to let you know. Default: none

Error loading the SDK when Eclipse starts

Check the

  • Android wear ARM EABI
  • Android wear Intel x86

Than delete them and restart Eclipse IDE. This should fix the problem.

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

Can I append an array to 'formdata' in javascript?

We can simply do like this.

_x000D_
_x000D_
formData = new FormData;
words = ["apple", "ball", "cat"]
words.forEach((item) => formData.append("words[]", item))

// verify the data
console.log(formData.getAll("words[]"))
//["apple", "ball", "cat"]
_x000D_
_x000D_
_x000D_

On server-side you will get words = ["apple", "ball", "cat"]

When to use a linked list over an array/array list?

Arrays, by far, are the most widely used data structures. However, linked lists prove useful in their own unique way where arrays are clumsy - or expensive, to say the least.

Linked lists are useful to implement stacks and queues in situations where their size is subject to vary. Each node in the linked list can be pushed or popped without disturbing the majority of the nodes. Same goes for insertion/deletion of nodes somewhere in the middle. In arrays, however, all the elements have to be shifted, which is an expensive job in terms of execution time.

Binary trees and binary search trees, hash tables, and tries are some of the data structures wherein - at least in C - you need linked lists as a fundamental ingredient for building them up.

However, linked lists should be avoided in situations where it is expected to be able to call any arbitrary element by its index.

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

 

Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

  <dependencies>
    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>4.0.4</version>
    </dependency>
  </dependencies>

 

Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

ucanaccess-4.0.1.jar  
  /lib/
    commons-lang-2.6.jar  
    commons-logging-1.1.1.jar  
    hsqldb.jar  
    jackcess-2.1.6.jar

All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

BuildPath.png

NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

nbAddJar.png

After adding all five (5) JAR files the "Libraries" folder should look something like this:

nbLibraries.png

IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

IntelliJ.png

 

That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

 

Disclosure

At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

How can I check if a JSON is empty in NodeJS?

If you have compatibility with Object.keys, and node does have compatibility, you should use that for sure.

However, if you do not have compatibility, and for any reason using a loop function is out of the question - like me, I used the following solution:

JSON.stringify(obj) === '{}'

Consider this solution a 'last resort' use only if must.

See in the comments "there are many ways in which this solution is not ideal".

I had a last resort scenario, and it worked perfectly.

Use HTML5 to resize an image before upload

if any interested I've made a typescript version:

interface IResizeImageOptions {
  maxSize: number;
  file: File;
}
const resizeImage = (settings: IResizeImageOptions) => {
  const file = settings.file;
  const maxSize = settings.maxSize;
  const reader = new FileReader();
  const image = new Image();
  const canvas = document.createElement('canvas');
  const dataURItoBlob = (dataURI: string) => {
    const bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
        atob(dataURI.split(',')[1]) :
        unescape(dataURI.split(',')[1]);
    const mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
    const max = bytes.length;
    const ia = new Uint8Array(max);
    for (var i = 0; i < max; i++) ia[i] = bytes.charCodeAt(i);
    return new Blob([ia], {type:mime});
  };
  const resize = () => {
    let width = image.width;
    let height = image.height;

    if (width > height) {
        if (width > maxSize) {
            height *= maxSize / width;
            width = maxSize;
        }
    } else {
        if (height > maxSize) {
            width *= maxSize / height;
            height = maxSize;
        }
    }

    canvas.width = width;
    canvas.height = height;
    canvas.getContext('2d').drawImage(image, 0, 0, width, height);
    let dataUrl = canvas.toDataURL('image/jpeg');
    return dataURItoBlob(dataUrl);
  };

  return new Promise((ok, no) => {
      if (!file.type.match(/image.*/)) {
        no(new Error("Not an image"));
        return;
      }

      reader.onload = (readerEvent: any) => {
        image.onload = () => ok(resize());
        image.src = readerEvent.target.result;
      };
      reader.readAsDataURL(file);
  })    
};

and here's the javascript result:

var resizeImage = function (settings) {
    var file = settings.file;
    var maxSize = settings.maxSize;
    var reader = new FileReader();
    var image = new Image();
    var canvas = document.createElement('canvas');
    var dataURItoBlob = function (dataURI) {
        var bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
            atob(dataURI.split(',')[1]) :
            unescape(dataURI.split(',')[1]);
        var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
        var max = bytes.length;
        var ia = new Uint8Array(max);
        for (var i = 0; i < max; i++)
            ia[i] = bytes.charCodeAt(i);
        return new Blob([ia], { type: mime });
    };
    var resize = function () {
        var width = image.width;
        var height = image.height;
        if (width > height) {
            if (width > maxSize) {
                height *= maxSize / width;
                width = maxSize;
            }
        } else {
            if (height > maxSize) {
                width *= maxSize / height;
                height = maxSize;
            }
        }
        canvas.width = width;
        canvas.height = height;
        canvas.getContext('2d').drawImage(image, 0, 0, width, height);
        var dataUrl = canvas.toDataURL('image/jpeg');
        return dataURItoBlob(dataUrl);
    };
    return new Promise(function (ok, no) {
        if (!file.type.match(/image.*/)) {
            no(new Error("Not an image"));
            return;
        }
        reader.onload = function (readerEvent) {
            image.onload = function () { return ok(resize()); };
            image.src = readerEvent.target.result;
        };
        reader.readAsDataURL(file);
    });
};

usage is like:

resizeImage({
    file: $image.files[0],
    maxSize: 500
}).then(function (resizedImage) {
    console.log("upload resized image")
}).catch(function (err) {
    console.error(err);
});

or (async/await):

const config = {
    file: $image.files[0],
    maxSize: 500
};
const resizedImage = await resizeImage(config)
console.log("upload resized image")

Applying function with multiple arguments to create a new pandas column

Alternatively, you can use numpy underlying function:

>>> import numpy as np
>>> df = pd.DataFrame({"A": [10,20,30], "B": [20, 30, 10]})
>>> df['new_column'] = np.multiply(df['A'], df['B'])
>>> df
    A   B  new_column
0  10  20         200
1  20  30         600
2  30  10         300

or vectorize arbitrary function in general case:

>>> def fx(x, y):
...     return x*y
...
>>> df['new_column'] = np.vectorize(fx)(df['A'], df['B'])
>>> df
    A   B  new_column
0  10  20         200
1  20  30         600
2  30  10         300

Setting ANDROID_HOME enviromental variable on Mac OS X

A lot of correct answers here. However, one item is missing and I wasn't able to run the emulator from the command line without it.

export JAVA_HOME=$(/usr/libexec/java_home)
export PATH=$PATH:$JAVA_HOME/bin

export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/emulator       # can't run emulator without it
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/platform-tools

So it's a compilation of the answers above plus a solution for this problem.

And if you use zsh (instead of bash) the file to edit is ~/.zshrc.

Difference between window.location.href=window.location.href and window.location.reload()

If I remember correctly, window.location.reload() reloads the current page with POST data, while window.location.href=window.location.href does not include the POST data.

As noted by @W3Max in the comments below, window.location.href=window.location.href will not reload the page if there's an anchor (#) in the URL - You must use window.location.reload() in this case.

Also, as noted by @Mic below, window.location.reload() takes an additional argument skipCache so that with using window.location.reload(true) the browser will skip the cache and reload the page from the server. window.location.reload(false) will do the opposite, and load the page from cache if possible.

String.Format for Hex

The number 0 in {0:X} refers to the position in the list or arguments. In this case 0 means use the first value, which is Blue. Use {1:X} for the second argument (Green), and so on.

colorstring = String.Format("#{0:X}{1:X}{2:X}{3:X}", Blue, Green, Red, Space);

The syntax for the format parameter is described in the documentation:

Format Item Syntax

Each format item takes the following form and consists of the following components:

{ index[,alignment][:formatString]}

The matching braces ("{" and "}") are required.

Index Component

The mandatory index component, also called a parameter specifier, is a number starting from 0 that identifies a corresponding item in the list of objects. That is, the format item whose parameter specifier is 0 formats the first object in the list, the format item whose parameter specifier is 1 formats the second object in the list, and so on.

Multiple format items can refer to the same element in the list of objects by specifying the same parameter specifier. For example, you can format the same numeric value in hexadecimal, scientific, and number format by specifying a composite format string like this: "{0:X} {0:E} {0:N}".

Each format item can refer to any object in the list. For example, if there are three objects, you can format the second, first, and third object by specifying a composite format string like this: "{1} {0} {2}". An object that is not referenced by a format item is ignored. A runtime exception results if a parameter specifier designates an item outside the bounds of the list of objects.

Alignment Component

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

Format String Component

The optional formatString component is a format string that is appropriate for the type of object being formatted. Specify a standard or custom numeric format string if the corresponding object is a numeric value, a standard or custom date and time format string if the corresponding object is a DateTime object, or an enumeration format string if the corresponding object is an enumeration value. If formatString is not specified, the general ("G") format specifier for a numeric, date and time, or enumeration type is used. The colon is required if formatString is specified.

Note that in your case you only have the index and the format string. You have not specified (and do not need) an alignment component.

Select where count of one field is greater than one

It should also be mentioned that the "pk" should be a key field. The self-join

SELECT t1.* FROM db.table t1
JOIN db.table t2 ON t1.someField = t2.someField AND t1.pk != t2.pk 

by Bill Karwin give you all the records that are duplicates which is what I wanted. Because some have more than two, you can get the same record more than once. I wrote all to another table with the same fields to get rid of the same records by key fields suppression. I tried

SELECT * FROM db.table HAVING COUNT(someField) > 1

above first. The data returned from it give only one of the duplicates, less than 1/2 of what this gives you but the count is good if that is all you want.

Node.js - How to send data from html to express

I'd like to expand on Obertklep's answer. In his example it is an NPM module called body-parser which is doing most of the work. Where he puts req.body.name, I believe he/she is using body-parser to get the contents of the name attribute(s) received when the form is submitted.

If you do not want to use Express, use querystring which is a built-in Node module. See the answers in the link below for an example of how to use querystring.

It might help to look at this answer, which is very similar to your quest.

PostgreSQL - max number of parameters in "IN" clause?

You might want to consider refactoring that query instead of adding an arbitrarily long list of ids... You could use a range if the ids indeed follow the pattern in your example:

SELECT * FROM user WHERE id >= minValue AND id <= maxValue;

Another option is to add an inner select:

SELECT * 
FROM user 
WHERE id IN (
    SELECT userId
    FROM ForumThreads ft
    WHERE ft.id = X
);

MySQL Select Date Equal to Today

This query will use index if you have it for signup_date field

SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d') 
    FROM users 
    WHERE signup_date >= CURDATE() && signup_date < (CURDATE() + INTERVAL 1 DAY)

How to parse freeform street/postal address out of text, and into components

There are many street address parsers. They come in two basic flavors - ones that have databases of place names and street names, and ones that don't.

A regular expression street address parser can get up to about a 95% success rate without much trouble. Then you start hitting the unusual cases. The Perl one in CPAN, "Geo::StreetAddress::US", is about that good. There are Python and Javascript ports of that, all open source. I have an improved version in Python which moves the success rate up slightly by handling more cases. To get the last 3% right, though, you need databases to help with disambiguation.

A database with 3-digit ZIP codes and US state names and abbreviations is a big help. When a parser sees a consistent postal code and state name, it can start to lock on to the format. This works very well for the US and UK.

Proper street address parsing starts from the end and works backwards. That's how the USPS systems do it. Addresses are least ambiguous at the end, where country names, city names, and postal codes are relatively easy to recognize. Street names can usually be isolated. Locations on streets are the most complex to parse; there you encounter things such as "Fifth Floor" and "Staples Pavillion". That's when a database is a big help.

How can I preview a merge in git?

Pull Request - I've used most of the already submitted ideas but one that I also often use is ( especially if its from another dev ) doing a Pull Request which gives a handy way to review all of the changes in a merge before it takes place. I know that is GitHub not git but it sure is handy.

I want to use CASE statement to update some records in sql server 2005

Add a WHERE clause

UPDATE dbo.TestStudents  
SET     LASTNAME =  CASE  
                        WHEN LASTNAME = 'AAA' THEN 'BBB' 
                        WHEN LASTNAME = 'CCC' THEN 'DDD' 
                        WHEN LASTNAME = 'EEE' THEN 'FFF' 
                        ELSE LASTNAME
                    END 
WHERE   LASTNAME IN ('AAA', 'CCC', 'EEE')

what is difference between success and .done() method of $.ajax

In short, decoupling success callback function from the ajax function so later you can add your own handlers without modifying the original code (observer pattern).

Please find more detailed information from here: https://stackoverflow.com/a/14754681/1049184

Calculate the mean by group

We already have tons of options to get mean by group, adding one more from mosaic package.

mosaic::mean(speed~dive, data = df)
#dive1 dive2 
#0.579 0.440 

This returns a named numeric vector, if needed a dataframe we can wrap it in stack

stack(mosaic::mean(speed~dive, data = df))

#  values   ind
#1  0.579 dive1
#2  0.440 dive2

data

set.seed(123)
df <- data.frame(dive=factor(sample(c("dive1","dive2"),10,replace=TRUE)),
                 speed=runif(10))

Shrink to fit content in flexbox, or flex-basis: content workaround?

I want columns One and Two to shrink/grow to fit rather than being fixed.

Have you tried: flex-basis: auto

or this:

flex: 1 1 auto, which is short for:

  • flex-grow: 1 (grow proportionally)
  • flex-shrink: 1 (shrink proportionally)
  • flex-basis: auto (initial size based on content size)

or this:

main > section:first-child {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:nth-child(2) {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:last-child {
    flex: 20 1 auto;
    display: flex;
    flex-direction: column;  
}

revised demo

Related:

PHP: Read Specific Line From File

I would use the SplFileObject class...

$file = new SplFileObject("filename");
if (!$file->eof()) {
     $file->seek($lineNumber);
     $contents = $file->current(); // $contents would hold the data from line x
}

C++ sorting and keeping track of indexes

Suppose Given vector is

A=[2,4,3]

Create a new vector

V=[0,1,2] // indicating positions

Sort V and while sorting instead of comparing elements of V , compare corresponding elements of A

 //Assume A is a given vector with N elements
 vector<int> V(N);
 int x=0;
 std::iota(V.begin(),V.end(),x++); //Initializing
 sort( V.begin(),V.end(), [&](int i,int j){return A[i]<A[j];} );

How can I get the DateTime for the start of the week?

Following on from Compile This' Answer, use the following method to obtain the date for any day of the week:

public static DateTime GetDayOfWeek(DateTime dateTime, DayOfWeek dayOfWeek)
{
   var monday = dateTime.Date.AddDays((7 + (dateTime.DayOfWeek - DayOfWeek.Monday) % 7) * -1);

   var diff = dayOfWeek - DayOfWeek.Monday;

   if (diff == -1)
   {
      diff = 6;
   }

   return monday.AddDays(diff);
} 

How can I specify a display?

I through vnc to understand the X11 more. To specify the display to get a many-displayed program, export DISPLAY=IP:DisplayNum.ScreenNum

For example,

vncserver :2
vncserver -list
echo '$DISPLAY'=$DISPLAY 
export DISPLAY=:2  # export DISPLAY=IP:DisplayNum or export DISPLAY=:DisplayNum for localhost; So that can vnc connect and see the vnc desktop :2 if $DISPLAY is not :2.
echo '$DISPLAY'=$DISPLAY

Are "while(true)" loops so bad?

To me, the problem is readability.

A while statement with a true condition tells you nothing about the loop. It makes the job of understanding it much more difficult.

What would be easier to understand out of these two snippets?

do {
  // Imagine a nice chunk of code here
} while(true);

do {
  // Imagine a nice chunk of code here
} while(price < priceAllowedForDiscount);

How to write data with FileOutputStream without losing old data?

Use the constructor for appending material to the file:

FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.

So to append to a file say "abc.txt" use

FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);

pandas dataframe convert column type to string or categorical

To convert a column into a string type (that will be an object column per se in pandas), use astype:

df.zipcode = zipcode.astype(str)

If you want to get a Categorical column, you can pass the parameter 'category' to the function:

df.zipcode = zipcode.astype('category')

Prevent textbox autofill with previously entered values

Trying from the CodeBehind:

Textbox1.Attributes.Add("autocomplete", "off");