Programs & Examples On #Visual studio setup

Use this tag to ask questions related to visual studio project setup.

How to test an Internet connection with bash?

I've written scripts before that simply use telnet to connect to port 80, then transmit the text:

HTTP/1.0 GET /index.html

followed by two CR/LF sequences.

Provided you get back some form of HTTP response, you can generally assume the site is functioning.

Euclidean distance of two vectors

If you want to use less code, you can also use the norm in the stats package (the 'F' stands for Forbenius, which is the Euclidean norm):

norm(matrix(x1-x2), 'F')

While this may look a bit neater, it's not faster. Indeed, a quick test on very large vectors shows little difference, though so12311's method is slightly faster. We first define:

set.seed(1234)
x1 <- rnorm(300000000)
x2 <- rnorm(300000000)

Then testing for time yields the following:

> system.time(a<-sqrt(sum((x1-x2)^2)))
user  system elapsed 
1.02    0.12    1.18 
> system.time(b<-norm(matrix(x1-x2), 'F'))
user  system elapsed 
0.97    0.33    1.31 

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

You can change the class of the entire table and use the cascade in the CSS: http://jsbin.com/oyunuy/1/

How do I get my Maven Integration tests to run

You should use maven surefire plugin to run unit tests and maven failsafe plugin to run integration tests.

Please follow below if you wish to toggle the execution of these tests using flags.

Maven Configuration

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <skipTests>${skipUnitTests}</skipTests>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <configuration>
                <includes>
                    <include>**/*IT.java</include>
                </includes>
                <skipTests>${skipIntegrationTests}</skipTests>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>integration-test</goal>
                        <goal>verify</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

        <properties>
            <skipTests>false</skipTests>
            <skipUnitTests>${skipTests}</skipUnitTests>
            <skipIntegrationTests>${skipTests}</skipIntegrationTests>
        </properties>

So, tests will be skipped or switched according to below flag rules:

Tests can be skipped by below flags:

  • -DskipTests skips both unit and integration tests
  • -DskipUnitTests skips unit tests but executes integration tests
  • -DskipIntegrationTests skips integration tests but executes unit tests

Running Tests

Run below to execute only Unit Tests

mvn clean test

You can execute below command to run the tests (both unit and integration)

mvn clean verify

In order to run only Integration Tests, follow

mvn failsafe:integration-test

Or skip unit tests

mvn clean install -DskipUnitTests

Also, in order to skip integration tests during mvn install, follow

mvn clean install -DskipIntegrationTests

You can skip all tests using

mvn clean install -DskipTests

Makefile: How to correctly include header file and its directory?

The preprocessor is looking for StdCUtil/split.h in

and in

  • $INC_DIR (i.e. ../StdCUtil/ = /root/Core/../StdCUtil/ = /root/StdCUtil/). So ../StdCUtil/ + StdCUtil/split.h = ../StdCUtil/StdCUtil/split.h and the file is missing

You can fix the error changing the $INC_DIR variable (best solution):

$INC_DIR = ../

or the include directive:

#include "split.h"

but in this way you lost the "path syntax" that makes it very clear what namespace or module the header file belongs to.

Reference:

EDIT/UPDATE

It should also be

CXX = g++
CXXFLAGS = -c -Wall -I$(INC_DIR)

...

%.o: %.cpp $(DEPS)
    $(CXX) -o $@ $< $(CXXFLAGS)

Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes

I had the exact same error (on windows 7) and the cause was different. I solved it in a different way so I thought I'd add the cause and solution here for others.

Even though the error seemed to point to heroku really the error was saying "Heroku can't get to the git repository". I swore I had the same keys on all the servers because I created it and uploaded it to one after the other at the same time.

After spending almost a day on this I realized that because git was only showing me the fingerprint and not the actual key. I couldn't verify that it's key matched the one on my HD or heroku. I looked in the known hosts file and guess what... it shows the keys for each server and I was able to clearly see that the git and heroku public keys did not match.

1) I deleted all the files in my key folder, the key from github using their website, and the key from heroku using git bash and the command heroku keys:clear

2) Followed github's instructions here to generate a new key pair and upload the public key to git

3) using git bash- heroku keys:add to upload the same key to heroku.

Now git push heroku master works.

what a nightmare, hope this helped somebody.

Bryan

How do I keep track of pip-installed packages in an Anaconda (Conda) environment?

conda will only keep track of the packages it installed. And pip will give you the packages that were either installed using the pip installer itself or they used setuptools in their setup.py so conda build generated the egg information. So you have basically three options.

  1. You can take the union of the conda list and pip freeze and manage packages that were installed using conda (that show in the conda list) with the conda package manager and the ones that are installed with pip (that show in pip freeze but not in conda list) with pip.

  2. Install in your environment only the python, pip and distribute packages and manage everything with pip. (This is not that trivial if you're on Windows...)

  3. Build your own conda packages, and manage everything with conda.

I would personally recommend the third option since it's very easy to build conda packages. There is a git repository of example recipes on the continuum's github account. But it usually boils down to:

 conda skeleton pypi PACKAGE
 conda build PACKAGE

or just:

conda pipbuild PACKAGE

Also when you have built them once, you can upload them to https://binstar.org/ and just install from there.

Then you'll have everything managed using conda.

Can a table have two foreign keys?

CREATE TABLE User (
user_id INT NOT NULL AUTO_INCREMENT,
userName VARCHAR(100) NOT NULL,
password VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
userImage  LONGBLOB NOT NULL, 
Favorite VARCHAR(255) NOT NULL,
PRIMARY KEY (user_id)
);

and

CREATE TABLE Event (
    EventID INT NOT NULL AUTO_INCREMENT, 
    PRIMARY KEY (EventID),
    EventName VARCHAR(100) NOT NULL,
    EventLocation VARCHAR(100) NOT NULL,
    EventPriceRange VARCHAR(100) NOT NULL,
    EventDate Date NOT NULL,
    EventTime Time NOT NULL,
    EventDescription VARCHAR(255) NOT NULL,
    EventCategory VARCHAR(255) NOT NULL,
    EventImage  LONGBLOB NOT NULL,     
    index(EventID),
    FOREIGN KEY (EventID) REFERENCES User(user_id)
);

Looping through all rows in a table column, Excel-VBA

You can loop through the cells of any column in a table by knowing just its name and not its position. If the table is in sheet1 of the workbook:

Dim rngCol as Range
Dim cl as Range
Set rngCol = Sheet1.Range("TableName[ColumnName]")
For Each cl in rngCol
    cl.Value = "PHEV"
Next cl

The code above will loop through the data values only, excluding the header row and the totals row. It is not necessary to specify the number of rows in the table.

Use this to find the location of any column in a table by its column name:

Dim colNum as Long
colNum = Range("TableName[Column name to search for]").Column

This returns the numeric position of a column in the table.

Get the current user, within an ApiController action, without passing the userID as a parameter

Karan Bhandari's answer is good, but the AccountController added in a project is very likely a Mvc.Controller. To convert his answer for use in an ApiController change HttpContext.Current.GetOwinContext() to Request.GetOwinContext() and make sure you have added the following 2 using statements:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

What is the maximum recursion depth in Python, and how to increase it?

It is a guard against a stack overflow, yes. Python (or rather, the CPython implementation) doesn't optimize tail recursion, and unbridled recursion causes stack overflows. You can check the recursion limit with sys.getrecursionlimit:

import sys
print(sys.getrecursionlimit())

and change the recursion limit with sys.setrecursionlimit:

sys.setrecursionlimit(1500)

but doing so is dangerous -- the standard limit is a little conservative, but Python stackframes can be quite big.

Python isn't a functional language and tail recursion is not a particularly efficient technique. Rewriting the algorithm iteratively, if possible, is generally a better idea.

Is there a better way to iterate over two lists, getting one element from each list for each iteration?

Iterating through elements of two lists simultaneously is known as zipping, and python provides a built in function for it, which is documented here.

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
True

[Example is taken from pydocs]

In your case, it will be simply:

for (lat, lon) in zip(latitudes, longitudes):
    ... process lat and lon

Tree view of a directory/folder in Windows?

tree /f /a

About

The Windows command tree /f /a produces a tree of the current folder and all files & folders contained within it in ASCII format.

The output can be redirected to a text file using the > parameter.

Method

For Windows 8.1 or Windows 10, follow these steps:

  1. Navigate into the folder in file explorer.
  2. Press Shift, right-click mouse, and select "Open command window here".
  3. Type tree /f /a > tree.txt and press Enter.
  4. Open the new tree.txt file in your favourite text editor/viewer.

Note: Windows 7, Vista, XP and earlier users can type cmd in the run command box in the start menu for a command window.

Nth max salary in Oracle

select min(sal) from (select distinct sal from employee order by sal DESC) where rownum<=N;

place the number whatever the highest sal you want to retrieve.

Best way to add Gradle support to IntelliJ Project

  1. Add build.gradle in your project's root directory.

  2. Then just File -> Invalidate Caches / Restart

Here is a basic build.gradle for Java projects:

plugins {
    id 'java'
}

sourceCompatibility = '1.8'
targetCompatibility = '1.8'
version = '1.2.1'

Kubernetes service external ip pending

If you are not using GCE or EKS (you used kubeadm) you can add an externalIPs spec to your service YAML. You can use the IP associated with your node's primary interface such as eth0. You can then access the service externally, using the external IP of the node.

...
spec:
  type: LoadBalancer
  externalIPs:
  - 192.168.0.10

Can't run Curl command inside my Docker Container

Ran into this same issue while using the CURL command inside my Dockerfile. As Gilles pointed out, we have to install curl first. These are the commands to be added in the 'Dockerfile'.

FROM ubuntu:16.04

# Install prerequisites
RUN apt-get update && apt-get install -y \
curl
CMD /bin/bash

pull/push from multiple remote locations

I took the liberty to expand the answer from nona-urbiz; just add this to your ~/.bashrc:

git-pullall () { for RMT in $(git remote); do git pull -v $RMT $1; done; }    
alias git-pullall=git-pullall

git-pushall () { for RMT in $(git remote); do git push -v $RMT $1; done; }
alias git-pushall=git-pushall

Usage:

git-pullall master

git-pushall master ## or
git-pushall

If you do not provide any branch argument for git-pullall then the pull from non-default remotes will fail; left this behavior as it is, since it's analogous to git.

What are the Differences Between "php artisan dump-autoload" and "composer dump-autoload"?

Laravel's Autoload is a bit different:

1) It will in fact use Composer for some stuff

2) It will call Composer with the optimize flag

3) It will 'recompile' loads of files creating the huge bootstrap/compiled.php

4) And also will find all of your Workbench packages and composer dump-autoload them, one by one.

Eclipse Indigo - Cannot install Android ADT Plugin

None of the existing answers worked for me. Having all the correct update sites in "available sites" was not enough to tell Eclipse how to find its dependencies.

Using Fedora 14 and Eclipse Indigo 3.7.1, I had to follow these steps to make the installation working:

  1. Check and install "Linux Tools" from http://download.eclipse.org/releases/indigo
  2. Check and install "Linux Tools" from http://download.eclipse.org/releases/indigo/201109230900

After restarting Eclipse, I was able to finaly install the Android SDK.

What is the meaning of polyfills in HTML5?

A polyfill is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively.

Clear the cache in JavaScript

You can call window.location.reload(true) to reload the current page. It will ignore any cached items and retrieve new copies of the page, css, images, JavaScript, etc from the server. This doesn't clear the whole cache, but has the effect of clearing the cache for the page you are on.

However, your best strategy is to version the path or filename as mentioned in various other answers. In addition, see Revving Filenames: don’t use querystring for reasons not to use ?v=n as your versioning scheme.

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="1048576" />
    </system.web>
</configuration>

From here.

For IIS7 and above, you also need to add the lines below:

 <system.webServer>
   <security>
      <requestFiltering>
         <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
   </security>
 </system.webServer>

sql searching multiple words in a string

Oracle SQL:

There is the "IN" Operator in Oracle SQL which can be used for that:

select 
    namet.customerfirstname, addrt.city, addrt.postalcode
from schemax.nametable namet
join schemax.addresstable addrt on addrt.adtid = namet.natadtid
where namet.customerfirstname in ('David', 'Moses', 'Robi'); 

Module 'tensorflow' has no attribute 'contrib'

tf.contrib has moved out of TF starting TF 2.0 alpha.
Take a look at these tf 2.0 release notes https://github.com/tensorflow/tensorflow/releases/tag/v2.0.0-alpha0
You can upgrade your TF 1.x code to TF 2.x using the tf_upgrade_v2 script https://www.tensorflow.org/alpha/guide/upgrade

Correct use of flush() in JPA/Hibernate

Can em.flush() cause any harm when using it within a transaction?

Yes, it may hold locks in the database for a longer duration than necessary.

Generally, When using JPA you delegates the transaction management to the container (a.k.a CMT - using @Transactional annotation on business methods) which means that a transaction is automatically started when entering the method and commited / rolled back at the end. If you let the EntityManager handle the database synchronization, sql statements execution will be only triggered just before the commit, leading to short lived locks in database. Otherwise your manually flushed write operations may retain locks between the manual flush and the automatic commit which can be long according to remaining method execution time.

Notes that some operation automatically triggers a flush : executing a native query against the same session (EM state must be flushed to be reachable by the SQL query), inserting entities using native generated id (generated by the database, so the insert statement must be triggered thus the EM is able to retrieve the generated id and properly manage relationships)

ORA-00918: column ambiguously defined in SELECT *

A query's projection can only have one instance of a given name. As your WHERE clause shows, you have several tables with a column called ID. Because you are selecting * your projection will have several columns called ID. Or it would have were it not for the compiler hurling ORA-00918.

The solution is quite simple: you will have to expand the projection to explicitly select named columns. Then you can either leave out the duplicate columns, retaining just (say) COACHES.ID or use column aliases: coaches.id as COACHES_ID.

Perhaps that strikes you as a lot of typing, but it is the only way. If it is any comfort, SELECT * is regarded as bad practice in production code: explicitly named columns are much safer.

How do I escape spaces in path for scp copy in Linux?

Sorry for using this Linux question to put this tip for Powershell on Windows 10: the space char escaping with backslashes or surrounding with quotes didn't work for me in this case. Not efficient, but I solved it using the "?" char instead:

for the file "tasks.txt Jun-22.bkp" I downloaded it using "tasks.txt?Jun-22.bkp"

Escaping ampersand character in SQL string

I wrote a regex to help find and replace "&" within an INSERT, I hope that this helps someone.

The trick was to make sure that the "&" was with other text.

Find “(\'[^\']*(?=\&))(\&)([^\']*\')”

Replace “$1' || chr(38) || '$3”

what is the use of xsi:schemaLocation?

The Java XML parser that spring uses will read the schemaLocation values and try to load them from the internet, in order to validate the XML file. Spring, in turn, intercepts those load requests and serves up versions from inside its own JAR files.

If you omit the schemaLocation, then the XML parser won't know where to get the schema in order to validate the config.

Allow click on twitter bootstrap dropdown toggle link?

Here's a little hack that switched from data-hover to data-toggle depending the screen width:

/**
 * Bootstrap nav menu hack
 */
$(window).on('load', function () {
    // On page load
    if ($(window).width() < 768) {
        $('.navbar-nav > li > .dropdown-toggle').removeAttr('data-hover').attr('data-toggle', 'dropdown');
    }

    // On window resize
    $(window).resize(function () {
        if ($(window).width() < 768) {
            $('.navbar-nav > li > .dropdown-toggle').removeAttr('data-hover').attr('data-toggle', 'dropdown');
        } else {
            $('.navbar-nav > li > .dropdown-toggle').removeAttr('data-toggle').attr('data-hover', 'dropdown');
        }
    });
});

Find object by its property in array of objects with AngularJS way

For complete M B answer, if you want to access to an specific attribute of this object already filtered from the array in your HTML, you will have to do it in this way:

{{ (myArray | filter : {'id':73})[0].name }}

So, in this case, it will print john in the HTML.

Regards!

Mysql - delete from multiple tables with one query

You can use following query to delete rows from multiple tables,

DELETE table1, table2, table3 FROM table1 INNER JOIN table2 INNER JOIN table3 WHERE table1.userid = table2.userid AND table2.userid = table3.userid AND table1.userid=3

How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?

With Python 3.8 this workes for me. For instance to execute a python script within the venv:

    import subprocess
    import sys
    res = subprocess.run([
              sys.executable,            # venv3.8/bin/python
              'main.py', '--help',], 
            stdout=PIPE, 
            text=True)
    print(res.stdout)

How to hide the border for specified rows of a table?

You can simply add these lines of codes here to hide a row,

Either you can write border:0 or border-style:hidden; border: none or it will happen the same thing

_x000D_
_x000D_
<style type="text/css">_x000D_
              table, th, td {_x000D_
               border: 1px solid;_x000D_
              }_x000D_
              _x000D_
              tr.hide_all > td, td.hide_all{_x000D_
                 border: 0;_x000D_
                _x000D_
              }_x000D_
          }_x000D_
        </style>_x000D_
    <table>_x000D_
      <tr>_x000D_
        <th>Firstname</th>_x000D_
        <th>Lastname</th>_x000D_
        <th>Savings</th>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Peter</td>_x000D_
        <td>Griffin</td>_x000D_
        <td>$100</td>_x000D_
      </tr>_x000D_
      <tr class= hide_all>_x000D_
        <td>Lois</td>_x000D_
        <td>Griffin</td>_x000D_
        <td>$150</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Joe</td>_x000D_
        <td>Swanson</td>_x000D_
        <td>$300</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Cleveland</td>_x000D_
        <td>Brown</td>_x000D_
        <td>$250</td>_x000D_
      </tr>_x000D_
    </table>
_x000D_
_x000D_
_x000D_

running these lines of codes can solve the problem easily

What is monkey patching?

First: monkey patching is an evil hack (in my opinion).

It is often used to replace a method on the module or class level with a custom implementation.

The most common usecase is adding a workaround for a bug in a module or class when you can't replace the original code. In this case you replace the "wrong" code through monkey patching with an implementation inside your own module/package.

How to add jQuery in JS file

If document.write('<\script ...') isn't working, try document.createElement('script')...

Other than that, you should be worried about the type of website you're making - do you really think its a good idea to include .js files from .js files?

Creating a blurring overlay view

In case this helps anyone, here is a swift extension I created based on the answer by Jordan H. It is written in Swift 5 and can be used from Objective C.

extension UIView {

    @objc func blurBackground(style: UIBlurEffect.Style, fallbackColor: UIColor) {
        if !UIAccessibility.isReduceTransparencyEnabled {
            self.backgroundColor = .clear

            let blurEffect = UIBlurEffect(style: style)
            let blurEffectView = UIVisualEffectView(effect: blurEffect)
            //always fill the view
            blurEffectView.frame = self.self.bounds
            blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

            self.insertSubview(blurEffectView, at: 0)
        } else {
            self.backgroundColor = fallbackColor
        }
    }

}

NOTE: If you want to blur the background of an UILabel without affecting the text, you should create a container UIView, add the UILabel to the container UIView as a subview, set the UILabel's backgroundColor to UIColor.clear, and then call blurBackground(style: UIBlurEffect.Style, fallbackColor: UIColor) on the container UIView. Here's a quick example of this written in Swift 5:

let frame = CGRect(x: 50, y: 200, width: 200, height: 50)
let containerView = UIView(frame: frame)
let label = UILabel(frame: frame)
label.text = "Some Text"
label.backgroundColor = UIColor.clear
containerView.addSubview(label)
containerView.blurBackground(style: .dark, fallbackColor: UIColor.black)

Proper way of checking if row exists in table in PL/SQL block

Select 'YOU WILL SEE ME' as ANSWER from dual
where exists (select 1 from dual where 1 = 1);

Select 'YOU CAN NOT SEE ME' as ANSWER from dual
where exists (select 1 from dual where 1 = 0);

Select 'YOU WILL SEE ME, TOO' as ANSWER from dual
where not exists (select 1 from dual where 1 = 0);

Checkout subdirectories in Git?

You can't checkout a single directory of a repository because the entire repository is handled by the single .git folder in the root of the project instead of subversion's myriad of .svn directories.

The problem with working on plugins in a single repository is that making a commit to, e.g., mytheme will increment the revision number for myplugin, so even in subversion it is better to use separate repositories.

The subversion paradigm for sub-projects is svn:externals which translates somewhat to submodules in git (but not exactly in case you've used svn:externals before.)

using awk with column value conditions

My awk version is 3.1.5.

Yes, the input file is space separated, no tabs.

According to arutaku's answer, here's what I tried that worked:

awk '$8 ~ "ClNonZ"{ print $3; }' test  
0.180467091
0.010615711
0.492569002


$ awk '$8 ~ "ClNonZ" { print $3}' test  
0.180467091
0.010615711
0.492569002

What didn't work(I don't know why and maybe due to my awk version:),

$awk '$8 ~ "^ClNonZ$"{ print $3; }' test
$awk '$8 == "ClNonZ" { print $3 }' test

Thank you all for your answers, comments and help!

What is ".NET Core"?

.NET Core is a new cross-platform implementation of .NET standards (ECMA 335) similar to Mono but done by Microsoft itself.

See docs.microsoft.com

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

This is a better method :-

void main()throws IOException
{
    System.out.println("Enter sentence");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String str = br.readLine();
    String sentence = "";
    for(int i=0;i<str.length();i++)
    {
        if(Character.isUpperCase(str.charAt(i))==true)
        {
            char ch2= (char)(str.charAt(i)+32);
            sentence = sentence + ch2;
        }
        else if(Character.isLowerCase(str.charAt(i))==true)
        {
            char ch2= (char)(str.charAt(i)-32);
            sentence = sentence + ch2;
        }
        else
        sentence= sentence + str.charAt(i);

    }
    System.out.println(sentence);
}

Why does JavaScript only work after opening developer tools in IE once?

I put the resolution and fix for my issue . Looks like AJAX request that I put inside my JavaScript was not processing because my page was having some cache problem. if your site or page has a caching problem you will not see that problem in developers/F12 mode. my cached JavaScript AJAX requests it may not work as expected and cause the execution to break which F12 has no problem at all. So just added new parameter to make cache false.

$.ajax({
  cache: false,
});

Looks like IE specifically needs this to be false so that the AJAX and javascript activity run well.

Catch an exception thrown by an async void method

This blog explains your problem neatly Async Best Practices.

The gist of it being you shouldn't use void as return for an async method, unless it's an async event handler, this is bad practice because it doesn't allow exceptions to be caught ;-).

Best practice would be to change the return type to Task. Also, try to code async all the way trough, make every async method call and be called from async methods. Except for a Main method in a console, which can't be async (before C# 7.1).

You will run into deadlocks with GUI and ASP.NET applications if you ignore this best practice. The deadlock occurs because these applications runs on a context that allows only one thread and won't relinquish it to the async thread. This means the GUI waits synchronously for a return, while the async method waits for the context: deadlock.

This behaviour won't happen in a console application, because it runs on context with a thread pool. The async method will return on another thread which will be scheduled. This is why a test console app will work, but the same calls will deadlock in other applications...

How to force reloading php.ini file?

You also can use graceful restart the apache server with service apache2 reload or apachectl -k graceful. As the apache doc says:

The USR1 or graceful signal causes the parent process to advise the children to exit after their current request (or to exit immediately if they're not serving anything). The parent re-reads its configuration files and re-opens its log files. As each child dies off the parent replaces it with a child from the new generation of the configuration, which begins serving new requests immediately.

How can I get the content of CKEditor using JQuery?

To get data of ckeditor, you need to get ckeditor instance

HTML code:

<textarea class="form-control" id="reply_mail_msg" name="message" rows="3" data-form-field="Message" placeholder="" autofocus="" style="display: none;"></textarea>

Javascript:

var ck_ed = CKEDITOR.instances.reply_mail_msg.getData();

Oracle: how to set user password unexpire?

If you create a user using a profile like this:

CREATE PROFILE my_profile LIMIT
       PASSWORD_LIFE_TIME 30;
ALTER USER scott PROFILE my_profile;

then you can change the password lifetime like this:

ALTER PROFILE my_profile LIMIT
  PASSWORD_LIFE_TIME UNLIMITED;

I hope that helps.

Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

Had a similar problem and was getting the following errors depending on what app I used and if we bypassed the firewall / load balancer or not:

HTTPS handshake to [blah] (for #136) failed. System.IO.IOException Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host

and

ReadResponse() failed: The server did not return a complete response for this request. Server returned 0 bytes.

The problem turned out to be that the SSL Server Certificate got missed and wasn't installed on a couple servers.

Creating a constant Dictionary in C#

Creating a truly compile-time generated constant dictionary in C# is not really a straightforward task. Actually, none of the answers here really achieve that.

There is one solution though which meets your requirements, although not necessarily a nice one; remember that according to the C# specification, switch-case tables are compiled to constant hash jump tables. That is, they are constant dictionaries, not a series of if-else statements. So consider a switch-case statement like this:

switch (myString)
{
   case "cat": return 0;
   case "dog": return 1;
   case "elephant": return 3;
}

This is exactly what you want. And yes, I know, it's ugly.

Handle spring security authentication exceptions with @ExceptionHandler

I'm using the objectMapper. Every Rest Service is mostly working with json, and in one of your configs you have already configured an object mapper.

Code is written in Kotlin, hopefully it will be ok.

@Bean
fun objectMapper(): ObjectMapper {
    val objectMapper = ObjectMapper()
    objectMapper.registerModule(JodaModule())
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)

    return objectMapper
}

class UnauthorizedAuthenticationEntryPoint : BasicAuthenticationEntryPoint() {

    @Autowired
    lateinit var objectMapper: ObjectMapper

    @Throws(IOException::class, ServletException::class)
    override fun commence(request: HttpServletRequest, response: HttpServletResponse, authException: AuthenticationException) {
        response.addHeader("Content-Type", "application/json")
        response.status = HttpServletResponse.SC_UNAUTHORIZED

        val responseError = ResponseError(
            message = "${authException.message}",
        )

        objectMapper.writeValue(response.writer, responseError)
     }}

Passing arrays as parameters in bash

Just to add to the accepted answer, as I found it doesn't work well if the array contents are someting like:

RUN_COMMANDS=(
  "command1 param1... paramN"
  "command2 param1... paramN"
)

In this case, each member of the array gets split, so the array the function sees is equivalent to:

RUN_COMMANDS=(
    "command1"
    "param1"
     ...
    "command2"
    ...
)

To get this case to work, the way I found is to pass the variable name to the function, then use eval:

function () {
    eval 'COMMANDS=( "${'"$1"'[@]}" )'
    for COMMAND in "${COMMANDS[@]}"; do
        echo $COMMAND
    done
}

function RUN_COMMANDS

Just my 2©

Right way to write JSON deserializer in Spring or extend it

I was trying to @Autowire a Spring-managed service into my Deserializer. Somebody tipped me off to Jackson using the new operator when invoking the serializers/deserializers. This meant no auto-wiring of Jackson's instance of my Deserializer. Here's how I was able to @Autowire my service class into my Deserializer:

context.xml

<mvc:annotation-driven>
  <mvc:message-converters>
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
      <property name="objectMapper" ref="objectMapper" />
    </bean>
  </mvc:message-converters>
</mvc>
<bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
    <!-- Add deserializers that require autowiring -->
    <property name="deserializersByType">
        <map key-type="java.lang.Class">
            <entry key="com.acme.Anchor">
                <bean class="com.acme.AnchorDeserializer" />
            </entry>
        </map>
    </property>
</bean>

Now that my Deserializer is a Spring-managed bean, auto-wiring works!

AnchorDeserializer.java

public class AnchorDeserializer extends JsonDeserializer<Anchor> {
    @Autowired
    private AnchorService anchorService;
    public Anchor deserialize(JsonParser parser, DeserializationContext context)
             throws IOException, JsonProcessingException {
        // Do stuff
    }
}

AnchorService.java

@Service
public class AnchorService {}

Update: While my original answer worked for me back when I wrote this, @xi.lin's response is exactly what is needed. Nice find!

Is there a Google Voice API?

Well... These are PHP. There is an sms one from google here.

And github has one here.

Another sms one is here. However, this one has a lot more code, so it may take up more space.

How do I URl encode something in Node.js?

encodeURIComponent(string) will do it:

encodeURIComponent("Robert'); DROP TABLE Students;--")
//>> "Robert')%3B%20DROP%20TABLE%20Students%3B--"

Passing SQL around in a query string might not be a good plan though,

see this one

How to Programmatically Add Views to Views

One more way to add view from Activity

ViewGroup rootLayout = findViewById(android.R.id.content);
rootLayout.addView(view);

how to get right offset of an element? - jQuery

Alex, Gary:

As requested, here is my comment posted as an answer:

var rt = ($(window).width() - ($whatever.offset().left + $whatever.outerWidth()));

Thanks for letting me know.

In pseudo code that can be expressed as:

The right offset is:

The window's width MINUS
( The element's left offset PLUS the element's outer width )

Sass and combined child selector

Without the combined child selector you would probably do something similar to this:

foo {
  bar {
    baz {
      color: red;
    }
  }
}

If you want to reproduce the same syntax with >, you could to this:

foo {
  > bar {
    > baz {
      color: red;
    }
  }
}

This compiles to this:

foo > bar > baz {
  color: red;
}

Or in sass:

foo
  > bar
    > baz
      color: red

Node: log in a file instead of the console

Another solution not mentioned yet is by hooking the Writable streams in process.stdout and process.stderr. This way you don't need to override all the console functions that output to stdout and stderr. This implementation redirects both stdout and stderr to a log file:

var log_file = require('fs').createWriteStream(__dirname + '/log.txt', {flags : 'w'})

function hook_stream(stream, callback) {
    var old_write = stream.write

    stream.write = (function(write) {
        return function(string, encoding, fd) {
            write.apply(stream, arguments)  // comments this line if you don't want output in the console
            callback(string, encoding, fd)
        }
    })(stream.write)

    return function() {
        stream.write = old_write
    }
}

console.log('a')
console.error('b')

var unhook_stdout = hook_stream(process.stdout, function(string, encoding, fd) {
    log_file.write(string, encoding)
})

var unhook_stderr = hook_stream(process.stderr, function(string, encoding, fd) {
    log_file.write(string, encoding)
})

console.log('c')
console.error('d')

unhook_stdout()
unhook_stderr()

console.log('e')
console.error('f')

It should print in the console

a
b
c
d
e
f

and in the log file:

c
d

For more info, check this gist.

How do malloc() and free() work?

Well it depends on the memory allocator implementation and the OS.

Under windows for example a process can ask for a page or more of RAM. The OS then assigns those pages to the process. This is not, however, memory allocated to your application. The CRT memory allocator will mark the memory as a contiguous "available" block. The CRT memory allocator will then run through the list of free blocks and find the smallest possible block that it can use. It will then take as much of that block as it needs and add it to an "allocated" list. Attached to the head of the actual memory allocation will be a header. This header will contain various bit of information (it could, for example, contain the next and previous allocated blocks to form a linked list. It will most probably contain the size of the allocation).

Free will then remove the header and add it back to the free memory list. If it forms a larger block with the surrounding free blocks these will be added together to give a larger block. If a whole page is now free the allocator will, most likely, return the page to the OS.

It is not a simple problem. The OS allocator portion is completely out of your control. I recommend you read through something like Doug Lea's Malloc (DLMalloc) to get an understanding of how a fairly fast allocator will work.

Edit: Your crash will be caused by the fact that by writing larger than the allocation you have overwritten the next memory header. This way when it frees it gets very confused as to what exactly it is free'ing and how to merge into the following block. This may not always cause a crash straight away on the free. It may cause a crash later on. In general avoid memory overwrites!

iPhone Safari Web App opens links in new window

I prefer to open all links inside the standalone web app mode except ones that have target="_blank". Using jQuery, of course.

$(document).on('click', 'a', function(e) {
    if ($(this).attr('target') !== '_blank') {
        e.preventDefault();
        window.location = $(this).attr('href');
    }
});

What is the difference between SAX and DOM?

You are correct in your understanding of the DOM based model. The XML file will be loaded as a whole and all its contents will be built as an in-memory representation of the tree the document represents. This can be time- and memory-consuming, depending on how large the input file is. The benefit of this approach is that you can easily query any part of the document, and freely manipulate all the nodes in the tree.

The DOM approach is typically used for small XML structures (where small depends on how much horsepower and memory your platform has) that may need to be modified and queried in different ways once they have been loaded.

SAX on the other hand is designed to handle XML input of virtually any size. Instead of the XML framework doing the hard work for you in figuring out the structure of the document and preparing potentially lots of objects for all the nodes, attributes etc., SAX completely leaves that to you.

What it basically does is read the input from the top and invoke callback methods you provide when certain "events" occur. An event might be hitting an opening tag, an attribute in the tag, finding text inside an element or coming across an end-tag.

SAX stubbornly reads the input and tells you what it sees in this fashion. It is up to you to maintain all state-information you require. Usually this means you will build up some sort of state-machine.

While this approach to XML processing is a lot more tedious, it can be very powerful, too. Imagine you want to just extract the titles of news articles from a blog feed. If you read this XML using DOM it would load all the article contents, all the images etc. that are contained in the XML into memory, even though you are not even interested in it.

With SAX you can just check if the element name is (e. g.) "title" whenever your "startTag" event method is called. If so, you know that you needs to add whatever the next "elementText" event offers you. When you receive the "endTag" event call, you check again if this is the closing element of the "title". After that, you just ignore all further elements, until either the input ends, or another "startTag" with a name of "title" comes along. And so on...

You could read through megabytes and megabytes of XML this way, just extracting the tiny amount of data you need.

The negative side of this approach is of course, that you need to do a lot more book-keeping yourself, depending on what data you need to extract and how complicated the XML structure is. Furthermore, you naturally cannot modify the structure of the XML tree, because you never have it in hand as a whole.

So in general, SAX is suitable for combing through potentially large amounts of data you receive with a specific "query" in mind, but need not modify, while DOM is more aimed at giving you full flexibility in changing structure and contents, at the expense of higher resource demand.

Fill remaining vertical space with CSS using display:flex

Use the flex-grow property to the main content div and give the dispaly: flex; to its parent;

_x000D_
_x000D_
body {_x000D_
    height: 100%;_x000D_
    position: absolute;_x000D_
    margin: 0;_x000D_
}_x000D_
section {_x000D_
  height: 100%;_x000D_
  display: flex;_x000D_
  flex-direction : column;_x000D_
}_x000D_
header {_x000D_
  background: tomato;_x000D_
}_x000D_
div {_x000D_
  flex: 1; /* or flex-grow: 1  */;_x000D_
  overflow-x: auto;_x000D_
  background: gold;_x000D_
}_x000D_
footer {_x000D_
  background: lightgreen;_x000D_
  min-height: 60px;_x000D_
}
_x000D_
<section>_x000D_
  <header>_x000D_
    header: sized to content_x000D_
    <br>(but is it really?)_x000D_
  </header>_x000D_
  <div>_x000D_
    main content: fills remaining space<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
  </div>_x000D_
  <footer>_x000D_
    footer: fixed height in px_x000D_
  </footer>_x000D_
</section>
_x000D_
_x000D_
_x000D_

jQuery hasClass() - check for more than one class

What about:

if($('.class.class2.class3').length > 0){
    //...
}

Why can't I declare static methods in an interface?

The reason lies in the design-principle, that java does not allow multiple inheritance. The problem with multiple inheritance can be illustrated by the following example:

public class A {
   public method x() {...}
}
public class B {
   public method x() {...}
}
public class C extends A, B { ... }

Now what happens if you call C.x()? Will be A.x() or B.x() executed? Every language with multiple inheritance has to solve this problem.

Interfaces allow in Java some sort of restricted multiple inheritance. To avoid the problem above, they are not allowed to have methods. If we look at the same problem with interfaces and static methods:

public interface A {
   public static method x() {...}
}
public interface B {
   public static method x() {...}
}
public class C implements A, B { ... }

Same problem here, what happen if you call C.x()?

How to read file binary in C#?

Well, reading it isn't hard, just use FileStream to read a byte[]. Converting it to text isn't really generally possible or meaningful unless you convert the 1's and 0's to hex. That's easy to do with the BitConverter.ToString(byte[]) overload. You'd generally want to dump 16 or 32 bytes in each line. You could use Encoding.ASCII.GetString() to try to convert the bytes to characters. A sample program that does this:

using System;
using System.IO;
using System.Text;

class Program {
    static void Main(string[] args) {
        // Read the file into <bits>
        var fs = new FileStream(@"c:\temp\test.bin", FileMode.Open);
        var len = (int)fs.Length;
        var bits = new byte[len];
        fs.Read(bits, 0, len);
        // Dump 16 bytes per line
        for (int ix = 0; ix < len; ix += 16) {
            var cnt = Math.Min(16, len - ix);
            var line = new byte[cnt];
            Array.Copy(bits, ix, line, 0, cnt);
            // Write address + hex + ascii
            Console.Write("{0:X6}  ", ix);
            Console.Write(BitConverter.ToString(line));
            Console.Write("  ");
            // Convert non-ascii characters to .
            for (int jx = 0; jx < cnt; ++jx)
                if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';
            Console.WriteLine(Encoding.ASCII.GetString(line));
        }
        Console.ReadLine();
    }
}

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

Under Apache 2+ you can simply do as below (Using Linux Terminal):

sudo a2enmod rewrite && sudo service apache2 restart

or

sudo a2enmod rewrite && sudo /etc/init.d/apache2 restart

How can I know if a branch has been already merged into master?

git branch --merged master lists branches merged into master

git branch --merged lists branches merged into HEAD (i.e. tip of current branch)

git branch --no-merged lists branches that have not been merged

By default this applies to only the local branches. The -a flag will show both local and remote branches, and the -r flag shows only the remote branches.

Finding repeated words on a string and counting the repetitions

I hope this will help you

public void countInPara(String str) {

    Map<Integer,String> strMap = new HashMap<Integer,String>();
    List<String> paraWords = Arrays.asList(str.split(" "));
    Set<String> strSet = new LinkedHashSet<>(paraWords);
    int count;

    for(String word : strSet) {
        count = Collections.frequency(paraWords, word);
        strMap.put(count, strMap.get(count)==null ? word : strMap.get(count).concat(","+word));
    }

    for(Map.Entry<Integer,String> entry : strMap.entrySet())
        System.out.println(entry.getKey() +" :: "+ entry.getValue());
}

Reading Xml with XmlReader in C#

The following example navigates through the stream to determine the current node type, and then uses XmlWriter to output the XmlReader content.

    StringBuilder output = new StringBuilder();

    String xmlString =
            @"<?xml version='1.0'?>
            <!-- This is a sample XML document -->
            <Items>
              <Item>test with a child element <more/> stuff</Item>
            </Items>";
    // Create an XmlReader
    using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
    {
        XmlWriterSettings ws = new XmlWriterSettings();
        ws.Indent = true;
        using (XmlWriter writer = XmlWriter.Create(output, ws))
        {

            // Parse the file and display each of the nodes.
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        writer.WriteStartElement(reader.Name);
                        break;
                    case XmlNodeType.Text:
                        writer.WriteString(reader.Value);
                        break;
                    case XmlNodeType.XmlDeclaration:
                    case XmlNodeType.ProcessingInstruction:
                        writer.WriteProcessingInstruction(reader.Name, reader.Value);
                        break;
                    case XmlNodeType.Comment:
                        writer.WriteComment(reader.Value);
                        break;
                    case XmlNodeType.EndElement:
                        writer.WriteFullEndElement();
                        break;
                }
            }

        }
    }
    OutputTextBlock.Text = output.ToString();

The following example uses the XmlReader methods to read the content of elements and attributes.

StringBuilder output = new StringBuilder();

String xmlString =
    @"<bookstore>
        <book genre='autobiography' publicationdate='1981-03-22' ISBN='1-861003-11-0'>
            <title>The Autobiography of Benjamin Franklin</title>
            <author>
                <first-name>Benjamin</first-name>
                <last-name>Franklin</last-name>
            </author>
            <price>8.99</price>
        </book>
    </bookstore>";

// Create an XmlReader
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
    reader.ReadToFollowing("book");
    reader.MoveToFirstAttribute();
    string genre = reader.Value;
    output.AppendLine("The genre value: " + genre);

    reader.ReadToFollowing("title");
    output.AppendLine("Content of the title element: " + reader.ReadElementContentAsString());
}

OutputTextBlock.Text = output.ToString();

How do you make Git work with IntelliJ?

Literally, just restarted IntelliJ after it kept showing this "install git" message after I have pressed and installed git, and it disappeared, and git works

Change color of PNG image via CSS?

In most browsers, you can use filters :

  • on both <img> elements and background images of other elements

  • and set them either statically in your CSS, or dynamically using JavaScript

See demos below.


<img> elements

You can apply this technique to a <img> element :

_x000D_
_x000D_
#original, #changed {_x000D_
    width: 45%;_x000D_
    padding: 2.5%;_x000D_
    float: left;_x000D_
}_x000D_
_x000D_
#changed {_x000D_
    -webkit-filter : hue-rotate(180deg);_x000D_
    filter : hue-rotate(180deg);_x000D_
}
_x000D_
<img id="original" src="http://i.stack.imgur.com/rfar2.jpg" />_x000D_
_x000D_
<img id="changed" src="http://i.stack.imgur.com/rfar2.jpg" />
_x000D_
_x000D_
_x000D_

Background images

You can apply this technique to a background image :

_x000D_
_x000D_
#original, #changed {_x000D_
    background: url('http://i.stack.imgur.com/kaKzj.jpg');_x000D_
    background-size: cover;_x000D_
    width: 30%;_x000D_
    margin: 0 10% 0 10%;_x000D_
    padding-bottom: 28%;_x000D_
    float: left;_x000D_
}_x000D_
_x000D_
#changed {_x000D_
    -webkit-filter : hue-rotate(180deg);_x000D_
    filter : hue-rotate(180deg);_x000D_
}
_x000D_
<div id="original"></div>_x000D_
_x000D_
<div id="changed"></div>
_x000D_
_x000D_
_x000D_

JavaScript

You can use JavaScript to set a filter at runtime :

_x000D_
_x000D_
var element = document.getElementById("changed");_x000D_
var filter = 'hue-rotate(120deg) saturate(2.4)';_x000D_
element.style['-webkit-filter'] = filter;_x000D_
element.style['filter'] = filter;
_x000D_
#original, #changed {_x000D_
    margin: 0 10%;_x000D_
    width: 30%;_x000D_
    float: left;_x000D_
    background: url('http://i.stack.imgur.com/856IQ.png');_x000D_
    background-size: cover;_x000D_
    padding-bottom: 25%;_x000D_
}
_x000D_
<div id="original"></div>_x000D_
_x000D_
<div id="changed"></div>
_x000D_
_x000D_
_x000D_

How do I get a list of installed CPAN modules?

I wrote a perl script just yesterday to do exactly this. The script returns the list of perl modules installed in @INC using the '::' as the separator. Call the script using -

perl perlmod.pl

OR

perl perlmod.pl <module name> #Case-insensitive(eg. perl perlmod.pl ftp)

As of now the script skips the current directory('.') since I was having problems with recursing soft-links but you can include it by changing the grep function in line 17 from

  grep { $_ !~ '^\.$' } @INC

to just,

@INC

The script can be found here.

What is a good Hash Function?

A good hash function should

  1. be bijective to not loose information, where possible, and have the least collisions
  2. cascade as much and as evenly as possible, i.e. each input bit should flip every output bit with probability 0.5 and without obvious patterns.
  3. if used in a cryptographic context there should not exist an efficient way to invert it.

A prime number modulus does not satisfy any of these points. It is simply insufficient. It is often better than nothing, but it's not even fast. Multiplying with an unsigned integer and taking a power-of-two modulus distributes the values just as well, that is not well at all, but with only about 2 cpu cycles it is much faster than the 15 to 40 a prime modulus will take (yes integer division really is that slow).

To create a hash function that is fast and distributes the values well the best option is to compose it from fast permutations with lesser qualities like they did with PCG for random number generation.

Useful permutations, among others, are:

  • multiplication with an uneven integer
  • binary rotations
  • xorshift

Following this recipe we can create our own hash function or we take splitmix which is tested and well accepted.

If cryptographic qualities are needed I would highly recommend to use a function of the sha family, which is well tested and standardised, but for educational purposes this is how you would make one:

First you take a good non-cryptographic hash function, then you apply a one-way function like exponentiation on a prime field or k many applications of (n*(n+1)/2) mod 2^k interspersed with an xorshift when k is the number of bits in the resulting hash.

Iterating through a variable length array

Arrays have an implicit member variable holding the length:

for(int i=0; i<myArray.length; i++) {
    System.out.println(myArray[i]);
}

Alternatively if using >=java5, use a for each loop:

for(Object o : myArray) {
    System.out.println(o);
}

Angular 2: import external js file into component

The following approach worked in Angular 5 CLI.

For sake of simplicity, I used similar d3gauge.js demo created and provided by oliverbinns - which you may easily find on Github.

So first, I simply created a new folder named externalJS on same level as the assets folder. I then copied the 2 following .js files.

  • d3.v3.min.js
  • d3gauge.js

I then made sure to declare both linked directives in main index.html

<script src="./externalJS/d3.v3.min.js"></script>
<script src="./externalJS/d3gauge.js"></script>

I then added a similar code in a gauge.component.ts component as followed:

import { Component, OnInit } from '@angular/core';

declare var d3gauge:any; <----- !
declare var drawGauge: any; <-----!

@Component({
  selector: 'app-gauge',
  templateUrl: './gauge.component.html'
})

export class GaugeComponent implements OnInit {
   constructor() { }

   ngOnInit() {
      this.createD3Gauge();
   }

   createD3Gauge() { 
      let gauges = []
      document.addEventListener("DOMContentLoaded", function (event) {      
      let opt = {
         gaugeRadius: 160,
         minVal: 0,
         maxVal: 100,
         needleVal: Math.round(30),
         tickSpaceMinVal: 1,
         tickSpaceMajVal: 10,
         divID: "gaugeBox",
         gaugeUnits: "%"
    } 

    gauges[0] = new drawGauge(opt);
    });
 }

}

and finally, I simply added a div in corresponding gauge.component.html

<div id="gaugeBox"></div>

et voilà ! :)

enter image description here

What's the difference between echo, print, and print_r in PHP?

**Echocan accept multiple expressions while print cannot. The Print_r () PHP function is used to return an array in a human readable form. It is simply written as

![Print_r ($your_array)][1]

How to search if dictionary value contains certain string with Python

I am a bit late, but another way is to use list comprehension and the any function, that takes an iterable and returns True whenever one element is True :

# Checking if string 'Mary' exists in the lists of the dictionary values
print any(any('Mary' in s for s in subList) for subList in myDict.values())

If you wanna count the number of element that have "Mary" in them, you can use sum():

# Number of sublists containing 'Mary'
print sum(any('Mary' in s for s in subList) for subList in myDict.values())

# Number of strings containing 'Mary'
print sum(sum('Mary' in s for s in subList) for subList in myDict.values())

From these methods, we can easily make functions to check which are the keys or values matching.

To get the keys containing 'Mary':

def matchingKeys(dictionary, searchString):
    return [key for key,val in dictionary.items() if any(searchString in s for s in val)]

To get the sublists:

def matchingValues(dictionary, searchString):
    return [val for val in dictionary.values() if any(searchString in s for s in val)]

To get the strings:

def matchingValues(dictionary, searchString):
    return [s for s i for val in dictionary.values() if any(searchString in s for s in val)]

To get both:

def matchingElements(dictionary, searchString):
    return {key:val for key,val in dictionary.items() if any(searchString in s for s in val)}

And if you want to get only the strings containing "Mary", you can do a double list comprehension :

def matchingStrings(dictionary, searchString):
    return [s for val in dictionary.values() for s in val if searchString in s]

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

If you want using Internet in your app as well as check the network state i.e. Is app is connected to the internet then you have to use below code outside of the application tag.

For Internet Permission:

<uses-permission android:name="android.permission.INTERNET" />

For Access network state:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Complete Code:

<uses-sdk
    android:minSdkVersion="9"
    android:targetSdkVersion="16" />

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >


    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

How to fill color in a cell in VBA?

Non VBA Solution:

Use Conditional Formatting rule with formula: =ISNA(A1) (to highlight cells with all errors - not only #N/A, use =ISERROR(A1))

enter image description here

VBA Solution:

Your code loops through 50 mln cells. To reduce number of cells, I use .SpecialCells(xlCellTypeFormulas, 16) and .SpecialCells(xlCellTypeConstants, 16)to return only cells with errors (note, I'm using If cell.Text = "#N/A" Then)

Sub ColorCells()
    Dim Data As Range, Data2 As Range, cell As Range
    Dim currentsheet As Worksheet

    Set currentsheet = ActiveWorkbook.Sheets("Comparison")

    With currentsheet.Range("A2:AW" & Rows.Count)
        .Interior.Color = xlNone
        On Error Resume Next
        'select only cells with errors
        Set Data = .SpecialCells(xlCellTypeFormulas, 16)
        Set Data2 = .SpecialCells(xlCellTypeConstants, 16)
        On Error GoTo 0
    End With

    If Not Data2 Is Nothing Then
        If Not Data Is Nothing Then
            Set Data = Union(Data, Data2)
        Else
            Set Data = Data2
        End If
    End If

    If Not Data Is Nothing Then
        For Each cell In Data
            If cell.Text = "#N/A" Then
               cell.Interior.ColorIndex = 4
            End If
        Next
    End If
End Sub

Note, to highlight cells witn any error (not only "#N/A"), replace following code

If Not Data Is Nothing Then
   For Each cell In Data
       If cell.Text = "#N/A" Then
          cell.Interior.ColorIndex = 3
       End If
   Next
End If

with

If Not Data Is Nothing Then Data.Interior.ColorIndex = 3

UPD: (how to add CF rule through VBA)

Sub test()
    With ActiveWorkbook.Sheets("Comparison").Range("A2:AW" & Rows.Count).FormatConditions
        .Delete
        .Add Type:=xlExpression, Formula1:="=ISNA(A1)"
        .Item(1).Interior.ColorIndex = 3
    End With
End Sub

A valid provisioning profile for this executable was not found for debug mode

This looks like a bug (I'm using XCode 7.3.1).

Trying to use XCode->Product->Profile spat out the "no valid provision profile" error.

By sheer dumb luck I got it working simply by running the app on my attached device using a normal compile, then going to the "Debug Navigator" and clicking on "Profile in Instruments" in the top right corner.

enter image description here

Sending email through Gmail SMTP server with C#

I've had some problems sending emails from my gmail account too, which were due to several of the aforementioned situations. Here's a summary of how I got it working, and keeping it flexible at the same time:

  • First of all setup your GMail account:
    • Enable IMAP and assert the right maximum number of messages (you can do so here)
    • Make sure your password is at least 7 characters and is strong (according to Google)
    • Make sure you don't have to enter a captcha code first. You can do so by sending a test email from your browser.
  • Make changes in web.config (or app.config, I haven't tried that yet but I assume it's just as easy to make it work in a windows application):
<configuration>
    <appSettings>
        <add key="EnableSSLOnMail" value="True"/>   
    </appSettings>

    <!-- other settings --> 

    ...

    <!-- system.net settings -->
    <system.net>
        <mailSettings>
            <smtp from="[email protected]" deliveryMethod="Network">
                <network 
                    defaultCredentials="false" 
                    host="smtp.gmail.com" 
                    port="587" 
                    password="stR0ngPassW0rd" 
                    userName="[email protected]"
                    />
                <!-- When using .Net 4.0 (or later) add attribute: enableSsl="true" and you're all set-->
            </smtp>
        </mailSettings>
    </system.net>
</configuration>
Add a Class to your project:

Imports System.Net.Mail

Public Class SSLMail

    Public Shared Sub SendMail(ByVal e As System.Web.UI.WebControls.MailMessageEventArgs)

        GetSmtpClient.Send(e.Message)

        'Since the message is sent here, set cancel=true so the original SmtpClient will not try to send the message too:
        e.Cancel = True

    End Sub

    Public Shared Sub SendMail(ByVal Msg As MailMessage)
        GetSmtpClient.Send(Msg)
    End Sub

    Public Shared Function GetSmtpClient() As SmtpClient

        Dim smtp As New Net.Mail.SmtpClient
        'Read EnableSSL setting from web.config
        smtp.EnableSsl = CBool(ConfigurationManager.AppSettings("EnableSSLOnMail"))
        Return smtp
    End Function

End Class

And now whenever you want to send emails all you need to do is call SSLMail.SendMail:

e.g. in a Page with a PasswordRecovery control:

Partial Class RecoverPassword
Inherits System.Web.UI.Page

Protected Sub RecoverPwd_SendingMail(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MailMessageEventArgs) Handles RecoverPwd.SendingMail
    e.Message.Bcc.Add("[email protected]")
    SSLMail.SendMail(e)
End Sub

End Class

Or anywhere in your code you can call:

SSLMail.SendMail(New system.Net.Mail.MailMessage("[email protected]","[email protected]", "Subject", "Body"})

I hope this helps anyone who runs into this post! (I used VB.NET but I think it's trivial to convert it to any .NET language.)

How many times does each value appear in a column?

You can use CountIf. Put the following code in B1 and drag down the whole column

=COUNTIF(A:A,A1)

It will look like this:

enter image description here

Multiline editing in Visual Studio Code

I am using the vscodevim extension, so I'm not sure if this is a common problem. But, I was having the issue where Ctrl + Alt + UpArrow flipped my screen upside down.

Looking at the Visual Studio Code Basics (I don't know if they changed this in a recent update), it says to use:

Ctrl + Alt + Shift + (Up/down)

Using Java with Microsoft Visual Studio 2012

IntegraStudio enables syntax coloring, building, debugging and finding definition and references (F12 and ALT-F12) for Java projects in Visual Studio.

Deleting rows from parent and child tables

If the children have FKs linking them to the parent, then you can use DELETE CASCADE on the parent.

e.g.

CREATE TABLE supplier 
( supplier_id numeric(10) not null, 
 supplier_name varchar2(50) not null, 
 contact_name varchar2(50),  
 CONSTRAINT supplier_pk PRIMARY KEY (supplier_id) 
); 



CREATE TABLE products 
( product_id numeric(10) not null, 
 supplier_id numeric(10) not null, 
 CONSTRAINT fk_supplier 
   FOREIGN KEY (supplier_id) 
  REFERENCES supplier(supplier_id) 
  ON DELETE CASCADE 
); 

Delete the supplier, and it will delate all products for that supplier

Consider marking event handler as 'passive' to make the page more responsive

For those stuck with legacy issues, find the line throwing the error and add {passive: true} - eg:

this.element.addEventListener(t, e, !1)

becomes

this.element.addEventListener(t, e, { passive: true} )

Insert Multiple Rows Into Temp Table With SQL Server 2012

When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:

SQL Fiddle

MS SQL Server 2012 Schema Setup:

Query 1:

CREATE TABLE #Names
  ( 
    Name1 VARCHAR(100),
    Name2 VARCHAR(100)
  ) 

INSERT INTO #Names
  (Name1, Name2)
VALUES
  ('Matt', 'Matthew'),
  ('Matt', 'Marshal'),
  ('Matt', 'Mattison')

SELECT * FROM #NAMES

Results:

| NAME1 |    NAME2 |
--------------------
|  Matt |  Matthew |
|  Matt |  Marshal |
|  Matt | Mattison |

Here a SSMS 2012 screenshot: enter image description here

Declaration of Methods should be Compatible with Parent Methods in PHP

if you wanna keep OOP form without turning any error off, you can also:

class A
{
    public function foo() {
        ;
    }
}
class B extends A
{
    /*instead of : 
    public function foo($a, $b, $c) {*/
    public function foo() {
        list($a, $b, $c) = func_get_args();
        // ...

    }
}

SSIS expression: convert date to string

For SSIS you could go with:

RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" +  (DT_STR, 4, 1252) DATEPART("yy" , GETDATE())

Expression builder screen:

Expression builder screen

For each row return the column name of the largest value

Based on the above suggestions, the following data.table solution worked very fast for me:

library(data.table)

set.seed(45)
DT <- data.table(matrix(sample(10, 10^7, TRUE), ncol=10))

system.time(
  DT[, col_max := colnames(.SD)[max.col(.SD, ties.method = "first")]]
)
#>    user  system elapsed 
#>    0.15    0.06    0.21
DT[]
#>          V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 col_max
#>       1:  7  4  1  2  3  7  6  6  6   1      V1
#>       2:  4  6  9 10  6  2  7  7  1   3      V4
#>       3:  3  4  9  8  9  9  8  8  6   7      V3
#>       4:  4  8  8  9  7  5  9  2  7   1      V4
#>       5:  4  3  9 10  2  7  9  6  6   9      V4
#>      ---                                       
#>  999996:  4  6 10  5  4  7  3  8  2   8      V3
#>  999997:  8  7  6  6  3 10  2  3 10   1      V6
#>  999998:  2  3  2  7  4  7  5  2  7   3      V4
#>  999999:  8 10  3  2  3  4  5  1  1   4      V2
#> 1000000: 10  4  2  6  6  2  8  4  7   4      V1

And also comes with the advantage that can always specify what columns .SD should consider by mentioning them in .SDcols:

DT[, MAX2 := colnames(.SD)[max.col(.SD, ties.method="first")], .SDcols = c("V9", "V10")]

In case we need the column name of the smallest value, as suggested by @lwshang, one just needs to use -.SD:

DT[, col_min := colnames(.SD)[max.col(-.SD, ties.method = "first")]]

How do I delete rows in a data frame?

Here's a quick and dirty function to remove a row by index.

removeRowByIndex <- function(x, row_index) {
  nr <- nrow(x)
  if (nr < row_index) {
    print('row_index exceeds number of rows')
  } else if (row_index == 1)
  {
    return(x[2:nr, ])
  } else if (row_index == nr) {
    return(x[1:(nr - 1), ])
  } else {
    return (x[c(1:(row_index - 1), (row_index + 1):nr), ])
  }
}

It's main flaw is it the row_index argument doesn't follow the R pattern of being a vector of values. There may be other problems as I only spent a couple of minutes writing and testing it, and have only started using R in the last few weeks. Any comments and improvements on this would be very welcome!

Determine if char is a num or letter

You'll want to use the isalpha() and isdigit() standard functions in <ctype.h>.

char c = 'a'; // or whatever

if (isalpha(c)) {
    puts("it's a letter");
} else if (isdigit(c)) {
    puts("it's a digit");
} else {
    puts("something else?");
}

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

In my case running Yosemite in VMWare Workstation 10.0.5 I had to:

1) Set kext to dev mode (might not be needed anymore .... try first without it)

sudo nvram boot-args="kext-dev-mode=1" 

Then reboot (power down VM) for step 2) below.

Details here: http://www.csell.net/2014/09/03/VTNX_Not_Enabled/

2) Add vhv.enable = "TRUE" to my VMX file and restart the VM

Details discussed here: https://communities.vmware.com/thread/416997?start=15&tstart=0

3) Install HAXM 1.1.1 as discussed above from the Intel 's site

(would love to post more links -> but have limit for 2 -> so vote for me so next time you will gert more .. :-))

Best way to determine user's locale within browser

This article suggests the following properties of the browser's navigator object:

  • navigator.language (Netscape - Browser Localization)
  • navigator.browserLanguage (IE-Specific - Browser Localized Language)
  • navigator.systemLanguage (IE-Specific - Windows OS - Localized Language)
  • navigator.userLanguage

Roll these into a javascript function and you should be able to guess the right language, in most circumstances. Be sure to degrade gracefully, so have a div containing your language choice links, so that if there is no javascript or the method doesn't work, the user can still decide. If it does work, just hide the div.

The only problem with doing this on the client side is that either you serve up all the languages to the client, or you have to wait until the script has run and detected the language before requesting the right version. Perhaps serving up the most popular language version as a default would irritate the fewest people.

Edit: I'd second Ivan's cookie suggestion, but make sure the user can always change the language later; not everyone prefers the language their browser defaults to.

How to do sed like text replace with python?

Here's a one-module Python replacement for perl -p:

# Provide compatibility with `perl -p`

# Usage:
#
#     python -mloop_over_stdin_lines '<program>'

# In, `<program>`, use the variable `line` to read and change the current line.

# Example:
#
#         python -mloop_over_stdin_lines 'line = re.sub("pattern", "replacement", line)'

# From the perlrun documentation:
#
#        -p   causes Perl to assume the following loop around your
#             program, which makes it iterate over filename arguments
#             somewhat like sed:
# 
#               LINE:
#                 while (<>) {
#                     ...             # your program goes here
#                 } continue {
#                     print or die "-p destination: $!\n";
#                 }
# 
#             If a file named by an argument cannot be opened for some
#             reason, Perl warns you about it, and moves on to the next
#             file. Note that the lines are printed automatically. An
#             error occurring during printing is treated as fatal. To
#             suppress printing use the -n switch. A -p overrides a -n
#             switch.
# 
#             "BEGIN" and "END" blocks may be used to capture control
#             before or after the implicit loop, just as in awk.
# 

import re
import sys

for line in sys.stdin:
    exec(sys.argv[1], globals(), locals())
    try:
        print line,
    except:
        sys.exit('-p destination: $!\n')

The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

For me using solution provided by codedom did not worked. Here we can only changed compatibility version of exiting database.

But actual problem lies that, internal database version which do not matches due to changes in there storage format.

Check out more details about SQL Server version and their internal db version & Db compatibility level here So it would be good if you create your database using SQL Server 2012 Express version or below. Or start using Visual Studio 2015 Preview.

Android: Difference between Parcelable and Serializable?

you can use the serializable objects in the intents but at the time of making serialize a Parcelable object it can give a serious exception like NotSerializableException. Is it not recommended using serializable with Parcelable . So it is better to extends Parcelable with the object that you want to use with bundle and intents. As this Parcelable is android specific so it doesn't have any side effects. :)

install cx_oracle for python

If you are trying to install in MAC , just unzip the Oracle client which you downloaded and place it into the folder where you written python scripts. it will start working.

There is too much problem of setting up environmental variables. It worked for me.

Hope this helps.

Thanks

How do I use properly CASE..WHEN in MySQL

CASE case_value
    WHEN when_value THEN statements
    [WHEN when_value THEN statements]
    ELSE statements
END 

Or:

CASE
WHEN <search_condition> THEN statements
[WHEN <search_condition> THEN statements] 
ELSE statements
END 

here CASE is an expression in 2nd scenario search_condition will evaluate and if no search_condition is equal then execute else

SELECT
   CASE course_enrollment_settings.base_price
    WHEN course_enrollment_settings.base_price = 0      THEN 1

should be

SELECT
   CASE 
    WHEN course_enrollment_settings.base_price = 0      THEN 1

Changing the color of a clicked table row using jQuery

.highlight { background-color: red; }

If you want multiple selections

$("#data tr").click(function() {
    $(this).toggleClass("highlight");
});

If you want only 1 row in the table to be selected at a time

$("#data tr").click(function() {
    var selected = $(this).hasClass("highlight");
    $("#data tr").removeClass("highlight");
    if(!selected)
            $(this).addClass("highlight");
});

Also note your TABLE tag has 2 ID attributes, you can't do that.

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

I used (the suggested answer from above)

sudo apt-get install eclipse eclipse-cdt g++

but ONLY after then also doing

sudo eclipse -clean

Hope that also helps.

jQuery onclick toggle class name

you can use toggleClass() to toggle class it is really handy.

case:1

<div id='mydiv' class="class1"></div>

$('#mydiv').toggleClass('class1 class2');

output: <div id='mydiv' class="class2"></div>

case:2

<div id='mydiv' class="class2"></div>

$('#mydiv').toggleClass('class1 class2');

output: <div id='mydiv' class="class1"></div>

case:3

<div id='mydiv' class="class1 class2 class3"></div>

$('#mydiv').toggleClass('class1 class2');

output: <div id='mydiv' class="class3"></div>

How can I print using JQuery

Try like

$('.printMe').click(function(){
     window.print();
});

or if you want to print selected area try like

$('.printMe').click(function(){
     $("#outprint").print();
});

Best way to iterate through a Perl array

1 is substantially different from 2 and 3, since it leaves the array in tact, whereas the other two leave it empty.

I'd say #3 is pretty wacky and probably less efficient, so forget that.

Which leaves you with #1 and #2, and they do not do the same thing, so one cannot be "better" than the other. If the array is large and you don't need to keep it, generally scope will deal with it (but see NOTE), so generally, #1 is still the clearest and simplest method. Shifting each element off will not speed anything up. Even if there is a need to free the array from the reference, I'd just go:

undef @Array;

when done.

  • NOTE: The subroutine containing the scope of the array actually keeps the array and re-uses the space next time. Generally, that should be fine (see comments).

What is the difference between bindParam and bindValue?

Here are some I can think about :

  • With bindParam, you can only pass variables ; not values
  • with bindValue, you can pass both (values, obviously, and variables)
  • bindParam works only with variables because it allows parameters to be given as input/output, by "reference" (and a value is not a valid "reference" in PHP) : it is useful with drivers that (quoting the manual) :

support the invocation of stored procedures that return data as output parameters, and some also as input/output parameters that both send in data and are updated to receive it.

With some DB engines, stored procedures can have parameters that can be used for both input (giving a value from PHP to the procedure) and ouput (returning a value from the stored proc to PHP) ; to bind those parameters, you've got to use bindParam, and not bindValue.

Script for rebuilding and reindexing the fragmented index?

Two solutions: One simple and one more advanced.

Introduction

There are two solutions available to you depending on the severity of your issue

Replace with your own values, as follows:

  • Replace XXXMYINDEXXXX with the name of an index.
  • Replace XXXMYTABLEXXX with the name of a table.
  • Replace XXXDATABASENAMEXXX with the name of a database.

Solution 1. Indexing

Rebuild all indexes for a table in offline mode

ALTER INDEX ALL ON XXXMYTABLEXXX REBUILD

Rebuild one specified index for a table in offline mode

ALTER INDEX XXXMYINDEXXXX ON XXXMYTABLEXXX REBUILD

Solution 2. Fragmentation

Fragmentation is an issue in tables that regularly have entries both added and removed.

Check fragmentation percentage

SELECT  
    ips.[index_id] ,
    idx.[name] ,
    ips.[avg_fragmentation_in_percent]
FROM    
    sys.dm_db_index_physical_stats(DB_ID(N'XXXMYDATABASEXXX'), OBJECT_ID(N'XXXMYTABLEXXX'), NULL, NULL, NULL) AS [ips]
    INNER JOIN sys.indexes AS [idx] ON [ips].[object_id] = [idx].[object_id] AND [ips].[index_id] = [idx].[index_id]

Fragmentation 5..30%

If the fragmentation value is greater than 5%, but less than 30% then it is worth reorganising indexes.

Reorganise all indexes for a table

ALTER INDEX ALL ON XXXMYTABLEXXX REORGANIZE

Reorganise one specified index for a table

ALTER INDEX XXXMYINDEXXXX ON XXXMYTABLEXXX REORGANIZE

Fragmentation 30%+

If the fragmentation value is 30% or greater then it is worth rebuilding then indexes in online mode.

Rebuild all indexes in online mode for a table

ALTER INDEX ALL ON XXXMYTABLEXXX REBUILD WITH (ONLINE = ON)

Rebuild one specified index in online mode for a table

ALTER INDEX XXXMYINDEXXXX ON XXXMYTABLEXXX REBUILD WITH (ONLINE = ON)

How do you copy and paste into Git Bash

Aside from using the edit menu commands, you can directly paste into the git bash window using the keyboard shortcut, Insert.

String or binary data would be truncated. The statement has been terminated

When you define varchar etc without a length, the default is 1.

When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified with the CAST function, the default length is 30.

So, if you expect 400 bytes in the @trackingItems1 column from stock, use nvarchar(400).

Otherwise, you are trying to fit >1 character into nvarchar(1) = fail

As a comment, this is bad use of table value function too because it is "multi statement". It can be written like this and it will run better

ALTER FUNCTION [dbo].[testing1](@price int)
RETURNS
AS
   SELECT ta.item, ta.warehouse, ta.price 
   FROM   stock ta
   WHERE  ta.price >= @price;

Of course, you could just use a normal SELECT statement..

Regular expression to limit number of characters to 10

grep '^[0-9]\{1,16\}' | wc -l

Gives the counts with exact match count with limit

What is "Advanced" SQL?

The rest of the job opening listing could provide context to provide a better guess at what "Advanced SQL" may encompass.

I disagree with comments and responses indicating that understanding JOIN and aggregate queries are "advanced" skills; many employers would consider this rather basic, I'm afraid. Here's a rough guess as what "Advanced" can mean.

There's been an "awful" lot of new stuff in the RDBMS domain, in the last few years!

The "Advanced SQL" requirement probably hints at knowledge and possibly proficiency in several of the new concepts such as:

  • CTEs (Common Table Expressions)
  • UDFs (User Defined Functions)
  • Fulltext search extensions/integration
  • performance tuning with new partitionning schemes, filtered indexes, sparse columns...)
  • new data types (ex: GIS/spatial or hierarchical)
  • XML support / integration
  • LINQ
  • and a few more... (BTW the above list is somewhat MSSQL-centric, but similar evolution is observed in most other DBMS platforms).

While keeping abreast of the pro (and cons) of the new features is an important task for any "advanced SQL" practitioner, the old "advanced fundamentals" are probably also considered part of the "advanced":

  • triggers and stored procedures at large
  • Cursors (when to use, how to avoid ...)
  • design expertise: defining tables, what to index, type of indexes
  • performance tuning expertise in general
  • query optimization (reading query plans, knowing what's intrinsically slow etc.)
  • Procedural SQL
  • ...

Note: the above focuses on skills associated with programming/lead role. "Advanced SQL" could also refer to experience with administrative roles (Replication, backups, hardware layout, user management...). Come to think about it, a serious programmer should be somewhat familiar with such practices as well.

Edit: LuckyLindy posted a comment which I found quite insightful. It suggests that "Advanced" may effectively have a different purpose than implying a fair-to-expert level in most of the categories listed above...
I repeat this comment here to give it more visibility.

I think a lot of companies post Advanced SQL because they are tired of getting someone who says "I'm a SQL expert" and has trouble putting together a 3 table outer join. I post similar stuff in job postings and my expectation is simply that a candidate will not need to constantly come to me for help writing SQL. (comment by LuckyLindy)

How do I convert a String to an InputStream in Java?

Like this:

InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8));

Note that this assumes that you want an InputStream that is a stream of bytes that represent your original string encoded as UTF-8.

For versions of Java less than 7, replace StandardCharsets.UTF_8 with "UTF-8".

How to find encoding of a file via script on Linux?

If you're talking about XML-files (ISO-8859-1), the XML-declaration inside them specifies the encoding: <?xml version="1.0" encoding="ISO-8859-1" ?>
So, you can use regular expressions (e.g. with perl) to check every file for such specification.
More information can be found here: How to Determine Text File Encoding.

How to create nested directories using Mkdir in Golang?

An utility method like the following can be used to solve this.

import (
  "os"
  "path/filepath"
  "log"
)

func ensureDir(fileName string) {
  dirName := filepath.Dir(fileName)
  if _, serr := os.Stat(dirName); serr != nil {
    merr := os.MkdirAll(dirName, os.ModePerm)
    if merr != nil {
        panic(merr)
    }
  }
}



func main() {
  _, cerr := os.Create("a/b/c/d.txt")
  if cerr != nil {
    log.Fatal("error creating a/b/c", cerr)
  }
  log.Println("created file in a sub-directory.")
}

Understanding __getitem__ method

__getitem__ can be used to implement "lazy" dict subclasses. The aim is to avoid instantiating a dictionary at once that either already has an inordinately large number of key-value pairs in existing containers, or has an expensive hashing process between existing containers of key-value pairs, or if the dictionary represents a single group of resources that are distributed over the internet.

As a simple example, suppose you have two lists, keys and values, whereby {k:v for k,v in zip(keys, values)} is the dictionary that you need, which must be made lazy for speed or efficiency purposes:

class LazyDict(dict):
    
    def __init__(self, keys, values):
        self.keys = keys
        self.values = values
        super().__init__()
        
    def __getitem__(self, key):
        if key not in self:
            try:
                i = self.keys.index(key)
                self.__setitem__(self.keys.pop(i), self.values.pop(i))
            except ValueError, IndexError:
                raise KeyError("No such key-value pair!!")
        return super().__getitem__(key)

Usage:

>>> a = [1,2,3,4]
>>> b = [1,2,2,3]
>>> c = LazyDict(a,b)
>>> c[1]
1
>>> c[4]
3
>>> c[2]
2
>>> c[3]
2
>>> d = LazyDict(a,b)
>>> d.items()
dict_items([])

How to Find the Default Charset/Encoding in Java?

First, Latin-1 is the same as ISO-8859-1, so, the default was already OK for you. Right?

You successfully set the encoding to ISO-8859-1 with your command line parameter. You also set it programmatically to "Latin-1", but, that's not a recognized value of a file encoding for Java. See http://java.sun.com/javase/6/docs/technotes/guides/intl/encoding.doc.html

When you do that, looks like Charset resets to UTF-8, from looking at the source. That at least explains most of the behavior.

I don't know why OutputStreamWriter shows ISO8859_1. It delegates to closed-source sun.misc.* classes. I'm guessing it isn't quite dealing with encoding via the same mechanism, which is weird.

But of course you should always be specifying what encoding you mean in this code. I'd never rely on the platform default.

Filtering a spark dataframe based on date

Don't use this as suggested in other answers

.filter(f.col("dateColumn") < f.lit('2017-11-01'))

But use this instead

.filter(f.col("dateColumn") < f.unix_timestamp(f.lit('2017-11-01 00:00:00')).cast('timestamp'))

This will use the TimestampType instead of the StringType, which will be more performant in some cases. For example Parquet predicate pushdown will only work with the latter.

Insert using LEFT JOIN and INNER JOIN

you can't use VALUES clause when inserting data using another SELECT query. see INSERT SYNTAX

INSERT INTO user
(
 id, name, username, email, opted_in
)
(
    SELECT id, name, username, email, opted_in
    FROM user
         LEFT JOIN user_permission AS userPerm
            ON user.id = userPerm.user_id
);

How to store decimal values in SQL Server?

DECIMAL(18,0) will allow 0 digits after the decimal point.

Use something like DECIMAL(18,4) instead that should do just fine!

That gives you a total of 18 digits, 4 of which after the decimal point (and 14 before the decimal point).

react-router scroll to top on every transition

The documentation for React Router v4 contains code samples for scroll restoration. Here is their first code sample, which serves as a site-wide solution for “scroll to the top” when a page is navigated to:

class ScrollToTop extends Component {
  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      window.scrollTo(0, 0)
    }
  }

  render() {
    return this.props.children
  }
}

export default withRouter(ScrollToTop)

Then render it at the top of your app, but below Router:

const App = () => (
  <Router>
    <ScrollToTop>
      <App/>
    </ScrollToTop>
  </Router>
)

// or just render it bare anywhere you want, but just one :)
<ScrollToTop/>

^ copied directly from the documentation

Obviously this works for most cases, but there is more on how to deal with tabbed interfaces and why a generic solution hasn't been implemented.

CASE statement in SQLite query

The syntax is wrong in this clause (and similar ones)

    CASE lkey WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

It's either

    CASE WHEN [condition] THEN [expression] ELSE [expression] END

or

    CASE [expression] WHEN [value] THEN [expression] ELSE [expression] END

So in your case it would read:

    CASE WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

Check out the documentation (The CASE expression):

http://www.sqlite.org/lang_expr.html

Is an HTTPS query string secure?

From a "sniff the network packet" point of view a GET request is safe, as the browser will first establish the secure connection and then send the request containing the GET parameters. But GET url's will be stored in the users browser history / autocomplete, which is not a good place to store e.g. password data in. Of course this only applies if you take the broader "Webservice" definition that might access the service from a browser, if you access it only from your custom application this should not be a problem.

So using post at least for password dialogs should be preferred. Also as pointed out in the link littlegeek posted a GET URL is more likely to be written to your server logs.

How to change max_allowed_packet size

For anyone running MySQL on Amazon RDS service, this change is done via parameter groups. You need to create a new PG or use an existing one (other than the default, which is read-only).

You should search for the max_allowed_packet parameter, change its value, and then hit save.

Back in your MySQL instance, if you created a new PG, you should attach the PG to your instance (you may need a reboot). If you changed a PG that was already attached to your instance, changes will be applied without reboot, to all your instances that have that PG attached.

How to include a font .ttf using CSS?

You can use font face like this:

@font-face {
  font-family:"Name-Of-Font";
  src: url("yourfont.ttf") format("truetype");
}

How to enable NSZombie in Xcode?

Here's a video and explaination how to use Instruments and NSZombie to find and fix memory crashes on iOS: http://www.markj.net/iphone-memory-debug-nszombie/

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Session.Abandon() destroys the session and the Session_OnEnd event is triggered.

Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.

So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.

Use Session.Clear(), if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.

Output of git branch in tree like fashion

It's not quite what you asked for, but

git log --graph --simplify-by-decoration --pretty=format:'%d' --all

does a pretty good job. It shows tags and remote branches as well. This may not be desirable for everyone, but I find it useful. --simplifiy-by-decoration is the big trick here for limiting the refs shown.

I use a similar command to view my log. I've been able to completely replace my gitk usage with it:

git log --graph --oneline --decorate --all

I use it by including these aliases in my ~/.gitconfig file:

[alias]
    l = log --graph --oneline --decorate
    ll = log --graph --oneline --decorate --branches --tags
    lll = log --graph --oneline --decorate --all

Edit: Updated suggested log command/aliases to use simpler option flags.

TypeError: list indices must be integers or slices, not str

First, array_length should be an integer and not a string:

array_length = len(array_dates)

Second, your for loop should be constructed using range:

for i in range(array_length):  # Use `xrange` for python 2.

Third, i will increment automatically, so delete the following line:

i += 1

Note, one could also just zip the two lists given that they have the same length:

import csv

dates = ['2020-01-01', '2020-01-02', '2020-01-03']
urls = ['www.abc.com', 'www.cnn.com', 'www.nbc.com']

csv_file_patch = '/path/to/filename.csv'

with open(csv_file_patch, 'w') as fout:
    csv_file = csv.writer(fout, delimiter=';', lineterminator='\n')
    result_array = zip(dates, urls)
    csv_file.writerows(result_array)

Display PDF within web browser

instead of using iframe and depending on the third party`think about using flexpaper, or pdf.js.

I used PDF.js, it works fine for me. Here is the demo.

How to convert text to binary code in JavaScript?

this seems to be the simplified version

Array.from('abc').map((each)=>each.charCodeAt(0).toString(2)).join(" ")

PowerShell script to return versions of .NET Framework on a machine?

Refer to the page Script for finding which .NET versions are installed on remote workstations.

The script there might be useful to find the .NET version for multiple machines on a network.

How to get htaccess to work on MAMP

If you have MAMP PRO you can set up a host like mysite.local, then add some options from the 'Advanced' panel in the main window. Just switch on the options 'Indexes' and 'MultiViews'. 'Includes' and 'FollowSymLinks' should already be checked.

Permanently hide Navigation Bar in an activity

There is a solution starting with KitKat (4.4.2), called Immersive Mode: https://developer.android.com/training/system-ui/immersive.html

Basically, you should add this code to your onResume() method:

View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                              | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                              | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                              | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                              | View.SYSTEM_UI_FLAG_FULLSCREEN
                              | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

What's the best way to do a backwards loop in C/C#/C++?

In C I like to do this:


int i = myArray.Length;
while (i--) {
  myArray[i] = 42;
}

C# example added by MusiGenesis:

{int i = myArray.Length; while (i-- > 0)
{
    myArray[i] = 42;
}}

image size (drawable-hdpi/ldpi/mdpi/xhdpi)

Tablets supports tvdpi and for that scaling factor is 1.33 times dimensions of medium dpi

    ldpi | mdpi | tvdpi | hdpi | xhdpi | xxhdpi | xxxhdpi
    0.75 | 1    | 1.33  | 1.5  | 2     | 3      | 4

This means that if you generate a 400x400 image for xxxhdpi devices, you should generate the same resource in 300x300 for xxhdpi, 200x200 for xhdpi, 133x133 for tvdpi, 150x150 for hdpi, 100x100 for mdpi, and 75x75 for ldpi devices

How to view the current heap size that an application is using?

Attach with jvisualvm from Sun Java 6 JDK. Startup flags are listed.

Eclipse count lines of code

Another way would by to use another loc utility, like LocMetrics for instance.
It also lists many other loc tools. The integration with Eclipse wouldn't be always there (as it would be with Metrics2, which you can check out because it is a more recent version than Metrics), but at least those tools can reason in term of logical lines (computed by summing the terminal semicolons and terminal curly braces).
You can also check with eclipse-metrics is more adapted to what you expect.

Can I get the name of the currently running function in JavaScript?

This has to go in the category of "world's ugliest hacks", but here you go.

First up, printing the name of the current function (as in the other answers) seems to have limited use to me, since you kind of already know what the function is!

However, finding out the name of the calling function could be pretty useful for a trace function. This is with a regexp, but using indexOf would be about 3x faster:

function getFunctionName() {
    var re = /function (.*?)\(/
    var s = getFunctionName.caller.toString();
    var m = re.exec( s )
    return m[1];
}

function me() {
    console.log( getFunctionName() );
}

me();

How to delete an element from an array in C#

Balabaster's answer is correct if you want to remove all instances of the element. If you want to remove only the first one, you would do something like this:

int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int firstFoundIndex = Array.IndexOf(numbers, numToRemove);
if (numbers >= 0)
{
    numbers = numbers.Take(firstFoundIndex).Concat(numbers.Skip(firstFoundIndex + 1)).ToArray();
}

Storing query results into a variable and modifying it inside a Stored Procedure

Yup, this is possible of course. Here are several examples.

-- one way to do this
DECLARE @Cnt int

SELECT @Cnt = COUNT(SomeColumn)
FROM TableName
GROUP BY SomeColumn

-- another way to do the same thing
DECLARE @StreetName nvarchar(100)
SET @StreetName = (SELECT Street_Name from Streets where Street_ID = 123)

-- Assign values to several variables at once
DECLARE @val1 nvarchar(20)
DECLARE @val2 int
DECLARE @val3 datetime
DECLARE @val4 uniqueidentifier
DECLARE @val5 double

SELECT @val1 = TextColumn,
@val2 = IntColumn,
@val3 = DateColumn,
@val4 = GuidColumn,
@val5 = DoubleColumn
FROM SomeTable

How many characters can a Java String have?

I believe they can be up to 2^31-1 characters, as they are held by an internal array, and arrays are indexed by integers in Java.

Fatal error compiling: invalid target release: 1.8 -> [Help 1]

In my case (IntelliJ), I needed to check if I had the right Runner for maven:

  1. Preferences
  2. Build, Execution, Deployment
  3. Maven -> Runner

Preferences

Encode/Decode URLs in C++

the juicy bits

#include <ctype.h> // isdigit, tolower

from_hex(char ch) {
  return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10;
}

char to_hex(char code) {
  static char hex[] = "0123456789abcdef";
  return hex[code & 15];
}

noting that

char d = from_hex(hex[0]) << 4 | from_hex(hex[1]);

as in

// %7B = '{'

char d = from_hex('7') << 4 | from_hex('B');

Calling async method on button click

use below code

 Task.WaitAll(Task.Run(async () => await GetResponse<MyObject>("my url")));

Connect Android Studio with SVN

Go to File->Settings->Version Control->Subversion enter the path for your SVN executable in the General tab under Subversion configuration directory. Also, you can download a latest SVN client such as VisualSVN and point the path to the executable as mentioned above. That will most likely solve your problem.

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

I had the same issue. I resolved it doing the following:

  1. Add the this line to the dispatcher-servlet file:

    <tx:annotation-driven/>
    

    Check above <beans> section in the same file. These two lines must be present:

    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation= "http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
    
  2. Also make sure you added @Repository and @Transactional where you are using sessionFactory.

    @Repository
    @Transactional
    public class ItemDaoImpl implements ItemDao {
        @Autowired
        private SessionFactory sessionFactory;
    

Phonegap + jQuery Mobile, real world sample or tutorial

This is a nice 5-part tutorial that covers a lot of useful material: http://mobile.tutsplus.com/tutorials/phonegap/phonegap-from-scratch/
(Anyone else noticing a trend forming here??? hehehee )

And this will definitely be of use to all developers:
http://blip.tv/mobiletuts/weinre-demonstration-5922038
=)
Todd

Edit I just finished a nice four part tutorial building an app to write, save, edit, & delete notes using jQuery mobile (only), it was very practical & useful, but it was also only for jQM. So, I looked to see what else they had on DZone.

I'm now going to start sorting through these search results. At a glance, it looks really promising. I remembered this post; so I thought I'd steer people to it. ?

How to call a function within class?

That doesn't work because distToPoint is inside your class, so you need to prefix it with the classname if you want to refer to it, like this: classname.distToPoint(self, p). You shouldn't do it like that, though. A better way to do it is to refer to the method directly through the class instance (which is the first argument of a class method), like so: self.distToPoint(p).

How to get selenium to wait for ajax response?

The code (C#) bellow ensures that the target element is displayed:

        internal static bool ElementIsDisplayed()
        {
          IWebDriver driver = new ChromeDriver();
          driver.Url = "http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp";
          WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
          By locator = By.CssSelector("input[value='csharp']:first-child");
          IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
          {
            return d.FindElement(locator);
          });
          return myDynamicElement.Displayed;
        }

If the page supports jQuery it can be used the jQuery.active function to ensure that the target element is retrieved after all the ajax calls are finished:

 public static bool ElementIsDisplayed()
    {
        IWebDriver driver = new ChromeDriver();
        driver.Url = "http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp";
        WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
        By locator = By.CssSelector("input[value='csharp']:first-child");
        return wait.Until(d => ElementIsDisplayed(d, locator));
    }

    public static bool ElementIsDisplayed(IWebDriver driver, By by)
    {
        try
        {
            if (driver.FindElement(by).Displayed)
            {
                //jQuery is supported.
                if ((bool)((IJavaScriptExecutor)driver).ExecuteScript("return window.$ != undefined"))
                {
                    return (bool)((IJavaScriptExecutor)driver).ExecuteScript("return $.active == 0");
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }
        catch (Exception)
        {
            return false;
        }
    }

Spark Kill Running Application

It may be time consuming to get all the application Ids from YARN and kill them one by one. You can use a Bash for loop to accomplish this repetitive task quickly and more efficiently as shown below:

Kill all applications on YARN which are in ACCEPTED state:

for x in $(yarn application -list -appStates ACCEPTED | awk 'NR > 2 { print $1 }'); do yarn application -kill $x; done

Kill all applications on YARN which are in RUNNING state:

for x in $(yarn application -list -appStates RUNNING | awk 'NR > 2 { print $1 }'); do yarn application -kill $x; done

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

What worked for me, is registering it on the Page while specifying the type as that of the UpdatePanel, like so:

ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel) Guid.NewGuid().ToString(), myScript, true);

How do I change the background color of a plot made with ggplot2

To change the panel's background color, use the following code:

myplot + theme(panel.background = element_rect(fill = 'green', colour = 'red'))

To change the color of the plot (but not the color of the panel), you can do:

myplot + theme(plot.background = element_rect(fill = 'green', colour = 'red'))

See here for more theme details Quick reference sheet for legends, axes and themes.

How do I run a program with a different working directory from current, from Linux shell?

why not keep it simple

cd SOME_PATH && run_some_command && cd -

the last 'cd' command will take you back to the last pwd directory. This should work on all *nix systems.

When & why to use delegates?

Delegates are extremely useful when wanting to declare a block of code that you want to pass around. For example when using a generic retry mechanism.

Pseudo:

function Retry(Delegate func, int numberOfTimes)
    try
    {
       func.Invoke();
    }
    catch { if(numberOfTimes blabla) func.Invoke(); etc. etc. }

Or when you want to do late evaluation of code blocks, like a function where you have some Transform action, and want to have a BeforeTransform and an AfterTransform action that you can evaluate within your Transform function, without having to know whether the BeginTransform is filled, or what it has to transform.

And of course when creating event handlers. You don't want to evaluate the code now, but only when needed, so you register a delegate that can be invoked when the event occurs.

How to delete images from a private docker registry?

This docker image includes a bash script that can be used to remove images from a remote v2 registry : https://hub.docker.com/r/vidarl/remove_image_from_registry/

How to calculate an age based on a birthday?

Stackoverflow uses such function to determine the age of a user.

Calculate age in C#

The given answer is

DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (now < bday.AddYears(age)) age--;

So your helper method would look like

public static string Age(this HtmlHelper helper, DateTime birthday)
{
    DateTime now = DateTime.Today;
    int age = now.Year - birthday.Year;
    if (now < birthday.AddYears(age)) age--;

    return age.ToString();
}

Today, I use a different version of this function to include a date of reference. This allow me to get the age of someone at a future date or in the past. This is used for our reservation system, where the age in the future is needed.

public static int GetAge(DateTime reference, DateTime birthday)
{
    int age = reference.Year - birthday.Year;
    if (reference < birthday.AddYears(age)) age--;

    return age;
}

API pagination best practices

If you've got pagination you also sort the data by some key. Why not let API clients include the key of the last element of the previously returned collection in the URL and add a WHERE clause to your SQL query (or something equivalent, if you're not using SQL) so that it returns only those elements for which the key is greater than this value?

Change background position with jQuery

$('#submenu li').hover(function(){
    $('#carousel').css('backgroundPosition', newValue);
});

Django auto_now and auto_now_add

But I wanted to point out that the opinion expressed in the accepted answer is somewhat outdated. According to more recent discussions (django bugs #7634 and #12785), auto_now and auto_now_add are not going anywhere, and even if you go to the original discussion, you'll find strong arguments against the RY (as in DRY) in custom save methods.

A better solution has been offered (custom field types), but didn't gain enough momentum to make it into django. You can write your own in three lines (it's Jacob Kaplan-Moss' suggestion).

from django.db import models
from django.utils import timezone


class AutoDateTimeField(models.DateTimeField):
    def pre_save(self, model_instance, add):
        return timezone.now()

#usage
created_at = models.DateField(default=timezone.now)
updated_at = models.AutoDateTimeField(default=timezone.now)

How to compare binary files to check if they are the same?

For finding flash memory defects, I had to write this script which shows all 1K blocks which contain differences (not only the first one as cmp -b does)

#!/bin/sh

f1=testinput.dat
f2=testoutput.dat

size=$(stat -c%s $f1)
i=0
while [ $i -lt $size ]; do
  if ! r="`cmp -n 1024 -i $i -b $f1 $f2`"; then
    printf "%8x: %s\n" $i "$r"
  fi
  i=$(expr $i + 1024)
done

Output:

   2d400: testinput.dat testoutput.dat differ: byte 3, line 1 is 200 M-^@ 240 M- 
   2dc00: testinput.dat testoutput.dat differ: byte 8, line 1 is 327 M-W 127 W
   4d000: testinput.dat testoutput.dat differ: byte 37, line 1 is 270 M-8 260 M-0
   4d400: testinput.dat testoutput.dat differ: byte 19, line 1 is  46 &  44 $

Disclaimer: I hacked the script in 5 min. It doesn't support command line arguments nor does it support spaces in file names

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

You can solve your problem with help of Attribute routing

Controller

[Route("api/category/{categoryId}")]
public IEnumerable<Order> GetCategoryId(int categoryId) { ... }

URI in jquery

api/category/1

Route Configuration

using System.Web.Http;

namespace WebApplication
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            // Other Web API configuration not shown.
        }
    }
}

and your default routing is working as default convention-based routing

Controller

public string Get(int id)
    {
        return "object of id id";
    }   

URI in Jquery

/api/records/1 

Route Configuration

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Review article for more information Attribute routing and onvention-based routing here & this

Duplicate Symbols for Architecture arm64

If someone is experimenting this working on Flutter, don't try to pod deintegrate, pod init.

How I solved is running flutter clean, flutter run -d [iOS Device]

Hope can help somebody.

PHP send mail to multiple email addresses

Your

$email_to = "[email protected], [email protected], [email protected]"

Needs to be a comma delimited list of email adrresses.

mail($email_to, $email_subject, $thankyou);

Resize image proportionally with CSS?

Try

transform: scale(0.5, 0.5);
-ms-transform: scale(0.5, 0.5);
-webkit-transform: scale(0.5, 0.5);

Rename Pandas DataFrame Index

For Single Index :

 df.index.rename('new_name')

For Multi Index :

 df.index.rename(['new_name','new_name2'])

WE can also use this in latest pandas :

rename_axis

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

Update using NuGet Package Manager Console in your Visual Studio

Update-Package -reinstall Microsoft.AspNet.Mvc

Checking if a string array contains a value, and if so, getting its position

You could use the Array.IndexOf method:

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos > -1)
{
    // the array contains the string and the pos variable
    // will have its position in the array
}

How do I abort/cancel TPL Tasks?

You can abort a task like a thread if you can cause the task to be created on its own thread and call Abort on its Thread object. By default, a task runs on a thread pool thread or the calling thread - neither of which you typically want to abort.

To ensure the task gets its own thread, create a custom scheduler derived from TaskScheduler. In your implementation of QueueTask, create a new thread and use it to execute the task. Later, you can abort the thread, which will cause the task to complete in a faulted state with a ThreadAbortException.

Use this task scheduler:

class SingleThreadTaskScheduler : TaskScheduler
{
    public Thread TaskThread { get; private set; }

    protected override void QueueTask(Task task)
    {
        TaskThread = new Thread(() => TryExecuteTask(task));
        TaskThread.Start();
    }

    protected override IEnumerable<Task> GetScheduledTasks() => throw new NotSupportedException(); // Unused
    protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => throw new NotSupportedException(); // Unused
}

Start your task like this:

var scheduler = new SingleThreadTaskScheduler();
var task = Task.Factory.StartNew(action, cancellationToken, TaskCreationOptions.LongRunning, scheduler);

Later, you can abort with:

scheduler.TaskThread.Abort();

Note that the caveat about aborting a thread still applies:

The Thread.Abort method should be used with caution. Particularly when you call it to abort a thread other than the current thread, you do not know what code has executed or failed to execute when the ThreadAbortException is thrown, nor can you be certain of the state of your application or any application and user state that it is responsible for preserving. For example, calling Thread.Abort may prevent static constructors from executing or prevent the release of unmanaged resources.

How to create dictionary and add key–value pairs dynamically?

In case if someone needs to create a dictionary object dynamically you can use the following code snippet

_x000D_
_x000D_
   let vars = [{key:"key", value:"value"},{key:"key2", value:"value2"}];
     let dict={}
     vars.map(varItem=>{
              dict[varItem.key]=varItem.value
            })

    console.log(dict)
_x000D_
_x000D_
_x000D_

"Object doesn't support this property or method" error in IE11

We have set compatibility mode for IE11 to resolve an issue: Settings>Compatibility View Settings>Add your site name or Check "Display intranet sites in Compatibility View" if your portal is in the intranet.

IE version 11.0.9600.16521

Worked for us, hope this helps someone.

Which comes first in a 2D array, rows or columns?

In java the rows are done first, because a 2 dimension array is considered two separate arrays. Starts with the first row 1 dimension array.

How do I open a new window using jQuery?

This works:

myWindow = window.open('http://www.yahoo.com','myWindow', "width=200, height=200");

Is it possible to style html5 audio tag?

Missing the most important one IMO the container for the controls ::-webkit-media-controls-enclosure:

&::-webkit-media-controls-enclosure {
    border-radius: 5px;
    background-color: green;
}

Laravel 5 - How to access image uploaded in storage within View?

According to Laravel 5.2 docs, your publicly accessible files should be put in directory

storage/app/public

To make them accessible from the web, you should create a symbolic link from public/storage to storage/app/public.

ln -s /path/to/laravel/storage/app/public /path/to/laravel/public/storage

Now you can create in your view an URL to the files using the asset helper:

echo asset('storage/file.txt');

How can I pass arguments to a batch file?

Let's keep this simple.

Here is the .cmd file.

@echo off
rem this file is named echo_3params.cmd
echo %1
echo %2
echo %3
set v1=%1
set v2=%2
set v3=%3
echo v1 equals %v1%
echo v2 equals %v2%
echo v3 equals %v3%

Here are 3 calls from the command line.

C:\Users\joeco>echo_3params 1abc 2 def  3 ghi
1abc
2
def
v1 equals 1abc
v2 equals 2
v3 equals def

C:\Users\joeco>echo_3params 1abc "2 def"  "3 ghi"
1abc
"2 def"
"3 ghi"
v1 equals 1abc
v2 equals "2 def"
v3 equals "3 ghi"

C:\Users\joeco>echo_3params 1abc '2 def'  "3 ghi"
1abc
'2
def'
v1 equals 1abc
v2 equals '2
v3 equals def'

C:\Users\joeco>

How to do multiple arguments to map function where one remains the same in python?

You can include lambda along with map:

list(map(lambda a: a+2, [1, 2, 3]))

JSON encode MySQL results

<?php
define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','dishant');

$con = mysqli_connect(HOST,USER,PASS,DB);


  if (mysqli_connect_errno())
  {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

 $sql = "select * from demo ";

 $sth = mysqli_query($con,$sql);

$rows = array();

while($r = mysqli_fetch_array($sth,MYSQL_ASSOC)) {

 $row_array['id'] = $r;

    **array_push($rows,$row_array);**
}
echo json_encode($rows);

mysqli_close($con);
?>

aarray_push($rows,$row_array); help to build array otherwise it give last value in the while loop

this work like append method of StringBuilder in java

Difference Between $.getJSON() and $.ajax() in jQuery

.getJson is simply a wrapper around .ajax but it provides a simpler method signature as some of the settings are defaulted e.g dataType to json, type to get etc

N.B .load, .get and .post are also simple wrappers around the .ajax method.

How to get index of an item in java.util.Set

you can extend LinkedHashSet adding your desired getIndex() method. It's 15 minutes to implement and test it. Just go through the set using iterator and counter, check the object for equality. If found, return the counter.

CSS3 gradient background set on body doesn't stretch but instead repeats?

background: #13486d; /* for non-css3 browsers */
background-image: -webkit-gradient(linear, left top, left bottom, from(#9dc3c3),   to(#13486d));  background: -moz-linear-gradient(top,  #9dc3c3,  #13486d);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#9dc3c3', endColorstr='#13486d');
background-repeat:no-repeat;

How to compare timestamp dates with date-only parameter in MySQL?

In case you are using SQL parameters to run the query then this would be helpful

SELECT * FROM table WHERE timestamp between concat(date(?), ' ', '00:00:00') and concat(date(?), ' ', '23:59:59')

Regex doesn't work in String.matches()

You can make your pattern case insensitive by doing:

Pattern p = Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE);

Removing index column in pandas when reading a csv

you can specify which column is an index in your csv file by using index_col parameter of from_csv function if this doesn't solve you problem please provide example of your data

python - if not in list

How about this?

for item in mylist:
    if item in checklist:
        pass
    else:
       # do something
       print item

How To Set Text In An EditText

You can set android:text="your text";

<EditText
    android:id="@+id/editTextName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/intro_name"/>

Multidimensional Array [][] vs [,]

In the first instance you are trying to create what is called a jagged array.

double[][] ServicePoint = new double[10][9].

The above statement would have worked if it was defined like below.

double[][] ServicePoint = new double[10][]

what this means is you are creating an array of size 10 ,that can store 10 differently sized arrays inside it.In simple terms an Array of arrays.see the below image,which signifies a jagged array.

enter image description here

http://msdn.microsoft.com/en-us/library/2s05feca(v=vs.80).aspx

The second one is basically a two dimensional array and the syntax is correct and acceptable.

  double[,] ServicePoint = new double[10,9];//<-ok (2)

And to access or modify a two dimensional array you have to pass both the dimensions,but in your case you are passing just a single dimension,thats why the error

Correct usage would be

ServicePoint[0][2] ,Refers to an item on the first row ,third column.

Pictorial rep of your two dimensional array

enter image description here

How to create an 2D ArrayList in java?

1st of all, when you declare a variable in java, you should declare it using Interfaces even if you specify the implementation when instantiating it

ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();

should be written

List<List<String>> listOfLists = new ArrayList<List<String>>(size); 

Then you will have to instantiate all columns of your 2d array

    for(int i = 0; i < size; i++)  {
        listOfLists.add(new ArrayList<String>());
    }

And you will use it like this :

listOfLists.get(0).add("foobar");

But if you really want to "create a 2D array that each cell is an ArrayList!"

Then you must go the dijkstra way.

How to add ID property to Html.BeginForm() in asp.net mvc?

In System.Web.Mvc.Html ( in System.Web.Mvc.dll ) the begin form is defined like:- Details

BeginForm ( this HtmlHelper htmlHelper, string actionName, string
controllerName, object routeValues, FormMethod method, object htmlAttributes)

Means you should use like this :

Html.BeginForm( string actionName, string controllerName,object routeValues, FormMethod method, object htmlAttributes)

So, it worked in MVC 4

@using (Html.BeginForm(null, null, new { @id = string.Empty }, FormMethod.Post,
    new { @id = "signupform" }))
{
    <input id="TRAINER_LIST" name="TRAINER_LIST" type="hidden" value="">
    <input type="submit" value="Create" id="btnSubmit" />
}

Does Python support short-circuiting?

Yes, Python does support Short-circuit evaluation, minimal evaluation, or McCarthy evaluation for Boolean operators. It is used to reduce the number of evaluations for computing the output of boolean expression. Example -

Base Functions

def a(x):
    print('a')
    return x

def b(x):
    print('b')
    return x 

AND

if(a(True) and b(True)):
    print(1,end='\n\n')

if(a(False) and b(True)):
    print(2,end='\n\n') 

AND-OUTPUT

a
b
1

a 

OR

if(a(True) or b(False)):
    print(3,end='\n\n')

if(a(False) or b(True)):
    print(4,end='\n\n') 

OR-OUTPUT

a
3

a
b
4 

How to configure XAMPP to send mail from localhost?

in addition to all answers please note that in sendmail.ini file:

auth_password=this-is-Not-your-Gmail-password

due to new google security concern, you should follow these steps to make an application password for this purpose:

  1. go to https://accounts.google.com/ in security tab
  2. turn two-step-verification on
  3. go back to the security tab and make an App-password (in select-app drop-down menu you can choose 'other')

pandas get column average/mean

You can also access a column using the dot notation (also called attribute access) and then calculate its mean:

df.your_column_name.mean()

Using Get-childitem to get a list of files modified in the last 3 days

Try this:

(Get-ChildItem -Path c:\pstbak\*.* -Filter *.pst | ? {
  $_.LastWriteTime -gt (Get-Date).AddDays(-3) 
}).Count

Increasing the Command Timeout for SQL command

Add timeout of your SqlCommand. Please note time is in second.

// Setting command timeout to 1 second
scGetruntotals.CommandTimeout = 1;

glm rotate usage in Opengl

You need to multiply your Model matrix. Because that is where model position, scaling and rotation should be (that's why it's called the model matrix).

All you need to do is (see here)

Model = glm::rotate(Model, angle_in_radians, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)

Note that to convert from degrees to radians, use glm::radians(degrees)

That takes the Model matrix and applies rotation on top of all the operations that are already in there. The other functions translate and scale do the same. That way it's possible to combine many transformations in a single matrix.

note: earlier versions accepted angles in degrees. This is deprecated since 0.9.6

Model = glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)

Simplest way to detect keypresses in javascript

There are a few ways to handle that; Vanilla JavaScript can do it quite nicely:

function code(e) {
    e = e || window.event;
    return(e.keyCode || e.which);
}
window.onload = function(){
    document.onkeypress = function(e){
        var key = code(e);
        // do something with key
    };
};

Or a more structured way of handling it:

(function(d){
    var modern = (d.addEventListener), event = function(obj, evt, fn){
        if(modern) {
            obj.addEventListener(evt, fn, false);
        } else {
            obj.attachEvent("on" + evt, fn);
        }
    }, code = function(e){
        e = e || window.event;
        return(e.keyCode || e.which);
    }, init = function(){
        event(d, "keypress", function(e){
            var key = code(e);
            // do stuff with key here
        });
    };
    if(modern) {
        d.addEventListener("DOMContentLoaded", init, false);
    } else {
        d.attachEvent("onreadystatechange", function(){
            if(d.readyState === "complete") {
                init();
            }
        });
    }
})(document);

How do you tell if a checkbox is selected in Selenium for Java?

public boolean getcheckboxvalue(String element)
    {   
        WebElement webElement=driver.findElement(By.xpath(element));
        return webElement.isSelected();
    }