Programs & Examples On #Smslib

SMSLib is a programmer's library for sending and receiving SMS messages via a GSM modem or mobile phone. SMSLib also supports a few bulk SMS operators.

How do I dump an object's fields to the console?

p object

Ruby doc for p.

p(*args) public

For each object, directly writes obj.inspect followed by a newline to the program’s standard output.

Optional args in MATLAB functions

A good way of going about this is not to use nargin, but to check whether the variables have been set using exist('opt', 'var').

Example:

function [a] = train(x, y, opt)
    if (~exist('opt', 'var'))
        opt = true;
    end
end

See this answer for pros of doing it this way: How to check whether an argument is supplied in function call?

How do I use Spring Boot to serve static content located in Dropbox folder?

Based on @Dave Syers answer I add the following class to my Spring Boot project:

@Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter {

 private static final Logger LOG = LoggerFactory.getLogger(StaticResourceConfiguration.class);

 @Value("${static.path}")
 private String staticPath;

 @Override
 public void addResourceHandlers(ResourceHandlerRegistry registry) {

    if(staticPath != null) {
        LOG.info("Serving static content from " + staticPath);
        registry.addResourceHandler("/**").addResourceLocations("file:" + staticPath);
    }
 }

 // see https://stackoverflow.com/questions/27381781/java-spring-boot-how-to-map-my-my-app-root-to-index-html
 @Override
 public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("redirect:/index.html");
 }
}

This allows me to start my spring boot app with the parameter --static.path like

java -jar spring-app-1.0-SNAPSHOT.jar --static.path=/path/to/my/static-files/

This can be very handy for development and testing.

SmtpException: Unable to read data from the transport connection: net_io_connectionclosed

For anyone who stumbles across this post looking for a solution and you've set up SMTP sendgrid via Azure.

The username is not the username you set up when you've created the sendgrid object in azure. To find your username;

  • Click on your sendgrid object in azure and click manage. You will be redirected to the SendGrid site.
  • Confirm your email and then copy down the username displayed there.. it's an automatically generated username.
  • Add the username from SendGrid into your SMTP settings in the web.config file.

Hope this helps!

Target WSGI script cannot be loaded as Python module

For me the issue was that the WSGI script wasn't executable.

sudo chmod a+x django.wsgi

or just

sudo chmod u+x django.wsgi

so long as you have the correct owner

How to split a data frame?

You may also want to cut the data frame into an arbitrary number of smaller dataframes. Here, we cut into two dataframes.

x = data.frame(num = 1:26, let = letters, LET = LETTERS)
set.seed(10)
split(x, sample(rep(1:2, 13)))

gives

$`1`
   num let LET
3    3   c   C
6    6   f   F
10  10   j   J
12  12   l   L
14  14   n   N
15  15   o   O
17  17   q   Q
18  18   r   R
20  20   t   T
21  21   u   U
22  22   v   V
23  23   w   W
26  26   z   Z

$`2`
   num let LET
1    1   a   A
2    2   b   B
4    4   d   D
5    5   e   E
7    7   g   G
8    8   h   H
9    9   i   I
11  11   k   K
13  13   m   M
16  16   p   P
19  19   s   S
24  24   x   X
25  25   y   Y

You can also split a data frame based upon an existing column. For example, to create three data frames based on the cyl column in mtcars:

split(mtcars,mtcars$cyl)

Multiple models in a view

Another way is to use:

@model Tuple<LoginViewModel,RegisterViewModel>

I have explained how to use this method both in the view and controller for another example: Two models in one view in ASP MVC 3

In your case you could implement it using the following code:

In the view:

@using YourProjectNamespace.Models;
@model Tuple<LoginViewModel,RegisterViewModel>

@using (Html.BeginForm("Login1", "Auth", FormMethod.Post))
{
        @Html.TextBoxFor(tuple => tuple.Item2.Name, new {@Name="Name"})
        @Html.TextBoxFor(tuple => tuple.Item2.Email, new {@Name="Email"})
        @Html.PasswordFor(tuple => tuple.Item2.Password, new {@Name="Password"})
}

@using (Html.BeginForm("Login2", "Auth", FormMethod.Post))
{
        @Html.TextBoxFor(tuple => tuple.Item1.Email, new {@Name="Email"})
        @Html.PasswordFor(tuple => tuple.Item1.Password, new {@Name="Password"})
}

Note that I have manually changed the Name attributes for each property when building the form. This needs to be done, otherwise it wouldn't get properly mapped to the method's parameter of type model when values are sent to the associated method for processing. I would suggest using separate methods to process these forms separately, for this example I used Login1 and Login2 methods. Login1 method requires to have a parameter of type RegisterViewModel and Login2 requires a parameter of type LoginViewModel.

if an actionlink is required you can use:

@Html.ActionLink("Edit", "Edit", new { id=Model.Item1.Id })

in the controller's method for the view, a variable of type Tuple needs to be created and then passed to the view.

Example:

public ActionResult Details()
{
    var tuple = new Tuple<LoginViewModel, RegisterViewModel>(new LoginViewModel(),new RegisterViewModel());
    return View(tuple);
}

or you can fill the two instances of LoginViewModel and RegisterViewModel with values and then pass it to the view.

How to add data via $.ajax ( serialize() + extra data ) like this

Personally, I'd append the element to the form instead of hacking the serialized data, e.g.

moredata = 'your custom data here';

// do what you like with the input
$input = $('<input type="text" name="moredata"/>').val(morevalue);

// append to the form
$('#myForm').append($input);

// then..
data: $('#myForm').serialize()

That way, you don't have to worry about ? or &

Basic Authentication Using JavaScript

After Spending quite a bit of time looking into this, i came up with the solution for this; In this solution i am not using the Basic authentication but instead went with the oAuth authentication protocol. But to use Basic authentication you should be able to specify this in the "setHeaderRequest" with minimal changes to the rest of the code example. I hope this will be able to help someone else in the future:

var token_ // variable will store the token
var userName = "clientID"; // app clientID
var passWord = "secretKey"; // app clientSecret
var caspioTokenUrl = "https://xxx123.caspio.com/oauth/token"; // Your application token endpoint  
var request = new XMLHttpRequest(); 

function getToken(url, clientID, clientSecret) {
    var key;           
    request.open("POST", url, true); 
    request.setRequestHeader("Content-type", "application/json");
    request.send("grant_type=client_credentials&client_id="+clientID+"&"+"client_secret="+clientSecret); // specify the credentials to receive the token on request
    request.onreadystatechange = function () {
        if (request.readyState == request.DONE) {
            var response = request.responseText;
            var obj = JSON.parse(response); 
            key = obj.access_token; //store the value of the accesstoken
            token_ = key; // store token in your global variable "token_" or you could simply return the value of the access token from the function
        }
    }
}
// Get the token
getToken(caspioTokenUrl, userName, passWord);

If you are using the Caspio REST API on some request it may be imperative that you to encode the paramaters for certain request to your endpoint; see the Caspio documentation on this issue;

NOTE: encodedParams is NOT used in this example but was used in my solution.

Now that you have the token stored from the token endpoint you should be able to successfully authenticate for subsequent request from the caspio resource endpoint for your application

function CallWebAPI() {
    var request_ = new XMLHttpRequest();        
    var encodedParams = encodeURIComponent(params);
    request_.open("GET", "https://xxx123.caspio.com/rest/v1/tables/", true);
    request_.setRequestHeader("Authorization", "Bearer "+ token_);
    request_.send();
    request_.onreadystatechange = function () {
        if (request_.readyState == 4 && request_.status == 200) {
            var response = request_.responseText;
            var obj = JSON.parse(response); 
            // handle data as needed... 

        }
    }
} 

This solution does only considers how to successfully make the authenticated request using the Caspio API in pure javascript. There are still many flaws i am sure...

ES6 Map in Typescript

EDIT (Jun 5 2019): While the idea that "TypeScript supports Map natively" is still true, since version 2.1 TypeScript supports something called Record.

type MyMapLikeType = Record<string, IPerson>;
const peopleA: MyMapLikeType = {
    "a": { name: "joe" },
    "b": { name: "bart" },
};

Unfortunately the first generic parameter (key type) is still not fully respected: even with a string type, something like peopleA[0] (a number) is still valid.


EDIT (Apr 25 2016): The answer below is old and should not be considered the best answer. TypeScript does support Maps "natively" now, so it simply allows ES6 Maps to be used when the output is ES6. For ES5, it does not provide polyfills; you need to embed them yourself.

For more information, refer to mohamed hegazy's answer below for a more modern answer, or even this reddit comment for a short version.


As of 1.5.0 beta, TypeScript does not yet support Maps. It is not yet part of the roadmap, either.

The current best solution is an object with typed key and value (sometimes called a hashmap). For an object with keys of type string, and values of type number:

var arr : { [key:string]:number; } = {};

Some caveats, however:

  1. keys can only be of type string or number
  2. It actually doesn't matter what you use as the key type, since numbers/strings are still accepted interchangeably (only the value is enforced).

With the above example:

// OK:
arr["name"] = 1; // String key is fine
arr[0] = 0; // Number key is fine too

// Not OK:
arr[{ a: "a" }] = 2; // Invalid key
arr[3] = "name"; // Invalid value

Copy the entire contents of a directory in C#

Copy and replace all files of the folder

        public static void CopyAndReplaceAll(string SourcePath, string DestinationPath, string backupPath)
    {
            foreach (string dirPath in Directory.GetDirectories(SourcePath, "*", SearchOption.AllDirectories))
            {
                Directory.CreateDirectory($"{DestinationPath}{dirPath.Remove(0, SourcePath.Length)}");
                Directory.CreateDirectory($"{backupPath}{dirPath.Remove(0, SourcePath.Length)}");
            }
            foreach (string newPath in Directory.GetFiles(SourcePath, "*.*", SearchOption.AllDirectories))
            {
                if (!File.Exists($"{ DestinationPath}{newPath.Remove(0, SourcePath.Length)}"))
                    File.Copy(newPath, $"{ DestinationPath}{newPath.Remove(0, SourcePath.Length)}");
                else
                    File.Replace(newPath
                        , $"{ DestinationPath}{newPath.Remove(0, SourcePath.Length)}"
                        , $"{ backupPath}{newPath.Remove(0, SourcePath.Length)}", false);
            }
    }

How to extract the decimal part from a floating point number in C?

Try this:

int main() {
  double num = 23.345;
  int intpart = (int)num;
  double decpart = num - intpart;
  printf("Num = %f, intpart = %d, decpart = %f\n", num, intpart, decpart);
}

For me, it produces:

Num = 23.345000, intpart = 23, decpart = 0.345000

Which appears to be what you're asking for.

How to make certain text not selectable with CSS

The CSS below stops users from being able to select text.

-webkit-user-select: none; /* Safari */        
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+/Edge */
user-select: none; /* Standard */

To target IE9 downwards the html attribute unselectable must be used instead:

<p unselectable="on">Test Text</p>

Delete file from internal storage

Have you tried getFilesDir().getAbsolutePath()?

Seems you fixed your problem by initializing the File object with a full path. I believe this would also do the trick.

Copy or rsync command

rsync is not necessarily more efficient, due to the more detailed inventory of files and blocks it performs. The algorithm is fantastic at what it does, but you need to understand your problem to know if it is really going to be the best choice.

On a very large file system (say many thousands or millions of files) where files tend to be added but not updated, "cp -u" will likely be more efficient. cp makes the decision to copy solely on metadata and can simply get to the business of copying.

Note that you might want some buffering, e.g. by using tar rather than straight cp, depending on the size of the files, network performance, other disk activity, etc. I find the following idea very useful:

tar cf - . | tar xCf directory -

Metadata itself may actually become a significant overhead on very large (cluster) file systems, but rsync and cp will share this problem.

rsync seems to frequently be the preferred tool (and in general purpose applications is my usual default choice), but there are probably many people who blindly use rsync without thinking it through.

How do I share a global variable between c files?

In the second .c file use extern keyword with the same variable name.

Create list or arrays in Windows Batch

@echo off

set array=

setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION

set nl=^&echo(

set array=auto blue ^!nl!^
  bycicle green ^!nl!^
  buggy   red

echo convert the String in indexed arrays

set /a index=0

for /F "tokens=1,2,3*" %%a in ( 'echo(!array!' ) do (

 echo(vehicle[!index!]=%%a color[!index!]=%%b 
 set vehicle[!index!]=%%a
 set color[!index!]=%%b
 set /a index=!index!+1   

)

echo use the arrays

echo(%vehicle[1]% %color[1]%
echo oder

set index=1
echo(!vehicle[%index%]! !color[%index%]!

Using Custom Domains With IIS Express

Following Jaro's advice, I was able to get this working under Windows XP and IIS Express (installed via Web Matrix) with a small modification and was not limited to only localhost. It's just a matter of setting the bindings correctly.

  1. Use WebMatrix to create a new site from folder in your web application root.
  2. Close WebMatrix.
  3. Open %USERPROFILE%\My Documents\IISExpress\config\applicationhost.config (Windows XP. Vista and 7 paths will be similar) and edit the site definition in the <sites> config block to be along the lines of the following:

    <site name="DevExample" id="997005936">
        <application path="/" applicationPool="Clr2IntegratedAppPool">
            <virtualDirectory
                path="/"
                physicalPath="C:\path\to\application\root" />
        </application>
        <bindings>
            <binding
                protocol="http"
                bindingInformation="*:80:dev.example.com" />
        </bindings>
        <applicationDefaults applicationPool="Clr2IntegratedAppPool" />
    </site>

If running MVC, then keep the applicationPool set to one of the "Integrated" options.

AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

CORS is Cross Origin Resource Sharing, you get this error if you are trying to access from one domain to another domain.

Try using JSONP. In your case, JSONP should work fine because it only uses the GET method.

Try something like this:

var url = "https://api.getevents.co/event?&lat=41.904196&lng=12.465974";
$http({
    method: 'JSONP',
    url: url
}).
success(function(status) {
    //your code when success
}).
error(function(status) {
    //your code when fails
});

webpack: Module not found: Error: Can't resolve (with relative path)

If you have a typescript file, you have to instruct the webpack to resolve them by using below code in webpack.config.js

module.exports={
   ...
   resolve:{
      extensions:['.ts','.tsx';]
   }
}

Equivalent of shell 'cd' command to change the working directory?

You can change the working directory with:

import os

os.chdir(path)

There are two best practices to follow when using this method:

  1. Catch the exception (WindowsError, OSError) on invalid path. If the exception is thrown, do not perform any recursive operations, especially destructive ones. They will operate on the old path and not the new one.
  2. Return to your old directory when you're done. This can be done in an exception-safe manner by wrapping your chdir call in a context manager, like Brian M. Hunt did in his answer.

Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use os.chdir() to change the CWD of the calling process.

How to clear the cache of nginx?

There is one right method to remove only cache-files, which matches any KEY. For example:

grep -lr 'KEY: yahoo' /var/lib/nginx/cache | xargs rm -rf

This removes all cache-files, which matches to KEY "yahoo/*", if in nginx.conf was set:

proxy_cache_key $host$uri;

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

I had a similar problem but I came to a different solution that may help others. I used Spring Profiles to separate out test and app configuration classes.

  1. Create a TestConfig class with a specific profile and exclude any app configuration from component scan you wish here.

  2. In your test class set the profile to match the TestConfig and include it using the @ContextConfiguration annotation.

For example:

configuration:

@Profile("test")
@Configuration
@EnableWebMvc
@ComponentScan(
    basePackages="your.base.package",
    excludeFilters = {
            @Filter(type = ASSIGNABLE_TYPE,
                    value = {
                            ExcludedAppConfig1.class,
                            ExcludedAppConfig2.class
            })
    })
public class TestConfig { ...}

test:

@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class)
@WebAppConfiguration
public class SomeTest{ ... }

How to run a program in Atom Editor?

  1. Click on Packages --> Commmand Palette --> Select Toggle.
  2. Type Install Packages and Themes.
  3. Search for Script and then install it.
  4. Press Command + I to run the code (on Mac)

git am error: "patch does not apply"

I had the same problem. I had used

git format-patch <commit_hash>

to create the patch. My main problem was patch was failing due to some conflicts, but I could not see any merge conflict in the file content. I had used git am --3way <patch_file_path> to apply the patch.

The correct command to apply the patch should be:

git am --3way --ignore-space-change <patch_file_path>

If you execute the above command for patching, it will create a merge conflict if patch apply fails. Then you can fix the conflict in your files, like the same way merge conflicts are resolved for git merge

How to debug "ImagePullBackOff"?

On GKE, if the pod is dead, it's best to check for the events. It will show in more detail what the error is about.

In my case, I had :

Failed to pull image "gcr.io/project/imagename@sha256:c8e91af54fc17faa1c49e2a05def5cbabf8f0a67fc558eb6cbca138061a8400a":
 rpc error: code = Unknown desc = error pulling image configuration: unknown blob

It turned out the image was damaged somehow. After repushing it and deploying with the new hash, it worked again.

How can I rename a field for all documents in MongoDB?

This nodejs code just do that , as @Felix Yan mentioned former way seems to work just fine , i had some issues with other snipets hope this helps.

This will rename column "oldColumnName" to be "newColumnName" of table "documents"

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

// Connection URL
//var url = 'mongodb://localhost:27017/myproject';
var url = 'mongodb://myuser:[email protected]:portNumber/databasename';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  renameDBColumn(db, function() {
    db.close();
  });

});

//
// This function should be used for renaming a field for all documents
//
var renameDBColumn = function(db, callback) {
  // Get the documents collection
  console.log("renaming database column of table documents");
  //use the former way:
  remap = function (x) {
    if (x.oldColumnName){
      db.collection('documents').update({_id:x._id}, {$set:{"newColumnName":x.oldColumnName}, $unset:{"oldColumnName":1}});
    }
  }

  db.collection('documents').find().forEach(remap);
  console.log("db table documents remap successfully!");
}

How to ignore certain files in Git

To ignore:

git update-index --assume-unchanged <path/to/file>

To undo ignore:

git update-index --no-assume-unchanged <path/to/file>

Resolving LNK4098: defaultlib 'MSVCRT' conflicts with

I get this every time I want to create an application in VC++.

Right-click the project, select Properties then under 'Configuration properties | C/C++ | Code Generation', select "Multi-threaded Debug (/MTd)" for Debug configuration.

Note that this does not change the setting for your Release configuration - you'll need to go to the same location and select "Multi-threaded (/MT)" for Release.

Pass Hidden parameters using response.sendRedirect()

Using session, I successfully passed a parameter (name) from servlet #1 to servlet #2, using response.sendRedirect in servlet #1. Servlet #1 code:

protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    String name = request.getParameter("name");
    String password = request.getParameter("password");
    ...
    request.getSession().setAttribute("name", name);
    response.sendRedirect("/todo.do");

In Servlet #2, you don't need to get name back. It's already connected to the session. You could do String name = (String) request.getSession().getAttribute("name"); ---but you don't need this.

If Servlet #2 calls a JSP, you can show name this way on the JSP webpage:

<h1>Welcome ${name}</h1>

What is the difference between SQL and MySQL?

SQL is Structured Query Language

MySQL is a relational database management system. You can submit SQL queries to the MySQL database to store, retrieve, modify or delete data.

What is dtype('O'), in pandas?

It means "a python object", i.e. not one of the builtin scalar types supported by numpy.

np.array([object()]).dtype
=> dtype('O')

Error Dropping Database (Can't rmdir '.test\', errno: 17)

I ran into this problem, and when I checked out the database directory, there were a number of exp files (the ibd and frm files had been removed). Listing the files to look at their attributes (since the owner already had rw privileges on the files)

lsattr *.exp
-------------e-- foo.exp
-------------e-- bar.exp

Man page says

       The  'e'  attribute  indicates that the file is using extents for mapping the blocks on disk.
       It may not be removed using chattr(1).

You actually can chattr -e these files, but mysql still won't let you drop the database. Removing the files with rm, however, allows the database to be dropped cleanly.

Oracle 11g Express Edition for Windows 64bit?

Some of more advanced Oracle database features such as session trace do not work properly in Oracle 11g XE 32-bit if installed on Windows 64-bit system. I needed session trace on Windows 7 64-bit.

Apart from that it works well for me in multiple production MS Windows 64-bit systems: Windows Server 2008 R2 and Windows Server 2003 R2.

Issue with Task Scheduler launching a task

My task also failed to start.

I solved it by specifying not only the path to the executable, but also the path to the folder of the executable (Tab "Actions" | Edit | TextBox "Start in").

MySQL compare DATE string with string from DATETIME field

SELECT * FROM `calendar` WHERE DATE(startTime) = '2010-04-29';

it helps , you can convert the values as DATE before comparing.

How do you copy a record in a SQL table but swap out the unique id of the new row?

If "key" is your PK field and it's autonumeric.

insert into MyTable (field1, field2, field3, parentkey)
select field1, field2, null, key from MyTable where uniqueId = @Id

it will generate a new record, copying field1 and field2 from the original record

How to use comparison operators like >, =, < on BigDecimal

This thread has plenty of answers stating that the BigDecimal.compareTo(BigDecimal) method is the one to use to compare BigDecimal instances. I just wanted to add for anymore not experienced with using the BigDecimal.compareTo(BigDecimal) method to be careful with how you are creating your BigDecimal instances. So, for example...

  • new BigDecimal(0.8) will create a BigDecimal instance with a value which is not exactly 0.8 and which has a scale of 50+,
  • new BigDecimal("0.8") will create a BigDecimal instance with a value which is exactly 0.8 and which has a scale of 1

... and the two will be deemed to be unequal according to the BigDecimal.compareTo(BigDecimal) method because their values are unequal when the scale is not limited to a few decimal places.

First of all, be careful to create your BigDecimal instances with the BigDecimal(String val) constructor or the BigDecimal.valueOf(double val) method rather than the BigDecimal(double val) constructor. Secondly, note that you can limit the scale of BigDecimal instances prior to comparing them by means of the BigDecimal.setScale(int newScale, RoundingMode roundingMode) method.

How do I check if an object has a specific property in JavaScript?

Do not do this object.hasOwnProperty(key)). It's really bad because these methods may be shadowed by properties on the object in question - consider { hasOwnProperty: false } - or, the object may be a null object (Object.create(null)).

The best way is to do Object.prototype.hasOwnProperty.call(object, key) or:

const has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.
/* Or */
import has from 'has'; // https://www.npmjs.com/package/has
// ...
console.log(has.call(object, key));

Extracting .jar file with command line

jar xf myFile.jar
change myFile to name of your file
this will save the contents in the current folder of .jar file
that should do :)

How to get a list of installed Jenkins plugins with name and version pair

From the Jenkins home page:

  1. Click Manage Jenkins.
  2. Click Manage Plugins.
  3. Click on the Installed tab.

Or

  1. Go to the Jenkins URL directly: {Your Jenkins base URL}/pluginManager/installed

Simple dictionary in C++

A table out of char array:

char map[256] = { 0 };
map['T'] = 'A'; 
map['A'] = 'T';
map['C'] = 'G';
map['G'] = 'C';
/* .... */

How to create a JSON object

You just need another layer in your php array:

$post_data = array(
  'item' => array(
    'item_type_id' => $item_type,
    'string_key' => $string_key,
    'string_value' => $string_value,
    'string_extra' => $string_extra,
    'is_public' => $public,
   'is_public_for_contacts' => $public_contacts
  )
);

echo json_encode($post_data);

Javascript Uncaught Reference error Function is not defined

Change the wrapping from "onload" to "No wrap - in <body>"

The function defined has a different scope.

Python: Binding Socket: "Address already in use"

As Felipe Cruze mentioned, you must set the SO_REUSEADDR before binding. I found a solution on another site - solution on other site, reproduced below

The problem is that the SO_REUSEADDR socket option must be set before the address is bound to the socket. This can be done by subclassing ThreadingTCPServer and overriding the server_bind method as follows:

import SocketServer, socket

class MyThreadingTCPServer(SocketServer.ThreadingTCPServer):
    def server_bind(self):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(self.server_address)

Bootstrap tab activation with JQuery

<div class="tabbable">
<ul class="nav nav-tabs">
    <li class="active"><a href="#aaa" data-toggle="tab">AAA</a></li>
    <li><a href="#bbb" data-toggle="tab">BBB</a></li>
    <li><a href="#ccc" data-toggle="tab">CCC</a></li>
</ul>
<div class="tab-content" id="tabs">
    <div class="tab-pane fade active in" id="aaa">...Content...</div>
    <div class="tab-pane" id="bbb">...Content...</div>
    <div class="tab-pane" id="ccc">...Content...</div>
</div>
</div>   

Add active class to any li element you want to be active after page load. And also adding active class to content div is needed ,fade in classes are useful for a smooth transition.

Shortest way to print current year in a website

<script type="text/javascript">document.write(new Date().getFullYear());</script>

Entity framework left join

Please make your life easier (don't use join into group):

var query = from ug in UserGroups
            from ugp in UserGroupPrices.Where(x => x.UserGroupId == ug.Id).DefaultIfEmpty()
            select new 
            { 
                UserGroupID = ug.UserGroupID,
                UserGroupName = ug.UserGroupName,
                Price = ugp != null ? ugp.Price : 0 //this is to handle nulls as even when Price is non-nullable prop it may come as null from SQL (result of Left Outer Join)
            };

MySQL timestamp select date range

Usually it would be this:

SELECT * 
  FROM yourtable
 WHERE yourtimetimefield>='2010-10-01'
   AND yourtimetimefield< '2010-11-01'

But because you have a unix timestamps, you'll need something like this:

SELECT * 
  FROM yourtable
 WHERE yourtimetimefield>=unix_timestamp('2010-10-01')
   AND yourtimetimefield< unix_timestamp('2010-11-01')

Background image jumps when address bar hides iOS/Android/Mobile Chrome

I created a vanilla javascript solution to using VH units. Using VH pretty much anywhere is effected by address bars minimizing on scroll. To fix the jank that shows when the page redraws, I've got this js here that will grab all your elements using VH units (if you give them the class .vh-fix), and give them inlined pixel heights. Essentially freezing them at the height we want. You could do this on rotation or on viewport size change to stay responsive.

var els = document.querySelectorAll('.vh-fix')
if (!els.length) return

for (var i = 0; i < els.length; i++) {
  var el = els[i]
  if (el.nodeName === 'IMG') {
    el.onload = function() {
      this.style.height = this.clientHeight + 'px'
    }
  } else {
    el.style.height = el.clientHeight + 'px'
  }
}

This has solved all my use cases, hope it helps.

Export/import jobs in Jenkins

For those of us in the Windows world who may or may not have Bash available, here's my PowerShell port of Katu and Larry Cai's approach. Hope it helps someone.

##### Config vars #####
$serverUri = 'http://localhost:8080/' # URI of your Jenkins server
$jenkinsCli = 'C:\Program Files (x86)\Jenkins\war\WEB-INF\jenkins-cli.jar' # Path to jenkins-cli.jar on your machine
$destFolder = 'C:\Jenkins Backup\' # Output folder (will be created if it doesn't exist)
$destFile = 'jenkins-jobs.zip' # Output filename (will be overwritten if it exists)
########################

$work = Join-Path ([System.IO.Path]::GetTempPath()) ([System.IO.Path]::GetRandomFileName())
New-Item -ItemType Directory -Force -Path $work | Out-Null # Suppress output noise
echo "Created a temp working folder: $work"

$jobs = (java -jar $jenkinsCli -s $serverUri list-jobs)
echo "Found $($jobs.Length) existing jobs: [$jobs]"

foreach ($j in $jobs)
{
    $outfile = Join-Path $work "$j.xml"
    java -jar $jenkinsCli -s $serverUri get-job $j | Out-File $outfile
}
echo "Saved $($jobs.Length) jobs to temp XML files"

New-Item -ItemType Directory -Force -Path $destFolder | Out-Null # Suppress output noise
echo "Found (or created) $destFolder folder"

$destPath = Join-Path $destFolder $destFile
Get-ChildItem $work -Filter *.xml | 
    Write-Zip -Level 9 -OutputPath $destPath -FlattenPaths |
    Out-Null # Suppress output noise
echo "Copied $($jobs.Length) jobs to $destPath"

Remove-Item $work -Recurse -Force
echo "Removed temp working folder"

How to center a button within a div?

Using flexbox

.Center {
  display: flex;
  align-items: center;
  justify-content: center;
}

And then adding the class to your button.

<button class="Center">Demo</button> 

Convert a space delimited string to list

states_list = states.split(' ')

In regards to your edit:

from random import choice
random_state = choice(states_list)

Swift error : signal SIGABRT how to solve it

A common reason for this type of error is that you might have changed the name of your IBOutlet or IBAction you can simply check this by going to source code.

Click on the main.storyboard and then select open as and then select source code enter image description here

source code will open

and then check whether there is the name of the iboutlet or ibaction that you have changed , if there is then select the part and delete it and then again create iboutlet or ibaction. This should resolve your problem

Add carriage return to a string

string s2 = s1.Replace(",", ",\n");

Tried to Load Angular More Than Once

You must change angular route '/'! It is a problem because '/' base url request. If you change '/' => '/home' or '/hede' angular will good work.

jQuery event handlers always execute in order they were bound - any way around this?

Updated Answer

jQuery changed the location of where events are stored in 1.8. Now you know why it is such a bad idea to mess around with internal APIs :)

The new internal API to access to events for a DOM object is available through the global jQuery object, and not tied to each instance, and it takes a DOM element as the first parameter, and a key ("events" for us) as the second parameter.

jQuery._data(<DOM element>, "events");

So here's the modified code for jQuery 1.8.

// [name] is the name of the event "click", "mouseover", .. 
// same as you'd pass it to bind()
// [fn] is the handler function
$.fn.bindFirst = function(name, fn) {
    // bind as you normally would
    // don't want to miss out on any jQuery magic
    this.on(name, fn);

    // Thanks to a comment by @Martin, adding support for
    // namespaced events too.
    this.each(function() {
        var handlers = $._data(this, 'events')[name.split('.')[0]];
        // take out the handler we just inserted from the end
        var handler = handlers.pop();
        // move it at the beginning
        handlers.splice(0, 0, handler);
    });
};

And here's a playground.


Original Answer

As @Sean has discovered, jQuery exposes all event handlers through an element's data interface. Specifically element.data('events'). Using this you could always write a simple plugin whereby you could insert any event handler at a specific position.

Here's a simple plugin that does just that to insert a handler at the beginning of the list. You can easily extend this to insert an item at any given position. It's just array manipulation. But since I haven't seen jQuery's source and don't want to miss out on any jQuery magic from happening, I normally add the handler using bind first, and then reshuffle the array.

// [name] is the name of the event "click", "mouseover", .. 
// same as you'd pass it to bind()
// [fn] is the handler function
$.fn.bindFirst = function(name, fn) {
    // bind as you normally would
    // don't want to miss out on any jQuery magic
    this.bind(name, fn);

    // Thanks to a comment by @Martin, adding support for
    // namespaced events too.
    var handlers = this.data('events')[name.split('.')[0]];
    // take out the handler we just inserted from the end
    var handler = handlers.pop();
    // move it at the beginning
    handlers.splice(0, 0, handler);
};

So for example, for this markup it would work as (example here):

<div id="me">..</div>

$("#me").click(function() { alert("1"); });
$("#me").click(function() { alert("2"); });    
$("#me").bindFirst('click', function() { alert("3"); });

$("#me").click(); // alerts - 3, then 1, then 2

However, since .data('events') is not part of their public API as far as I know, an update to jQuery could break your code if the underlying representation of attached events changes from an array to something else, for example.

Disclaimer: Since anything is possible :), here's your solution, but I would still err on the side of refactoring your existing code, as just trying to remember the order in which these items were attached can soon get out of hand as you keep adding more and more of these ordered events.

Facebook Oauth Logout

For Python developers that want to log user out straight from the backend

At the moment I'm writing this, the trick with m.facebook.com no longer works (at least for me) and user is redirected to the mobile FB login page which obviously is not good for UX.

Fortunately, FB PHP SDK has a semi-documented solution (in case the link doesn't lead to getLogoutUrl() function, just search look for it on that page). This is also mentioned in at least one other on StackOverflow: Facebook php SDK getLogoutUrl() problem.

BTW I've just noticed that Zach Greenberg got it right in this question, but I'm adding my answer as a summary for Python developers.

How to convert a string to character array in c (or) how to extract a single char form string?

In this simple way

char str [10] = "IAmCute";
printf ("%c",str[4]);

Render Content Dynamically from an array map function in React Native

lapsList() {

    return this.state.laps.map((data) => {
      return (
        <View><Text>{data.time}</Text></View>
      )
    })
}

You forgot to return the map. this code will resolve the issue.

R dplyr: Drop multiple columns

We can try

iris %>% 
      select_(.dots= setdiff(names(.),drop.cols))

Convert date to another timezone in JavaScript

Okay, found it!

I'm using timezone-js. this is the code:

var dt = new timezoneJS.Date("2012/04/10 10:10:30 +0000", 'Europe/London');
dt.setTimezone("Asia/Jakarta");

console.debug(dt); //return formatted date-time in asia/jakarta

Can a class member function template be virtual?

At least with gcc 5.4 virtual functions could be template members but has to be templates themselves.

#include <iostream>
#include <string>
class first {
protected:
    virtual std::string  a1() { return "a1"; }
    virtual std::string  mixt() { return a1(); }
};

class last {
protected:
    virtual std::string a2() { return "a2"; }
};

template<class T>  class mix: first , T {
    public:
    virtual std::string mixt() override;
};

template<class T> std::string mix<T>::mixt() {
   return a1()+" before "+T::a2();
}

class mix2: public mix<last>  {
    virtual std::string a1() override { return "mix"; }
};

int main() {
    std::cout << mix2().mixt();
    return 0;
}

Outputs

mix before a2
Process finished with exit code 0

Search a string in a file and delete it from this file by Shell Script

Try the vim-way:

ex -s +"g/foo/d" -cwq file.txt

PHP cURL HTTP CODE return 0

Try this:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

Correctly ignore all files recursively under a specific folder except for a specific file type

The best answer is to add a Resources/.gitignore file under Resources containing:

# Ignore any file in this directory except for this file and *.foo files
*
!/.gitignore
!*.foo

If you are unwilling or unable to add that .gitignore file, there is an inelegant solution:

# Ignore any file but *.foo under Resources. Update this if we add deeper directories
Resources/*
!Resources/*/
!Resources/*.foo
Resources/*/*
!Resources/*/*/
!Resources/*/*.foo
Resources/*/*/*
!Resources/*/*/*/
!Resources/*/*/*.foo
Resources/*/*/*/*
!Resources/*/*/*/*/
!Resources/*/*/*/*.foo

You will need to edit that pattern if you add directories deeper than specified.

Generating random numbers with normal distribution in Excel

As @osknows said in a comment above (rather than an answer which is why I am adding this), the Analysis Pack includes Random Number Generation functions (e.g. NORM.DIST, NORM.INV) to generate a set of numbers. A good summary link is at http://www.bettersolutions.com/excel/EUN147/YI231420881.htm.

how to customize `show processlist` in mysql?

...We don't have a newer version of MySQL yet, so I was able to do this (works only on UNIX):

 host=maindb

 echo "show full processlist\G" | mysql -h$host | grep -B 6 -A 1 Locked

The above will query for all locked sessions, and return the information and SQL that is involved.

...So- assuming you wanted to query for sessions that were sleeping:

  host=maindb

  echo "show full processlist\G" | mysql -h$host | grep -B 6 -A 1 Sleep

Or, assuming you needed to provide additional connection parameters for MySQL:

  host=maindb

  user=me

  password=mycoolpassword 

  echo "show full processlist\G" | mysql -h$host -u$user -p$password | grep -B 6 -A 1 Locked

With a couple of tweaks, I'm sure a shell script could be easily created to query the processlist the way you want it.

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

How do I show the schema of a table in a MySQL database?

SHOW CREATE TABLE yourTable;

or

SHOW COLUMNS FROM yourTable;

React Error: Target Container is not a DOM Element

Also you can do something like that:

document.addEventListener("DOMContentLoaded", function(event) {
  React.renderComponent(
    CardBox({url: "/cards/?format=json", pollInterval: 2000}),
    document.getElementById("content")
  );
})

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

PHP: convert spaces in string into %20?

Use the rawurlencode function instead.

Server returned HTTP response code: 401 for URL: https

Try This. You need pass the authentication to let the server know its a valid user. You need to import these two packages and has to include a jersy jar. If you dont want to include jersy jar then import this package

import sun.misc.BASE64Encoder;

import com.sun.jersey.core.util.Base64;
import sun.net.www.protocol.http.HttpURLConnection;

and then,

String encodedAuthorizedUser = getAuthantication("username", "password");
URL url = new URL("Your Valid Jira URL");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty ("Authorization", "Basic " + encodedAuthorizedUser );

 public String getAuthantication(String username, String password) {
   String auth = new String(Base64.encode(username + ":" + password));
   return auth;
 }

How to convert a 3D point into 2D perspective projection?

I see this question is a bit old, but I decided to give an answer anyway for those who find this question by searching.
The standard way to represent 2D/3D transformations nowadays is by using homogeneous coordinates. [x,y,w] for 2D, and [x,y,z,w] for 3D. Since you have three axes in 3D as well as translation, that information fits perfectly in a 4x4 transformation matrix. I will use column-major matrix notation in this explanation. All matrices are 4x4 unless noted otherwise.
The stages from 3D points and to a rasterized point, line or polygon looks like this:

  1. Transform your 3D points with the inverse camera matrix, followed with whatever transformations they need. If you have surface normals, transform them as well but with w set to zero, as you don't want to translate normals. The matrix you transform normals with must be isotropic; scaling and shearing makes the normals malformed.
  2. Transform the point with a clip space matrix. This matrix scales x and y with the field-of-view and aspect ratio, scales z by the near and far clipping planes, and plugs the 'old' z into w. After the transformation, you should divide x, y and z by w. This is called the perspective divide.
  3. Now your vertices are in clip space, and you want to perform clipping so you don't render any pixels outside the viewport bounds. Sutherland-Hodgeman clipping is the most widespread clipping algorithm in use.
  4. Transform x and y with respect to w and the half-width and half-height. Your x and y coordinates are now in viewport coordinates. w is discarded, but 1/w and z is usually saved because 1/w is required to do perspective-correct interpolation across the polygon surface, and z is stored in the z-buffer and used for depth testing.

This stage is the actual projection, because z isn't used as a component in the position any more.

The algorithms:

Calculation of field-of-view

This calculates the field-of view. Whether tan takes radians or degrees is irrelevant, but angle must match. Notice that the result reaches infinity as angle nears 180 degrees. This is a singularity, as it is impossible to have a focal point that wide. If you want numerical stability, keep angle less or equal to 179 degrees.

fov = 1.0 / tan(angle/2.0)

Also notice that 1.0 / tan(45) = 1. Someone else here suggested to just divide by z. The result here is clear. You would get a 90 degree FOV and an aspect ratio of 1:1. Using homogeneous coordinates like this has several other advantages as well; we can for example perform clipping against the near and far planes without treating it as a special case.

Calculation of the clip matrix

This is the layout of the clip matrix. aspectRatio is Width/Height. So the FOV for the x component is scaled based on FOV for y. Far and near are coefficients which are the distances for the near and far clipping planes.

[fov * aspectRatio][        0        ][        0              ][        0       ]
[        0        ][       fov       ][        0              ][        0       ]
[        0        ][        0        ][(far+near)/(far-near)  ][        1       ]
[        0        ][        0        ][(2*near*far)/(near-far)][        0       ]

Screen Projection

After clipping, this is the final transformation to get our screen coordinates.

new_x = (x * Width ) / (2.0 * w) + halfWidth;
new_y = (y * Height) / (2.0 * w) + halfHeight;

Trivial example implementation in C++

#include <vector>
#include <cmath>
#include <stdexcept>
#include <algorithm>

struct Vector
{
    Vector() : x(0),y(0),z(0),w(1){}
    Vector(float a, float b, float c) : x(a),y(b),z(c),w(1){}

    /* Assume proper operator overloads here, with vectors and scalars */
    float Length() const
    {
        return std::sqrt(x*x + y*y + z*z);
    }
    
    Vector Unit() const
    {
        const float epsilon = 1e-6;
        float mag = Length();
        if(mag < epsilon){
            std::out_of_range e("");
            throw e;
        }
        return *this / mag;
    }
};

inline float Dot(const Vector& v1, const Vector& v2)
{
    return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
}

class Matrix
{
    public:
    Matrix() : data(16)
    {
        Identity();
    }
    void Identity()
    {
        std::fill(data.begin(), data.end(), float(0));
        data[0] = data[5] = data[10] = data[15] = 1.0f;
    }
    float& operator[](size_t index)
    {
        if(index >= 16){
            std::out_of_range e("");
            throw e;
        }
        return data[index];
    }
    Matrix operator*(const Matrix& m) const
    {
        Matrix dst;
        int col;
        for(int y=0; y<4; ++y){
            col = y*4;
            for(int x=0; x<4; ++x){
                for(int i=0; i<4; ++i){
                    dst[x+col] += m[i+col]*data[x+i*4];
                }
            }
        }
        return dst;
    }
    Matrix& operator*=(const Matrix& m)
    {
        *this = (*this) * m;
        return *this;
    }

    /* The interesting stuff */
    void SetupClipMatrix(float fov, float aspectRatio, float near, float far)
    {
        Identity();
        float f = 1.0f / std::tan(fov * 0.5f);
        data[0] = f*aspectRatio;
        data[5] = f;
        data[10] = (far+near) / (far-near);
        data[11] = 1.0f; /* this 'plugs' the old z into w */
        data[14] = (2.0f*near*far) / (near-far);
        data[15] = 0.0f;
    }

    std::vector<float> data;
};

inline Vector operator*(const Vector& v, const Matrix& m)
{
    Vector dst;
    dst.x = v.x*m[0] + v.y*m[4] + v.z*m[8 ] + v.w*m[12];
    dst.y = v.x*m[1] + v.y*m[5] + v.z*m[9 ] + v.w*m[13];
    dst.z = v.x*m[2] + v.y*m[6] + v.z*m[10] + v.w*m[14];
    dst.w = v.x*m[3] + v.y*m[7] + v.z*m[11] + v.w*m[15];
    return dst;
}

typedef std::vector<Vector> VecArr;
VecArr ProjectAndClip(int width, int height, float near, float far, const VecArr& vertex)
{
    float halfWidth = (float)width * 0.5f;
    float halfHeight = (float)height * 0.5f;
    float aspect = (float)width / (float)height;
    Vector v;
    Matrix clipMatrix;
    VecArr dst;
    clipMatrix.SetupClipMatrix(60.0f * (M_PI / 180.0f), aspect, near, far);
    /*  Here, after the perspective divide, you perform Sutherland-Hodgeman clipping 
        by checking if the x, y and z components are inside the range of [-w, w].
        One checks each vector component seperately against each plane. Per-vertex
        data like colours, normals and texture coordinates need to be linearly
        interpolated for clipped edges to reflect the change. If the edge (v0,v1)
        is tested against the positive x plane, and v1 is outside, the interpolant
        becomes: (v1.x - w) / (v1.x - v0.x)
        I skip this stage all together to be brief.
    */
    for(VecArr::iterator i=vertex.begin(); i!=vertex.end(); ++i){
        v = (*i) * clipMatrix;
        v /= v.w; /* Don't get confused here. I assume the divide leaves v.w alone.*/
        dst.push_back(v);
    }

    /* TODO: Clipping here */

    for(VecArr::iterator i=dst.begin(); i!=dst.end(); ++i){
        i->x = (i->x * (float)width) / (2.0f * i->w) + halfWidth;
        i->y = (i->y * (float)height) / (2.0f * i->w) + halfHeight;
    }
    return dst;
}

If you still ponder about this, the OpenGL specification is a really nice reference for the maths involved. The DevMaster forums at http://www.devmaster.net/ have a lot of nice articles related to software rasterizers as well.

How to convert entire dataframe to numeric while preserving decimals?

You might need to do some checking. You cannot safely convert factors directly to numeric. as.character must be applied first. Otherwise, the factors will be converted to their numeric storage values. I would check each column with is.factor then coerce to numeric as necessary.

df1[] <- lapply(df1, function(x) {
    if(is.factor(x)) as.numeric(as.character(x)) else x
})
sapply(df1, class)
#         a         b 
# "numeric" "numeric" 

What is `related_name` used for in Django?

To add to existing answer - related name is a must in case there 2 FKs in the model that point to the same table. For example in case of Bill of material

@with_author 
class BOM(models.Model): 
    name = models.CharField(max_length=200,null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    tomaterial =  models.ForeignKey(Material, related_name = 'tomaterial')
    frommaterial =  models.ForeignKey(Material, related_name = 'frommaterial')
    creation_time = models.DateTimeField(auto_now_add=True, blank=True)
    quantity = models.DecimalField(max_digits=19, decimal_places=10)

So when you will have to access this data you only can use related name

 bom = material.tomaterial.all().order_by('-creation_time')

It is not working otherwise (at least I was not able to skip the usage of related name in case of 2 FK's to the same table.)

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

When we are going to migrate JQuery from 1.x to 2x or 3.x in our old existing application , then we will use .done,.fail instead of success,error as JQuery up gradation is going to be deprecated these methods.For example when we make a call to server web methods then server returns promise objects to the calling methods(Ajax methods) and this promise objects contains .done,.fail..etc methods.Hence we will the same for success and failure response. Below is the example(it is for POST request same way we can construct for request type like GET...)

 $.ajax({
            type: "POST",
            url: url,
            data: '{"name" :"sheo"}',
            contentType: "application/json; charset=utf-8",
            async: false,
            cache: false
            }).done(function (Response) {
                  //do something when get response            })
           .fail(function (Response) {
                    //do something when any error occurs.
                });

List of All Locales and Their Short Codes?

While accepted answer is pretty complete (I used myself in similar question that arised to me), I think it is worth to put the whole supported language codes and variations, as well as encodings, and point user to a file which is present in almost any linux distributions, in case he simply wants a quicker answer and no internet for example.

This is the file /usr/share/i18n/SUPPORTED and its contents:

aa_DJ.UTF-8 UTF-8
aa_DJ ISO-8859-1
aa_ER UTF-8
aa_ER@saaho UTF-8
aa_ET UTF-8
af_ZA.UTF-8 UTF-8
af_ZA ISO-8859-1
am_ET UTF-8
an_ES.UTF-8 UTF-8
an_ES ISO-8859-15
ar_AE.UTF-8 UTF-8
ar_AE ISO-8859-6
ar_BH.UTF-8 UTF-8
ar_BH ISO-8859-6
ar_DZ.UTF-8 UTF-8
ar_DZ ISO-8859-6
ar_EG.UTF-8 UTF-8
ar_EG ISO-8859-6
ar_IN UTF-8
ar_IQ.UTF-8 UTF-8
ar_IQ ISO-8859-6
ar_JO.UTF-8 UTF-8
ar_JO ISO-8859-6
ar_KW.UTF-8 UTF-8
ar_KW ISO-8859-6
ar_LB.UTF-8 UTF-8
ar_LB ISO-8859-6
ar_LY.UTF-8 UTF-8
ar_LY ISO-8859-6
ar_MA.UTF-8 UTF-8
ar_MA ISO-8859-6
ar_OM.UTF-8 UTF-8
ar_OM ISO-8859-6
ar_QA.UTF-8 UTF-8
ar_QA ISO-8859-6
ar_SA.UTF-8 UTF-8
ar_SA ISO-8859-6
ar_SD.UTF-8 UTF-8
ar_SD ISO-8859-6
ar_SY.UTF-8 UTF-8
ar_SY ISO-8859-6
ar_TN.UTF-8 UTF-8
ar_TN ISO-8859-6
ar_YE.UTF-8 UTF-8
ar_YE ISO-8859-6
az_AZ UTF-8
as_IN UTF-8
ast_ES.UTF-8 UTF-8
ast_ES ISO-8859-15
be_BY.UTF-8 UTF-8
be_BY CP1251
be_BY@latin UTF-8
bem_ZM UTF-8
ber_DZ UTF-8
ber_MA UTF-8
bg_BG.UTF-8 UTF-8
bg_BG CP1251
bho_IN UTF-8
bn_BD UTF-8
bn_IN UTF-8
bo_CN UTF-8
bo_IN UTF-8
br_FR.UTF-8 UTF-8
br_FR ISO-8859-1
br_FR@euro ISO-8859-15
brx_IN UTF-8
bs_BA.UTF-8 UTF-8
bs_BA ISO-8859-2
byn_ER UTF-8
ca_AD.UTF-8 UTF-8
ca_AD ISO-8859-15
ca_ES.UTF-8 UTF-8
ca_ES ISO-8859-1
ca_ES@euro ISO-8859-15
ca_FR.UTF-8 UTF-8
ca_FR ISO-8859-15
ca_IT.UTF-8 UTF-8
ca_IT ISO-8859-15
crh_UA UTF-8
cs_CZ.UTF-8 UTF-8
cs_CZ ISO-8859-2
csb_PL UTF-8
cv_RU UTF-8
cy_GB.UTF-8 UTF-8
cy_GB ISO-8859-14
da_DK.UTF-8 UTF-8
da_DK ISO-8859-1
de_AT.UTF-8 UTF-8
de_AT ISO-8859-1
de_AT@euro ISO-8859-15
de_BE.UTF-8 UTF-8
de_BE ISO-8859-1
de_BE@euro ISO-8859-15
de_CH.UTF-8 UTF-8
de_CH ISO-8859-1
de_DE.UTF-8 UTF-8
de_DE ISO-8859-1
de_DE@euro ISO-8859-15
de_LU.UTF-8 UTF-8
de_LU ISO-8859-1
de_LU@euro ISO-8859-15
dv_MV UTF-8
dz_BT UTF-8
el_GR.UTF-8 UTF-8
el_GR ISO-8859-7
el_CY.UTF-8 UTF-8
el_CY ISO-8859-7
en_AG UTF-8
en_AU.UTF-8 UTF-8
en_AU ISO-8859-1
en_BW.UTF-8 UTF-8
en_BW ISO-8859-1
en_CA.UTF-8 UTF-8
en_CA ISO-8859-1
en_DK.UTF-8 UTF-8
en_DK ISO-8859-1
en_GB.UTF-8 UTF-8
en_GB ISO-8859-1
en_HK.UTF-8 UTF-8
en_HK ISO-8859-1
en_IE.UTF-8 UTF-8
en_IE ISO-8859-1
en_IE@euro ISO-8859-15
en_IN UTF-8
en_NG UTF-8
en_NZ.UTF-8 UTF-8
en_NZ ISO-8859-1
en_PH.UTF-8 UTF-8
en_PH ISO-8859-1
en_SG.UTF-8 UTF-8
en_SG ISO-8859-1
en_US.UTF-8 UTF-8
en_US ISO-8859-1
en_ZA.UTF-8 UTF-8
en_ZA ISO-8859-1
en_ZM UTF-8
en_ZW.UTF-8 UTF-8
en_ZW ISO-8859-1
es_AR.UTF-8 UTF-8
es_AR ISO-8859-1
es_BO.UTF-8 UTF-8
es_BO ISO-8859-1
es_CL.UTF-8 UTF-8
es_CL ISO-8859-1
es_CO.UTF-8 UTF-8
es_CO ISO-8859-1
es_CR.UTF-8 UTF-8
es_CR ISO-8859-1
es_CU UTF-8
es_DO.UTF-8 UTF-8
es_DO ISO-8859-1
es_EC.UTF-8 UTF-8
es_EC ISO-8859-1
es_ES.UTF-8 UTF-8
es_ES ISO-8859-1
es_ES@euro ISO-8859-15
es_GT.UTF-8 UTF-8
es_GT ISO-8859-1
es_HN.UTF-8 UTF-8
es_HN ISO-8859-1
es_MX.UTF-8 UTF-8
es_MX ISO-8859-1
es_NI.UTF-8 UTF-8
es_NI ISO-8859-1
es_PA.UTF-8 UTF-8
es_PA ISO-8859-1
es_PE.UTF-8 UTF-8
es_PE ISO-8859-1
es_PR.UTF-8 UTF-8
es_PR ISO-8859-1
es_PY.UTF-8 UTF-8
es_PY ISO-8859-1
es_SV.UTF-8 UTF-8
es_SV ISO-8859-1
es_US.UTF-8 UTF-8
es_US ISO-8859-1
es_UY.UTF-8 UTF-8
es_UY ISO-8859-1
es_VE.UTF-8 UTF-8
es_VE ISO-8859-1
et_EE.UTF-8 UTF-8
et_EE ISO-8859-1
et_EE.ISO-8859-15 ISO-8859-15
eu_ES.UTF-8 UTF-8
eu_ES ISO-8859-1
eu_ES@euro ISO-8859-15
fa_IR UTF-8
ff_SN UTF-8
fi_FI.UTF-8 UTF-8
fi_FI ISO-8859-1
fi_FI@euro ISO-8859-15
fil_PH UTF-8
fo_FO.UTF-8 UTF-8
fo_FO ISO-8859-1
fr_BE.UTF-8 UTF-8
fr_BE ISO-8859-1
fr_BE@euro ISO-8859-15
fr_CA.UTF-8 UTF-8
fr_CA ISO-8859-1
fr_CH.UTF-8 UTF-8
fr_CH ISO-8859-1
fr_FR.UTF-8 UTF-8
fr_FR ISO-8859-1
fr_FR@euro ISO-8859-15
fr_LU.UTF-8 UTF-8
fr_LU ISO-8859-1
fr_LU@euro ISO-8859-15
fur_IT UTF-8
fy_NL UTF-8
fy_DE UTF-8
ga_IE.UTF-8 UTF-8
ga_IE ISO-8859-1
ga_IE@euro ISO-8859-15
gd_GB.UTF-8 UTF-8
gd_GB ISO-8859-15
gez_ER UTF-8
gez_ER@abegede UTF-8
gez_ET UTF-8
gez_ET@abegede UTF-8
gl_ES.UTF-8 UTF-8
gl_ES ISO-8859-1
gl_ES@euro ISO-8859-15
gu_IN UTF-8
gv_GB.UTF-8 UTF-8
gv_GB ISO-8859-1
ha_NG UTF-8
he_IL.UTF-8 UTF-8
he_IL ISO-8859-8
hi_IN UTF-8
hne_IN UTF-8
hr_HR.UTF-8 UTF-8
hr_HR ISO-8859-2
hsb_DE ISO-8859-2
hsb_DE.UTF-8 UTF-8
ht_HT UTF-8
hu_HU.UTF-8 UTF-8
hu_HU ISO-8859-2
hy_AM UTF-8
hy_AM.ARMSCII-8 ARMSCII-8
id_ID.UTF-8 UTF-8
id_ID ISO-8859-1
ig_NG UTF-8
ik_CA UTF-8
is_IS.UTF-8 UTF-8
is_IS ISO-8859-1
it_CH.UTF-8 UTF-8
it_CH ISO-8859-1
it_IT.UTF-8 UTF-8
it_IT ISO-8859-1
it_IT@euro ISO-8859-15
iu_CA UTF-8
iw_IL.UTF-8 UTF-8
iw_IL ISO-8859-8
ja_JP.EUC-JP EUC-JP
ja_JP.UTF-8 UTF-8
ka_GE.UTF-8 UTF-8
ka_GE GEORGIAN-PS
kk_KZ.UTF-8 UTF-8
kk_KZ PT154
kl_GL.UTF-8 UTF-8
kl_GL ISO-8859-1
km_KH UTF-8
kn_IN UTF-8
ko_KR.EUC-KR EUC-KR
ko_KR.UTF-8 UTF-8
kok_IN UTF-8
ks_IN UTF-8
ks_IN@devanagari UTF-8
ku_TR.UTF-8 UTF-8
ku_TR ISO-8859-9
kw_GB.UTF-8 UTF-8
kw_GB ISO-8859-1
ky_KG UTF-8
lb_LU UTF-8
lg_UG.UTF-8 UTF-8
lg_UG ISO-8859-10
li_BE UTF-8
li_NL UTF-8
lij_IT UTF-8
lo_LA UTF-8
lt_LT.UTF-8 UTF-8
lt_LT ISO-8859-13
lv_LV.UTF-8 UTF-8
lv_LV ISO-8859-13
mag_IN UTF-8
mai_IN UTF-8
mg_MG.UTF-8 UTF-8
mg_MG ISO-8859-15
mhr_RU UTF-8
mi_NZ.UTF-8 UTF-8
mi_NZ ISO-8859-13
mk_MK.UTF-8 UTF-8
mk_MK ISO-8859-5
ml_IN UTF-8
mn_MN UTF-8
mr_IN UTF-8
ms_MY.UTF-8 UTF-8
ms_MY ISO-8859-1
mt_MT.UTF-8 UTF-8
mt_MT ISO-8859-3
my_MM UTF-8
nan_TW@latin UTF-8
nb_NO.UTF-8 UTF-8
nb_NO ISO-8859-1
nds_DE UTF-8
nds_NL UTF-8
ne_NP UTF-8
nl_AW UTF-8
nl_BE.UTF-8 UTF-8
nl_BE ISO-8859-1
nl_BE@euro ISO-8859-15
nl_NL.UTF-8 UTF-8
nl_NL ISO-8859-1
nl_NL@euro ISO-8859-15
nn_NO.UTF-8 UTF-8
nn_NO ISO-8859-1
nr_ZA UTF-8
nso_ZA UTF-8
oc_FR.UTF-8 UTF-8
oc_FR ISO-8859-1
om_ET UTF-8
om_KE.UTF-8 UTF-8
om_KE ISO-8859-1
or_IN UTF-8
os_RU UTF-8
pa_IN UTF-8
pa_PK UTF-8
pap_AN UTF-8
pl_PL.UTF-8 UTF-8
pl_PL ISO-8859-2
ps_AF UTF-8
pt_BR.UTF-8 UTF-8
pt_BR ISO-8859-1
pt_PT.UTF-8 UTF-8
pt_PT ISO-8859-1
pt_PT@euro ISO-8859-15
ro_RO.UTF-8 UTF-8
ro_RO ISO-8859-2
ru_RU.KOI8-R KOI8-R
ru_RU.UTF-8 UTF-8
ru_RU ISO-8859-5
ru_UA.UTF-8 UTF-8
ru_UA KOI8-U
rw_RW UTF-8
sa_IN UTF-8
sc_IT UTF-8
sd_IN UTF-8
sd_IN@devanagari UTF-8
se_NO UTF-8
shs_CA UTF-8
si_LK UTF-8
sid_ET UTF-8
sk_SK.UTF-8 UTF-8
sk_SK ISO-8859-2
sl_SI.UTF-8 UTF-8
sl_SI ISO-8859-2
so_DJ.UTF-8 UTF-8
so_DJ ISO-8859-1
so_ET UTF-8
so_KE.UTF-8 UTF-8
so_KE ISO-8859-1
so_SO.UTF-8 UTF-8
so_SO ISO-8859-1
sq_AL.UTF-8 UTF-8
sq_AL ISO-8859-1
sq_MK UTF-8
sr_ME UTF-8
sr_RS UTF-8
sr_RS@latin UTF-8
ss_ZA UTF-8
st_ZA.UTF-8 UTF-8
st_ZA ISO-8859-1
sv_FI.UTF-8 UTF-8
sv_FI ISO-8859-1
sv_FI@euro ISO-8859-15
sv_SE.UTF-8 UTF-8
sv_SE ISO-8859-1
sw_KE UTF-8
sw_TZ UTF-8
ta_IN UTF-8
ta_LK UTF-8
te_IN UTF-8
tg_TJ.UTF-8 UTF-8
tg_TJ KOI8-T
th_TH.UTF-8 UTF-8
th_TH TIS-620
ti_ER UTF-8
ti_ET UTF-8
tig_ER UTF-8
tk_TM UTF-8
tl_PH.UTF-8 UTF-8
tl_PH ISO-8859-1
tn_ZA UTF-8
tr_CY.UTF-8 UTF-8
tr_CY ISO-8859-9
tr_TR.UTF-8 UTF-8
tr_TR ISO-8859-9
ts_ZA UTF-8
tt_RU UTF-8
tt_RU@iqtelif UTF-8
ug_CN UTF-8
uk_UA.UTF-8 UTF-8
uk_UA KOI8-U
unm_US UTF-8
ur_IN UTF-8
ur_PK UTF-8
uz_UZ ISO-8859-1
uz_UZ@cyrillic UTF-8
ve_ZA UTF-8
vi_VN UTF-8
wa_BE ISO-8859-1
wa_BE@euro ISO-8859-15
wa_BE.UTF-8 UTF-8
wae_CH UTF-8
wal_ET UTF-8
wo_SN UTF-8
xh_ZA.UTF-8 UTF-8
xh_ZA ISO-8859-1
yi_US.UTF-8 UTF-8
yi_US CP1255
yo_NG UTF-8
yue_HK UTF-8
zh_CN.GB18030 GB18030
zh_CN.GBK GBK
zh_CN.UTF-8 UTF-8
zh_CN GB2312
zh_HK.UTF-8 UTF-8
zh_HK BIG5-HKSCS
zh_SG.UTF-8 UTF-8
zh_SG.GBK GBK
zh_SG GB2312
zh_TW.EUC-TW EUC-TW
zh_TW.UTF-8 UTF-8
zh_TW BIG5
zu_ZA.UTF-8 UTF-8
zu_ZA ISO-8859-1

SQL: ... WHERE X IN (SELECT Y FROM ...)

If you want to know which is more effective, you should try looking at the estimated query plans, or the actual query plans after execution. It'll tell you the costs of the queries (I find CPU and IO cost to be interesting). I wouldn't be surprised much if there's little to no difference, but you never know. I've seen certain queries use multiple cores on our database server, while a rewritten version of that same query would only use one core (needless to say, the query that used all 4 cores was a good 3 times faster). Never really quite put my finger on why that is, but if you're working with large result sets, such differences can occur without your knowing about it.

Composer: how can I install another dependency without updating old ones?

To install a new package and only that, you have two options:

  1. Using the require command, just run:

    composer require new/package
    

    Composer will guess the best version constraint to use, install the package, and add it to composer.lock.

    You can also specify an explicit version constraint by running:

    composer require new/package ~2.5
    

–OR–

  1. Using the update command, add the new package manually to composer.json, then run:

    composer update new/package
    

If Composer complains, stating "Your requirements could not be resolved to an installable set of packages.", you can resolve this by passing the flag --with-dependencies. This will whitelist all dependencies of the package you are trying to install/update (but none of your other dependencies).

Regarding the question asker's issues with Laravel and mcrypt: check that it's properly enabled in your CLI php.ini. If php -m doesn't list mcrypt then it's missing.

Important: Don't forget to specify new/package when using composer update! Omitting that argument will cause all dependencies, as well as composer.lock, to be updated.

Get all mysql selected rows into an array

you can call mysql_fetch_array() for no_of_row time

Difference between "include" and "require" in php

<?PHP
echo "Firstline";
include('classes/connection.php');
echo "I will run if include but not on Require";
?>

A very simple Practical example with code. The first echo will be displayed. No matter you use include or require because its runs before include or required.

To check the result, In second line of a code intentionally provide the wrong path to the file or make error in file name. Thus the second echo to be displayed or not will be totally dependent on whether you use require or include.

If you use require the second echo will not execute but if you use include not matter what error comes you will see the result of second echo too.

What is the difference between a Relational and Non-Relational Database?

First up let me start by saying why we need a database.

We need a database to help organise information in such a manner that we can retrieve that data stored in a efficient manner.

Examples of relational database management systems(SQL):

1)Oracle Database

2)SQLite

3)PostgreSQL

4)MySQL

5)Microsoft SQL Server

6)IBM DB2

Examples of non relational database management systems(NoSQL)

1)MongoDB

2)Cassandra

3)Redis

4)Couchbase

5)HBase

6)DocumentDB

7)Neo4j

Relational databases have normalized data, as in information is stored in tables in forms of rows and columns, and normally when data is in normalized form, it helps to reduce data redundancy, and the data in tables are normally related to each other, so when we want to retrieve the data, we can query the data by using join statements and retrieve data as per our need.This is suited when we want to have more writes, less reads, and not much data involved, also its really easy relatively to update data in tables than in non relational databases. Horizontal scaling not possible, vertical scaling possible to some extent.CAP(Consistency, Availability, Partition Tolerant), and ACID (Atomicity, Consistency, Isolation, Duration)compliance.

Let me show entering data to a relational database using PostgreSQL as an example.

First create a product table as follows:

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric
);

then insert the data

INSERT INTO products (product_no, name, price) VALUES (1, 'Cheese', 9.99);

Let's look at another different example: enter image description here

Here in a relational database, we can link the student table and subject table using relationships, via foreign key, subject ID, but in a non relational database no need to have two documents, as no relationships, so we store all the subject details and student details in one document say student document, then data is getting duplicated, which makes updating records troublesome.

In non relational databases, there is no fixed schema, data is not normalized. no relationships between data is created, all data mostly put in one document. Well suited when handling lots of data, and can transfer lots of data at once, best where high amounts of reads and less writes, and less updates, bit difficult to query data, as no fixed schema. Horizontal and vertical scaling is possible.CAP (Consistency, Availability, Partition Tolerant)and BASE (Basically Available, soft state, Eventually consistent)compliance.

Let me show an example to enter data to a non relational database using Mongodb

db.users.insertOne({name: ‘Mary’, age: 28 , occupation: ‘writer’ })
db.users.insertOne({name: ‘Ben’ , age: 21})

Hence you can understand that to the database called db, and there is a collections called users, and document called insertOne to which we add data, and there is no fixed schema as our first record has 3 attributes, and second attribute has 2 attributes only, this is no problem in non relational databases, but this cannot be done in relational databases, as relational databases have a fixed schema.

Let's look at another different example

({Studname: ‘Ash’, Subname: ‘Mathematics’, LecturerName: ‘Mr. Oak’})

Hence we can see in non relational database we can enter both student details and subject details into one document, as no relationships defined in non relational databases, but here this way can lead to data duplication, and hence errors in updating can occur therefore.

Hope this explains everything

Add CSS to iFrame

Based on solution You've already found How to apply CSS to iframe?:

var cssLink = document.createElement("link") 
cssLink.href = "file://path/to/style.css"; 
cssLink .rel = "stylesheet"; 
cssLink .type = "text/css"; 
frames['iframe'].document.body.appendChild(cssLink);

or more jqueryish (from Append a stylesheet to an iframe with jQuery):

var $head = $("iframe").contents().find("head");                
$head.append($("<link/>", 
    { rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));

as for security issues: Disabling same-origin policy in Safari

Class file for com.google.android.gms.internal.zzaja not found

Use:

compile 'com.google.firebase:firebase-auth:11.0.4'

This works.

Android marshmallow request permission?

To handle runtime permission google has provided a library project. You can check this from here https://github.com/googlesamples/easypermissions

EasyPermissions is installed by adding the following dependency to your build.gradle file:

dependencies {
compile 'pub.devrel:easypermissions:0.3.0'
}

To begin using EasyPermissions, have your Activity (or Fragment) override the onRequestPermissionsResult method:

public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    // Forward results to EasyPermissions
    EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}

@Override
public void onPermissionsGranted(int requestCode, List<String> list) {
    // Some permissions have been granted
    // ...
}

@Override
public void onPermissionsDenied(int requestCode, List<String> list) {
    // Some permissions have been denied
    // ...
}
}

Here you will get a working example how this library works https://github.com/milon87/EasyPermission

Multiple Cursors in Sublime Text 2 Windows

It's usually just easier to skip the mouse altogether--or it would be if Sublime didn't mess up multiselect when word wrapping. Here's the official documentation on using the keyboard and mouse for multiple selection. Since it's a bit spread out, I'll summarize it:

Where shortcuts are different in Sublime Text 3, I've made a note. For v3, I always test using the latest dev build; if you're using the beta build, your experience may be different.

If you lose your selection when switching tabs or windows (particularly on Linux), try using Ctrl + U to restore it.

Mouse

Windows/Linux

Building blocks:

  • Positive/negative:
    • Add to selection: Ctrl
    • Subtract from selection: Alt In early builds of v3, this didn't work for linear selection.
  • Selection type:
    • Linear selection: Left Click
    • Block selection: Middle Click or Shift + Right Click On Linux, middle click pastes instead by default.

Combine as you see fit. For example:

  • Add to selection: Ctrl + Left Click (and optionally drag)
  • Subtract from selection: Alt + Left Click This didn't work in early builds of v3.
  • Add block selection: Ctrl + Shift + Right Click (and drag)
  • Subtract block selection: Alt + Shift + Right Click (and drag)

Mac OS X

Building blocks:

  • Positive/negative:
    • Add to selection: ?
    • Subtract from selection: ?? (only works with block selection in v3; presumably bug)
  • Selection type:
    • Linear selection: Left Click
    • Block selection: Middle Click or ? + Left Click

Combine as you see fit. For example:

  • Add to selection: ? + Left Click (and optionally drag)
  • Subtract from selection: ?? + Left Click (and drag--this combination doesn't work in Sublime Text 3, but supposedly it works in 2)
  • Add block selection: ?? + Left Click (and drag)
  • Subtract block selection: ??? + Left Click (and drag)

Keyboard

Windows

  • Return to single selection mode: Esc
  • Extend selection upward/downward at all carets: Ctrl + Alt + Up/Down
  • Extend selection leftward/rightward at all carets: Shift + Left/Right
  • Move all carets up/down/left/right, and clear selection: Up/Down/Left/Right
  • Undo the last selection motion: Ctrl + U
  • Add next occurrence of selected text to selection: Ctrl + D
  • Add all occurrences of the selected text to the selection: Alt + F3
  • Rotate between occurrences of selected text (single selection): Ctrl + F3 (reverse: Ctrl + Shift + F3)
  • Turn a single linear selection into a block selection, with a caret at the end of the selected text in each line: Ctrl + Shift + L

Linux

  • Return to single selection mode: Esc
  • Extend selection upward/downward at all carets: Alt + Up/Down Note that you may be able to hold Ctrl as well to get the same shortcuts as Windows, but Linux tends to use Ctrl + Alt combinations for global shortcuts.
  • Extend selection leftward/rightward at all carets: Shift + Left/Right
  • Move all carets up/down/left/right, and clear selection: Up/Down/Left/Right
  • Undo the last selection motion: Ctrl + U
  • Add next occurrence of selected text to selection: Ctrl + D
  • Add all occurrences of the selected text to the selection: Alt + F3
  • Rotate between occurrences of selected text (single selection): Ctrl + F3 (reverse: Ctrl + Shift + F3)
  • Turn a single linear selection into a block selection, with a caret at the end of the selected text in each line: Ctrl + Shift + L

Mac OS X

  • Return to single selection mode: ? (that's the Mac symbol for Escape)
  • Extend selection upward/downward at all carets: ^??, ^?? (See note)
  • Extend selection leftward/rightward at all carets: ??/??
  • Move all carets up/down/left/right and clear selection: ?, ?, ?, ?
  • Undo the last selection motion: ?U
  • Add next occurrence of selected text to selection: ?D
  • Add all occurrences of the selected text to the selection: ^?G
  • Rotate between occurrences of selected text (single selection): ??G (reverse: ???G)
  • Turn a single linear selection into a block selection, with a caret at the end of the selected text in each line: ??L

Notes for Mac users

On Yosemite and El Capitan, ^?? and ^?? are system keyboard shortcuts by default. If you want them to work in Sublime Text, you will need to change them:

  1. Open System Preferences.
  2. Select the Shortcuts tab.
  3. Select Mission Control in the left listbox.
  4. Change the keyboard shortcuts for Mission Control and Application windows (or disable them). I use ^?? and ^??. They defaults are ^? and ^?; adding ^ to those shortcuts triggers the same actions, but slows the animations.

In case you're not familiar with Mac's keyboard symbols:

  • ? is the escape key
  • ^ is the control key
  • ? is the option key
  • ? is the shift key
  • ? is the command key
  • ? et al are the arrow keys, as depicted

Postgresql, update if row with some unique value exists, else insert

If INSERTS are rare, I would avoid doing a NOT EXISTS (...) since it emits a SELECT on all updates. Instead, take a look at wildpeaks answer: https://dba.stackexchange.com/questions/5815/how-can-i-insert-if-key-not-exist-with-postgresql

CREATE OR REPLACE FUNCTION upsert_tableName(arg1 type, arg2 type) RETURNS VOID AS $$ 
    DECLARE 
    BEGIN 
        UPDATE tableName SET col1 = value WHERE colX = arg1 and colY = arg2; 
        IF NOT FOUND THEN 
        INSERT INTO tableName values (value, arg1, arg2); 
        END IF; 
    END; 
    $$ LANGUAGE 'plpgsql'; 

This way Postgres will initially try to do a UPDATE. If no rows was affected, it will fall back to emitting an INSERT.

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

Quote: I would like to know how to display the div in the middle of the screen, whether user has scrolled up/down.

Change

position: absolute;

To

position: fixed;

W3C specifications for position: absolute and for position: fixed.

Selected value for JSP drop down using JSTL

In HTML, the selected option is represented by the presence of the selected attribute on the <option> element like so:

<option ... selected>...</option>

Or if you're HTML/XHTML strict:

<option ... selected="selected">...</option>

Thus, you just have to let JSP/EL print it conditionally. Provided that you've prepared the selected department as follows:

request.setAttribute("selectedDept", selectedDept);

then this should do:

<select name="department">
    <c:forEach var="item" items="${dept}">
        <option value="${item.key}" ${item.key == selectedDept ? 'selected="selected"' : ''}>${item.value}</option>
    </c:forEach>
</select>

See also:

Mounting multiple volumes on a docker container?

You can have Read only or Read and Write only on the volume

docker -v /on/my/host/1:/on/the/container/1:ro \

docker -v /on/my/host/2:/on/the/container/2:rw \

How do I release memory used by a pandas dataframe?

del df will not be deleted if there are any reference to the df at the time of deletion. So you need to to delete all the references to it with del df to release the memory.

So all the instances bound to df should be deleted to trigger garbage collection.

Use objgragh to check which is holding onto the objects.

How to read barcodes with the camera on Android?

There are two parts in building barcode scanning feature, one capturing barcode image using camera and second extracting barcode value from the image.

Barcode image can be captured from your app using camera app and barcode value can be extracted using Firebase Machine Learning Kit barcode scanning API.

Here is an example app https://www.zoftino.com/android-barcode-scanning-example

Get last n lines of a file, similar to tail

An even cleaner python3 compatible version that doesn't insert but appends & reverses:

def tail(f, window=1):
    """
    Returns the last `window` lines of file `f` as a list of bytes.
    """
    if window == 0:
        return b''
    BUFSIZE = 1024
    f.seek(0, 2)
    end = f.tell()
    nlines = window + 1
    data = []
    while nlines > 0 and end > 0:
        i = max(0, end - BUFSIZE)
        nread = min(end, BUFSIZE)

        f.seek(i)
        chunk = f.read(nread)
        data.append(chunk)
        nlines -= chunk.count(b'\n')
        end -= nread
    return b'\n'.join(b''.join(reversed(data)).splitlines()[-window:])

use it like this:

with open(path, 'rb') as f:
    last_lines = tail(f, 3).decode('utf-8')

Does Visual Studio have code coverage for unit tests?

As already mentioned you can use Fine Code Coverage that visualize coverlet output. If you create a xunit test project (dotnet new xunit) you'll find coverlet reference already present in csproj file because Coverlet is the default coverage tool for every .NET Core and >= .NET 5 applications.

Microsoft has an example using ReportGenerator that converts coverage reports generated by coverlet, OpenCover, dotCover, Visual Studio, NCover, Cobertura, JaCoCo, Clover, gcov or lcov into human readable reports in various formats.

Example report:

enter image description here

While the article focuses on C# and xUnit as the test framework, both MSTest and NUnit would also work.

Guide:

https://docs.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows#generate-reports

If you want code coverage in .xml files you can run any of these commands:

dotnet test --collect:"XPlat Code Coverage"

dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

To remove all the documents in all the collections:

db.getCollectionNames().forEach( function(collection_name) { 
    if (collection_name.indexOf("system.") == -1) {
        print ( ["Removing: ", db[collection_name].count({}), " documents from ", collection_name].join('') );
        db[collection_name].remove({}); 
    }
});

Case insensitive string as HashMap key

One approach is to create a custom subclass of the Apache Commons AbstractHashedMap class, overriding the hash and isEqualKeys methods to perform case insensitive hashing and comparison of keys. (Note - I've never tried this myself ...)

This avoids the overhead of creating new objects each time you need to do a map lookup or update. And the common Map operations should O(1) ... just like a regular HashMap.

And if you are prepared to accept the implementation choices they have made, the Apache Commons CaseInsensitiveMap does the work of customizing / specializing AbstractHashedMap for you.


But if O(logN) get and put operations are acceptable, a TreeMap with a case insensitive string comparator is an option; e.g. using String.CASE_INSENSITIVE_ORDER.

And if you don't mind creating a new temporary String object each time you do a put or get, then Vishal's answer is just fine. (Though, I note that you wouldn't be preserving the original case of the keys if you did that ...)

How to copy a file to multiple directories using the gnu cp command

ls -db di*/subdir | xargs -n 1 cp File

-b in case there is a space in directory name otherwise it will be broken as a different item by xargs, had this problem with the echo version

How do I include a Perl module that's in a different directory?

I'm surprised nobody has mentioned it before, but FindBin::libs will always find your libs as it searches in all reasonable places relative to the location of your script.

#!/usr/bin/perl
use FindBin::libs;
use <your lib>;

Calling a function when ng-repeat has finished

I'm very surprised not to see the most simple solution among the answers to this question. What you want to do is add an ngInit directive on your repeated element (the element with the ngRepeat directive) checking for $last (a special variable set in scope by ngRepeat which indicates that the repeated element is the last in the list). If $last is true, we're rendering the last element and we can call the function we want.

ng-init="$last && test()"

The complete code for your HTML markup would be:

<div ng-app="testApp" ng-controller="myC">
    <p ng-repeat="t in ta" ng-init="$last && test()">{{t}}</p>
</div>

You don't need any extra JS code in your app besides the scope function you want to call (in this case, test) since ngInit is provided by Angular.js. Just make sure to have your test function in the scope so that it can be accessed from the template:

$scope.test = function test() {
    console.log("test executed");
}

Comparing strings by their alphabetical order

As others suggested, you can use String.compareTo(String).

But if you are sorting a list of Strings and you need a Comparator, you don't have to implement it, you can use Comparator.naturalOrder() or Comparator.reverseOrder().

Easy way to convert a unicode list to a list containing python strings?

Just simply use this code

EmployeeList = eval(EmployeeList)
EmployeeList = [str(x) for x in EmployeeList]

Question mark and colon in statement. What does it mean?

This is the conditional operator expression.

(condition) ? [true path] : [false path];

For example

 string value = someBooleanExpression ? "Alpha" : "Beta";

So if the boolean expression is true, value will hold "Alpha", otherwise, it holds "Beta".

For a common pitfall that people fall into, see this question in the C# tag wiki.

How To fix white screen on app Start up?

Try the following code:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowIsTranslucent">true</item>
</style>

This code works for me and will work on all Android devices.

How to set min-font-size in CSS

As of mid-December 2019, the CSS4 min/max-function is exactly what you want:
(tread with care, this is very new, older browsers (aka IE & msEdge) don't support it just yet)
(supported as of Chromium 79 & Firefox v75)

https://developer.mozilla.org/en-US/docs/Web/CSS/min
https://developer.mozilla.org/en-US/docs/Web/CSS/max

Example:

blockquote {
    font-size: max(1em, 12px);
}

That way the font-size will be 1em (if 1em > 12px), but at least 12px.

Unfortunatly this awesome CSS3 feature isn't supported by any browsers yet, but I hope this will change soon!

Edit:

This used to be part of CSS3, but was then re-scheduled for CSS4.
As per December 11th 2019, support arrived in Chrome/Chromium 79 (including on Android, and in Android WebView), and as such also in Microsoft Chredge aka Anaheim including Opera 66 and Safari 11.1 (incl. iOS)

How to create a simple checkbox in iOS?

On iOS there is the switch UI component instead of a checkbox, look into the UISwitch class. The property on (boolean) can be used to determine the state of the slider and about the saving of its state: That depends on how you save your other stuff already, its just saving a boolean value.

With CSS, how do I make an image span the full width of the page as a background image?

If you're hoping to use background-image: url(...);, I don't think you can. However, if you want to play with layering, you can do something like this:

<img class="bg" src="..." />

And then some CSS:

.bg
{
  width: 100%;
  z-index: 0;
}

You can now layer content above the stretched image by playing with z-indexes and such. One quick note, the image can't be contained in any other elements for the width: 100%; to apply to the whole page.

Here's a quick demo if you can't rely on background-size: http://jsfiddle.net/bB3Uc/

How can I check the syntax of Python script without executing it?

Pyflakes does what you ask, it just checks the syntax. From the docs:

Pyflakes makes a simple promise: it will never complain about style, and it will try very, very hard to never emit false positives.

Pyflakes is also faster than Pylint or Pychecker. This is largely because Pyflakes only examines the syntax tree of each file individually.

To install and use:

$ pip install pyflakes
$ pyflakes yourPyFile.py

Java ResultSet how to check if there are any results

By using resultSet.next() you can easily get the result, whether resultSet containing any value or not

ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet.next())
 //resultSet contain some values
else
 // empty resultSet

Insert PHP code In WordPress Page and Post

Description:

there are 3 steps to run PHP code inside post or page.

  1. In functions.php file (in your theme) add new function

  2. In functions.php file (in your theme) register new shortcode which call your function:

add_shortcode( 'SHORCODE_NAME', 'FUNCTION_NAME' );
  1. use your new shortcode

Example #1: just display text.

In functions:

function simple_function_1() {
    return "Hello World!";
}

add_shortcode( 'own_shortcode1', 'simple_function_1' );

In post/page:

[own_shortcode1]

Effect:

Hello World!

Example #2: use for loop.

In functions:

function simple_function_2() {
    $output = "";
    
    for ($number = 1; $number < 10; $number++) {    
        // Append numbers to the string
        $output .= "$number<br>";
    } 
    
    return "$output";
}

add_shortcode( 'own_shortcode2', 'simple_function_2' );

In post/page:

[own_shortcode2]

Effect:

1
2
3
4
5
6
7
8
9

Example #3: use shortcode with arguments

In functions:

function simple_function_3($name) {
    return "Hello $name";
}

add_shortcode( 'own_shortcode3', 'simple_function_3' );

In post/page:

[own_shortcode3 name="John"]

Effect:

Hello John

Example #3 - without passing arguments

In post/page:

[own_shortcode3]

Effect:

Hello 

What is an alternative to execfile in Python 3?

If the script you want to load is in the same directory than the one you run, maybe "import" will do the job ?

If you need to dynamically import code the built-in function __ import__ and the module imp are worth looking at.

>>> import sys
>>> sys.path = ['/path/to/script'] + sys.path
>>> __import__('test')
<module 'test' from '/path/to/script/test.pyc'>
>>> __import__('test').run()
'Hello world!'

test.py:

def run():
        return "Hello world!"

If you're using Python 3.1 or later, you should also take a look at importlib.

Fastest way to check if string contains only digits

Probably the fastest way is:

myString.All(c => char.IsDigit(c))

Note: it will return True in case your string is empty which is incorrect (if you not considering empty as valid number/digit )

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

Rotate an image in image source in html

If your rotation angles are fairly uniform, you can use CSS:

<img id="image_canv" src="/image.png" class="rotate90">

CSS:

.rotate90 {
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    transform: rotate(90deg);
}

Otherwise, you can do this by setting a data attribute in your HTML, then using Javascript to add the necessary styling:

<img id="image_canv" src="/image.png" data-rotate="90">

Sample jQuery:

$('img').each(function() {
    var deg = $(this).data('rotate') || 0;
    var rotate = 'rotate(' + deg + 'deg)';
    $(this).css({ 
        '-webkit-transform': rotate,
        '-moz-transform': rotate,
        '-o-transform': rotate,
        '-ms-transform': rotate,
        'transform': rotate 
    });
});

Demo:

http://jsfiddle.net/verashn/6rRnd/5/

HTML: How to make a submit button with text + image in it?

You're really close to the answer yourself

<button type="submit">
<img src="save.gif" alt="Save icon"/>
<br/>
Save
</button>

Or, you can just remove the type-attribute

<button>
<img src="save.gif" alt="Save icon"/>
<br/>
Save
</button>

What does "atomic" mean in programming?

Just found a post Atomic vs. Non-Atomic Operations to be very helpful to me.

"An operation acting on shared memory is atomic if it completes in a single step relative to other threads.

When an atomic store is performed on a shared memory, no other thread can observe the modification half-complete.

When an atomic load is performed on a shared variable, it reads the entire value as it appeared at a single moment in time."

PHP Checking if the current date is before or after a set date

if( strtotime($database_date) > strtotime('now') ) {
...

jquery's append not working with svg element?

When you pass a markup string into $, it's parsed as HTML using the browser's innerHTML property on a <div> (or other suitable container for special cases like <tr>). innerHTML can't parse SVG or other non-HTML content, and even if it could it wouldn't be able to tell that <circle> was supposed to be in the SVG namespace.

innerHTML is not available on SVGElement—it is a property of HTMLElement only. Neither is there currently an innerSVG property or other way(*) to parse content into an SVGElement. For this reason you should use DOM-style methods. jQuery doesn't give you easy access to the namespaced methods needed to create SVG elements. Really jQuery isn't designed for use with SVG at all and many operations may fail.

HTML5 promises to let you use <svg> without an xmlns inside a plain HTML (text/html) document in the future. But this is just a parser hack(**), the SVG content will still be SVGElements in the SVG namespace, and not HTMLElements, so you'll not be able to use innerHTML even though they look like part of an HTML document.

However, for today's browsers you must use XHTML (properly served as application/xhtml+xml; save with the .xhtml file extension for local testing) to get SVG to work at all. (It kind of makes sense to anyway; SVG is a properly XML-based standard.) This means you'd have to escape the < symbols inside your script block (or enclose in a CDATA section), and include the XHTML xmlns declaration. example:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"><head>
</head><body>
    <svg id="s" xmlns="http://www.w3.org/2000/svg"/>
    <script type="text/javascript">
        function makeSVG(tag, attrs) {
            var el= document.createElementNS('http://www.w3.org/2000/svg', tag);
            for (var k in attrs)
                el.setAttribute(k, attrs[k]);
            return el;
        }

        var circle= makeSVG('circle', {cx: 100, cy: 50, r:40, stroke: 'black', 'stroke-width': 2, fill: 'red'});
        document.getElementById('s').appendChild(circle);
        circle.onmousedown= function() {
            alert('hello');
        };
    </script>
</body></html>

*: well, there's DOM Level 3 LS's parseWithContext, but browser support is very poor. Edit to add: however, whilst you can't inject markup into an SVGElement, you could inject a new SVGElement into an HTMLElement using innerHTML, then transfer it to the desired target. It'll likely be a bit slower though:

<script type="text/javascript"><![CDATA[
    function parseSVG(s) {
        var div= document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
        div.innerHTML= '<svg xmlns="http://www.w3.org/2000/svg">'+s+'</svg>';
        var frag= document.createDocumentFragment();
        while (div.firstChild.firstChild)
            frag.appendChild(div.firstChild.firstChild);
        return frag;
    }

    document.getElementById('s').appendChild(parseSVG(
        '<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" onmousedown="alert(\'hello\');"/>'
    ));
]]></script>

**: I hate the way the authors of HTML5 seem to be scared of XML and determined to shoehorn XML-based features into the crufty mess that is HTML. XHTML solved these problems years ago.

HashSet vs. List performance

It depends. If the exact answer really matters, do some profiling and find out. If you're sure you'll never have more than a certain number of elements in the set, go with a List. If the number is unbounded, use a HashSet.

Plot multiple lines (data series) each with unique color in R

I know, its old a post to answer but like I came across searching for the same post, someone else might turn here as well

By adding : colour in ggplot function , I could achieve the lines with different colors related to the group present in the plot.

ggplot(data=Set6, aes(x=Semana, y=Net_Sales_in_pesos, group = Agencia_ID, colour = as.factor(Agencia_ID)))    

and

geom_line() 

Line Graph with Multiple colors

CardView not showing Shadow in Android L

After going through the docs again, I finally found the solution.

Just add card_view:cardUseCompatPadding="true" to your CardView and shadows will appear on Lollipop devices.

What happens is, the content area in a CardView take different sizes on pre-lollipop and lollipop devices. So in lollipop devices the shadow is actually covered by the card so its not visible. By adding this attribute the content area remains the same across all devices and the shadow becomes visible.

My xml code is like :

<android.support.v7.widget.CardView
    android:id="@+id/media_card_view"
    android:layout_width="match_parent"
    android:layout_height="130dp"
    card_view:cardBackgroundColor="@android:color/white"
    card_view:cardElevation="2dp"
    card_view:cardUseCompatPadding="true"
    >
...
</android.support.v7.widget.CardView>

Modify table: How to change 'Allow Nulls' attribute from not null to allow null

For MySQL, MariaDB

ALTER TABLE [table name] MODIFY COLUMN [column name] [data type] NULL

Use MODIFY COLUMN instead of ALTER COLUMN.

Taking screenshot on Emulator from Android Studio

  1. In Android Studio, select View > Tool Windows > Logcat to open Logcat.
  2. Select the device and a process from the drop-down at the top of the window.
  3. Click Screen Capture on the left side of the window.

For more info Check this link

CSS selector - element with a given child

Is it possible to select an element if it contains a specific child element?

Unfortunately not yet.

The CSS2 and CSS3 selector specifications do not allow for any sort of parent selection.


A Note About Specification Changes

This is a disclaimer about the accuracy of this post from this point onward. Parent selectors in CSS have been discussed for many years. As no consensus has been found, changes keep happening. I will attempt to keep this answer up-to-date, however be aware that there may be inaccuracies due to changes in the specifications.


An older "Selectors Level 4 Working Draft" described a feature which was the ability to specify the "subject" of a selector. This feature has been dropped and will not be available for CSS implementations.

The subject was going to be the element in the selector chain that would have styles applied to it.

Example HTML
<p><span>lorem</span> ipsum dolor sit amet</p>
<p>consecteture edipsing elit</p>

This selector would style the span element

p span {
    color: red;
}

This selector would style the p element

!p span {
    color: red;
}

A more recent "Selectors Level 4 Editor’s Draft" includes "The Relational Pseudo-class: :has()"

:has() would allow an author to select an element based on its contents. My understanding is it was chosen to provide compatibility with jQuery's custom :has() pseudo-selector*.

In any event, continuing the example from above, to select the p element that contains a span one could use:

p:has(span) {
    color: red;
}

* This makes me wonder if jQuery had implemented selector subjects whether subjects would have remained in the specification.

What is the maximum length of a Push Notification alert text?

The real limits for the alert text are not documented anywhere. The only thing the documentation says is:

In iOS 8 and later, the maximum size allowed for a notification payload is 2 kilobytes; Apple Push Notification Service refuses any notification that exceeds this limit. (Prior to iOS 8 and in OS X, the maximum payload size is 256 bytes.)

This is what I could find doing some experiments.

  • Alerts: Prior to iOS 7, the alerts display limit was 107 characters. Bigger messages were truncated and you would get a "..." at the end of the displayed message. With iOS 7 the limit seems to be increased to 235 characters. If you go over 8 lines your message will also get truncated.
  • Banners: Banners get truncated around 62 characters or 2 lines.
  • Notification Center: The messages in the notification center get truncated around 110 characters or 4 lines.
  • Lock Screen: Same as a notification center.

Just as a reminder here is a very good note from the official documentation:

If necessary, iOS truncates your message so that it fits well in each notification delivery style; for best results, you shouldn’t truncate your message.

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

How to force file download with PHP

try this:

header('Content-type: audio/mp3'); 
header('Content-disposition: attachment; 
filename=“'.$trackname'”');                             
readfile('folder name /'.$trackname);          
exit();

Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6

Warning message

~/venv/lib/python3.4/site-packages/urllib3/connectionpool.py:857: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning)

In Debian 8 this steps works

  1. In python3 code
import urllib3
urllib3.disable_warnings()
  1. Install two packages on Debian

libssl1.0.0_1.0.2l-1_bpo8+1_amd64.deb

libssl-dev_1.0.2l-1_bpo8+1_amd64.deb

debian mirror

To build dependencies with new library

  1. Create new venv for python project
python3 -m venv .venv
source .venv/bin/activate

Clean Install modules under python project inside virtual environment by

python3 -m pip install -e .

How to get selenium to wait for ajax response?

In my case the issue seemed due to ajax delays but was related to internal iframes inside the main page. In seleminum it is possible to switch to internal frames with:

    driver.switchTo().frame("body");
    driver.switchTo().frame("bodytab");

I use java. After that I was able to locate the element

    driver.findElement(By.id("e_46")).click();

nodejs - first argument must be a string or Buffer - when using response.write with http.request

response.statusCode is a number, e.g. response.statusCode === 200, not '200'. As the error message says, write expects a string or Buffer object, so you must convert it.

res.write(response.statusCode.toString());

You are also correct about your callback comment though. res.end(); should be inside the callback, just below your write calls.

How can I use tabs for indentation in IntelliJ IDEA?

My Intellij version is 13.4.1

Intellij IDEA->Perference->Code Style(Project Setting)

Python: call a function from string name

You can use a dictionary too.

def install():
    print "In install"

methods = {'install': install}

method_name = 'install' # set by the command line options
if method_name in methods:
    methods[method_name]() # + argument list of course
else:
    raise Exception("Method %s not implemented" % method_name)

How can I select from list of values in SQL Server

A technique that has worked for me is to query a table that you know has a large amount of records in it, including just the Row_Number field in your result

Select Top 10000 Row_Number() OVER (Order by fieldintable) As 'recnum' From largetable

will return a result set of 10000 records from 1 to 10000, use this within another query to give you the desired results

redirect to current page in ASP.Net

http://en.wikipedia.org/wiki/Post/Redirect/Get

The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)

Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.

Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.

String concatenation of two pandas columns

I have encountered a specific case from my side with 10^11 rows in my dataframe, and in this case none of the proposed solution is appropriate. I have used categories, and this should work fine in all cases when the number of unique string is not too large. This is easily done in the R software with XxY with factors but I could not find any other way to do it in python (I'm new to python). If anyone knows a place where this is implemented I'd be glad to know.

def Create_Interaction_var(df,Varnames):
    '''
    :df data frame
    :list of 2 column names, say "X" and "Y". 
    The two columns should be strings or categories
    convert strings columns to categories
    Add a column with the "interaction of X and Y" : X x Y, with name 
    "Interaction-X_Y"
    '''
    df.loc[:, Varnames[0]] = df.loc[:, Varnames[0]].astype("category")
    df.loc[:, Varnames[1]] = df.loc[:, Varnames[1]].astype("category")
    CatVar = "Interaction-" + "-".join(Varnames)
    Var0Levels = pd.DataFrame(enumerate(df.loc[:,Varnames[0]].cat.categories)).rename(columns={0 : "code0",1 : "name0"})
    Var1Levels = pd.DataFrame(enumerate(df.loc[:,Varnames[1]].cat.categories)).rename(columns={0 : "code1",1 : "name1"})
    NbLevels=len(Var0Levels)

    names = pd.DataFrame(list(itertools.product(dict(enumerate(df.loc[:,Varnames[0]].cat.categories)),
                                                dict(enumerate(df.loc[:,Varnames[1]].cat.categories)))),
                         columns=['code0', 'code1']).merge(Var0Levels,on="code0").merge(Var1Levels,on="code1")
    names=names.assign(Interaction=[str(x) + '_' + y for x, y in zip(names["name0"], names["name1"])])
    names["code01"]=names["code0"] + NbLevels*names["code1"]
    df.loc[:,CatVar]=df.loc[:,Varnames[0]].cat.codes+NbLevels*df.loc[:,Varnames[1]].cat.codes
    df.loc[:, CatVar]=  df[[CatVar]].replace(names.set_index("code01")[["Interaction"]].to_dict()['Interaction'])[CatVar]
    df.loc[:, CatVar] = df.loc[:, CatVar].astype("category")
    return df

Adding items to end of linked list

public static Node insertNodeAtTail(Node head,Object data) {
               Node node = new Node(data);
                 node.next = null;
                if (head == null){
                    return node;
                }
                else{
                    Node temp = head;
                    while(temp.next != null){
                        temp = temp.next;
                    }
                    temp.next = node; 
                    return head;
                }        
    }

Compiling Java 7 code via Maven

Please check you pom.xml for the below tags

<properties>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
</properties>

it should point the required jdk version

How can I export the schema of a database in PostgreSQL?

If you only want the create tables, then you can do pg_dump -s databasename | awk 'RS="";/CREATE TABLE[^;]*;/'

How can I remove or replace SVG content?

I am using the SVG using D3.js and i had the same issue.

I used this code for removing the previous svg but the linear gradient inside SVG were not coming in IE

$("#container_div_id").html("");

then I wrote the below code to resolve the issue

$('container_div_id g').remove();
$('#container_div_id path').remove();

here i am removing the previous g and path inside the SVG, replacing with the new one.

Keeping my linear gradient inside SVG tags in the static content and then I called the above code, This works in IE

Scrolling an iframe with JavaScript?

Based on Chris's comment

CSS
.amazon-rating {
  width: 55px;
  height: 12px;
  overflow: hidden;
}

.rating-stars {
  left: -18px;
  top: -102px;
  position: relative;
}
HAML
.amazon-rating
  %iframe.rating-stars{src: $item->ratingURL, seamless: 'seamless', frameborder: 0, scrolling: 'no'}

How do I convert between big-endian and little-endian values in C++?

Wow, I couldn't believe some of the answers I've read here. There's actually an instruction in assembly which does this faster than anything else. bswap. You could simply write a function like this...

__declspec(naked) uint32_t EndianSwap(uint32 value)
{
    __asm
    {
        mov eax, dword ptr[esp + 4]
        bswap eax
        ret
    }
}

It is MUCH faster than the intrinsics that have been suggested. I've disassembled them and looked. The above function has no prologue/epilogue so virtually has no overhead at all.

unsigned long _byteswap_ulong(unsigned long value);

Doing 16 bit is just as easy, with the exception that you'd use xchg al, ah. bswap only works on 32-bit registers.

64-bit is a little more tricky, but not overly so. Much better than all of the above examples with loops and templates etc.

There are some caveats here... Firstly bswap is only available on 80x486 CPU's and above. Is anyone planning on running it on a 386?!? If so, you can still replace bswap with...

mov ebx, eax
shr ebx, 16
xchg bl, bh
xchg al, ah
shl eax, 16
or eax, ebx

Also inline assembly is only available in x86 code in Visual Studio. A naked function cannot be lined and also isn't available in x64 builds. I that instance, you're going to have to use the compiler intrinsics.

Iterating through struct fieldnames in MATLAB

You have to use curly braces ({}) to access fields, since the fieldnames function returns a cell array of strings:

for i = 1:numel(fields)
  teststruct.(fields{i})
end

Using parentheses to access data in your cell array will just return another cell array, which is displayed differently from a character array:

>> fields(1)  % Get the first cell of the cell array

ans = 

    'a'       % This is how the 1-element cell array is displayed

>> fields{1}  % Get the contents of the first cell of the cell array

ans =

a             % This is how the single character is displayed

Flutter command not found

You must have .bash_profile file and define flutter path in .bash_profile file.

  1. First of all, if you do not have or do not know .bash_profile, please look my answer: How do I edit $PATH (.bash_profile) on OSX?

  2. You should add below line(.../flutter_SDK_path/flutter/bin) in your .bash_profile

export PATH=$PATH:/home/username/Documents/flutter_SDK_path/flutter/bin

After these steps, you can write flutter codes such as, flutter doctor, flutter build ios, flutter clean or etc. in terminal of Macbook.

@canerkaseler

Neither BindingResult nor plain target object for bean name available as request attr

Make sure that your Spring form mentions the modelAttribute="<Model Name".

Example:

@Controller
@RequestMapping("/greeting.html")
public class GreetingController {

 @ModelAttribute("greeting")
 public Greeting getGreetingObject() {
  return new Greeting();
 }

 /**
  * GET
  * 
  * 
  */
 @RequestMapping(method = RequestMethod.GET)
 public String handleRequest() {
  return "greeting";
 }

 /**
  * POST
  * 
  * 
  */
 @RequestMapping(method = RequestMethod.POST)
 public ModelAndView processSubmit(@ModelAttribute("greeting") Greeting greeting, BindingResult result){
  ModelAndView mv = new ModelAndView();
  mv.addObject("greeting", greeting);  
  return mv;
 }
}

In your JSP :

<form:form  modelAttribute="greeting" method="POST" action="greeting.html">

Using % for host when creating a MySQL user

localhost is special in MySQL, it means a connection over a UNIX socket (or named pipes on Windows, I believe) as opposed to a TCP/IP socket. Using % as the host does not include localhost, hence the need to explicitly specify it.

How to pause a YouTube player when hiding the iframe?

A more concise, elegant, and secure answer: add “?enablejsapi=1” to the end of the video URL, then construct and stringify an ordinary object representing the pause command:

const YouTube_pause_video_command_JSON = JSON.stringify(Object.create(null, {
    "event": {
        "value": "command",
        "enumerable": true
    },
    "func": {
        "value": "pauseVideo",
        "enumerable": true
    }
}));

Use the Window.postMessage method to send the resulting JSON string to the embedded video document:

// |iframe_element| is defined elsewhere.
const video_URL = iframe_element.getAttributeNS(null, "src");
iframe_element.contentWindow.postMessage(YouTube_pause_video_command_JSON, video_URL);

Make sure you specify the video URL for the Window.postMessage method’s targetOrigin argument to ensure that your messages won’t be sent to any unintended recipient.

How to get body of a POST in php?

function getPost()
{
    if(!empty($_POST))
    {
        // when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request
        // NOTE: if this is the case and $_POST is empty, check the variables_order in php.ini! - it must contain the letter P
        return $_POST;
    }

    // when using application/json as the HTTP Content-Type in the request 
    $post = json_decode(file_get_contents('php://input'), true);
    if(json_last_error() == JSON_ERROR_NONE)
    {
        return $post;
    }

    return [];
}

print_r(getPost());

Set transparent background using ImageMagick and commandline prompt

Solution

color=$( convert filename.png -format "%[pixel:p{0,0}]" info:- )
convert filename.png -alpha off -bordercolor $color -border 1 \
    \( +clone -fuzz 30% -fill none -floodfill +0+0 $color \
       -alpha extract -geometry 200% -blur 0x0.5 \
       -morphology erode square:1 -geometry 50% \) \
    -compose CopyOpacity -composite -shave 1 outputfilename.png

Explanation

This is rather a bit longer than the simple answers previously given, but it gives much better results: (1) The quality is superior due to antialiased alpha, and (2) only the background is removed as opposed to a single color. ("Background" is defined as approximately the same color as the top left pixel, using a floodfill from the picture edges.)

Additionally, the alpha channel is also eroded by half a pixel to avoid halos. Of course, ImageMagick's morphological operations don't (yet?) work at the subpixel level, so you can see I am blowing up the alpha channel to 200% before eroding.

Comparison of results

Here is a comparison of the simple approach ("-fuzz 2% -transparent white") versus my solution, when run on the ImageMagick logo. I've flattened both transparent images onto a saddle brown background to make the differences apparent (click for originals).

The simple replacement of white as transparent doesn't always work Antialiased alphachannel and floodfill looks much better

Notice how the Wizard's beard has disappeared in the simple approach. Compare the edges of the Wizard to see how antialiased alpha helps the figure blend smoothly into the background.

Of course, I completely admit there are times when you may wish to use the simpler solution. (For example: It's a heck of a lot easier to remember and if you're converting to GIF, you're limited to 1-bit alpha anyhow.)

mktrans shell script

Since it's unlikely you'll want to type this command repeatedly, I recommend wrapping it in a script. You can download a BASH shell script from github which performs my suggested solution. It can be run on multiple files in a directory and includes helpful comments in case you want to tweak things.

bg_removal script

By the way, ImageMagick actually comes with a script called "bg_removal" which uses floodfill in a similar manner as my solution. However, the results are not great because it still uses 1-bit alpha. Also, the bg_removal script runs slower and is a little bit trickier to use (it requires you to specify two different fuzz values). Here's an example of the output from bg_removal.

The bg_removal script: has beard, but lacks antialiasing

print variable and a string in python

From what I know, printing can be done in many ways

Here's what I follow:

Printing string with variables

a = 1
b = "ball"
print("I have", a, b)

Versus printing string with functions

a = 1
b = "ball"
print("I have" + str(a) + str(b))

In this case, str() is a function that takes a variable and spits out what its assigned to as a string

They both yield the same print, but in two different ways. I hope that was helpful

Execution time of C program

You have to take into account that measuring the time that took a program to execute depends a lot on the load that the machine has in that specific moment.

Knowing that, the way of obtain the current time in C can be achieved in different ways, an easier one is:

#include <time.h>

#define CPU_TIME (getrusage(RUSAGE_SELF,&ruse), ruse.ru_utime.tv_sec + \
  ruse.ru_stime.tv_sec + 1e-6 * \
  (ruse.ru_utime.tv_usec + ruse.ru_stime.tv_usec))

int main(void) {
    time_t start, end;
    double first, second;

    // Save user and CPU start time
    time(&start);
    first = CPU_TIME;

    // Perform operations
    ...

    // Save end time
    time(&end);
    second = CPU_TIME;

    printf("cpu  : %.2f secs\n", second - first); 
    printf("user : %d secs\n", (int)(end - start));
}

Hope it helps.

Regards!

How to ensure a <select> form field is submitted when it is disabled?

Same solution suggested by Tres without using jQuery

<form onsubmit="document.getElementById('mysel').disabled = false;" action="..." method="GET">

   <select id="mysel" disabled="disabled">....</select>

   <input name="submit" id="submit" type="submit" value="SEND FORM">
</form>

This might help someone understand more, but obviously is less flexible than the jQuery one.

angular 4: *ngIf with multiple conditions

<div *ngIf="currentStatus !== ('status1' || 'status2' || 'status3' || 'status4')">

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

  1. Search for sqllocaldb or localDB in your windows start menu and right click on open file location
  2. Open command prompt in the file location you found from the search
  3. On your command prompt type sqllocaldb start

  4. Use <add name="defaultconnection" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=tododb;Integrated Security=True" providerName="System.Data.SqlClient" />

Hosting ASP.NET in IIS7 gives Access is denied?

In my case running c:\windows\Microsoft.Net\Framework64\v4.0.30319\aspnet_regiis.exe /i resolved the 403 access denied issue.

How can I dynamically switch web service addresses in .NET without a recompile?

As long as the web service methods and underlying exposed classes do not change, it's fairly trivial. With Visual Studio 2005 (and newer), adding a web reference creates an app.config (or web.config, for web apps) section that has this URL. All you have to do is edit the app.config file to reflect the desired URL.

In our project, our simple approach was to just have the app.config entries commented per environment type (development, testing, production). So we just uncomment the entry for the desired environment type. No special coding needed there.

standard size for html newsletter template

Ideally the email content should be about 550px wide to fit within most email clients preview window. If you know for sure your target market can view bigger then you can design bigger. Loads of email examples over on http://www.beautiful-email-newsletters.com/

Multiple "style" attributes in a "span" tag: what's supposed to happen?

In HTML, SGML and XML, (1) attributes cannot be repeated, and should only be defined in an element once.

So your example:

<span style="color:blue" style="font-style:italic">Test</span>

is non-conformant to the HTML standard, and will result in undefined behaviour, which explains why different browsers are rendering it differently.


Since there is no defined way to interpret this, browsers can interpret it however they want and merge them, or ignore them as they wish.

(1): Every article I can find states that attributes are "key/value" pairs or "attribute-value" pairs, heavily implying the keys must be unique. The best source I can find states:

Attribute names (id and status in this example) are subject to the same restrictions as other names in XML; they need not be unique across the whole DTD, however, but only within the list of attributes for a given element. (Emphasis mine.)

Nginx fails to load css files

  1. In your nginx.conf file, add mime.types to your http body like so:

    http {
        include /etc/nginx/mime.types;
        include /etc/nginx/conf.d/*.conf;
    }
    
  2. Now go to the terminal and run the following to reload the server:

    sudo nginx -s reload
    
  3. Open your web browser and do a hard reload: Right click on the reload button and select hard reload. On Chrome you can do Ctrl+Shift+R

Make TextBox uneditable

Enabled="false" in aspx page

How would I get everything before a : in a string Python

Just use the split function. It returns a list, so you can keep the first element:

>>> s1.split(':')
['Username', ' How are you today?']
>>> s1.split(':')[0]
'Username'

Difference between rake db:migrate db:reset and db:schema:load

You could simply look in the Active Record Rake tasks as that is where I believe they live as in this file. https://github.com/rails/rails/blob/fe1f4b2ad56f010a4e9b93d547d63a15953d9dc2/activerecord/lib/active_record/tasks/database_tasks.rb

What they do is your question right?

That depends on where they come from and this is just and example to show that they vary depending upon the task. Here we have a different file full of tasks.

https://github.com/rails/rails/blob/fe1f4b2ad56f010a4e9b93d547d63a15953d9dc2/activerecord/Rakefile

which has these tasks.

namespace :db do
  task create: ["db:mysql:build", "db:postgresql:build"]
  task drop: ["db:mysql:drop", "db:postgresql:drop"]
end

This may not answer your question but could give you some insight into go ahead and look the source over especially the rake files and tasks. As they do a pretty good job of helping you use rails they don't always document the code that well. We could all help there if we know what it is supposed to do.

Run AVD Emulator without Android Studio

On windows

......\Android\sdk\tools\bin\avdmanager list avds

......\Android\sdk\tools\emulator.exe -avd Nexus_5X_API_27

A project with an Output Type of Class Library cannot be started directly

This was the solution that worked for me since I couldn't find 'Common Properties' option.

  1. Select your topmost level project in Solution Explorer.
  2. Go to Project, and in contextual menu Set as StartUp Project.

    Set as StartUp Project

See also: A project with an Output type of Class Library cannot be started directly

How to deal with persistent storage (e.g. databases) in Docker

Use Persistent Volume Claim (PVC) from Kubernetes, which is a Docker container management and scheduling tool:

Persistent Volumes

The advantages of using Kubernetes for this purpose are that:

  • You can use any storage like NFS or other storage and even when the node is down, the storage need not be.
  • Moreover the data in such volumes can be configured to be retained even after the container itself is destroyed - so that it can be reclaimed, if necessary, by another container.

How to prevent a dialog from closing when a button is clicked

public class ComentarDialog extends DialogFragment{
private EditText comentario;

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    LayoutInflater inflater = LayoutInflater.from(getActivity());
    View v = inflater.inflate(R.layout.dialog_comentar, null);
    comentario = (EditText)v.findViewById(R.id.etxt_comentar_dialog);

    builder.setTitle("Comentar")
           .setView(v)
           .setPositiveButton("OK", null)
           .setNegativeButton("CANCELAR", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {

               }
           });

    return builder.create();
}

@Override
public void onStart() {
    super.onStart();

    //Obtenemos el AlertDialog
    AlertDialog dialog = (AlertDialog)getDialog();

    dialog.setCanceledOnTouchOutside(false);
    dialog.setCancelable(false);//Al presionar atras no desaparece

    //Implementamos el listener del boton OK para mostrar el toast
    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(TextUtils.isEmpty(comentario.getText())){
               Toast.makeText(getActivity(), "Ingrese un comentario", Toast.LENGTH_SHORT).show();
               return;
            }
            else{
                ((AlertDialog)getDialog()).dismiss();
            }
        }
    });

    //Personalizamos
    Resources res = getResources();

    //Buttons
    Button positive_button = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
    positive_button.setBackground(res.getDrawable(R.drawable.btn_selector_dialog));

    Button negative_button =  dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
    negative_button.setBackground(res.getDrawable(R.drawable.btn_selector_dialog));

    int color = Color.parseColor("#304f5a");

    //Title
    int titleId = res.getIdentifier("alertTitle", "id", "android");
    View title = dialog.findViewById(titleId);
    if (title != null) {
        ((TextView) title).setTextColor(color);
    }

    //Title divider
    int titleDividerId = res.getIdentifier("titleDivider", "id", "android");
    View titleDivider = dialog.findViewById(titleDividerId);
    if (titleDivider != null) {
        titleDivider.setBackgroundColor(res.getColor(R.color.list_menu_divider));
    }
}
}

ImportError: No module named BeautifulSoup

I had the same problem with eclipse on windows 10.

I installed it like recommende over the windows command window (cmd) with:

C:\Users\NAMEOFUSER\AppData\Local\Programs\Python\beautifulsoup4-4.8.2\setup.py install 

BeautifulSoup was install like this in my python directory:

C:\Users\NAMEOFUSE\AppData\Local\Programs\Python\Python38\Lib\site-packages\beautifulsoup4-4.8.2-py3.8.egg

After manually coping the bs4 and EGG-INFO folders into the site-packages folder everything started to work, also the example:

from bs4 import BeautifulSoup


html = """
    <html>
        <body>
            <p> Ich bin ein Absatz!</p>
        </body>
    </html>
"""
print(html)


soup = BeautifulSoup(html, 'html.parser')

print(soup.find_all("p"))

android: how to change layout on button click?

You wanted to change the layout at runtime on button click. But that is not possible and as it has been rightly stated above, you need to restart the activity. You will come across a similar problem when u plan on changing the theme based on user's selection but it will not reflect in runtime. You will have to restart the activity.

How to make <input type="file"/> accept only these types?

Use accept attribute with the MIME_type as values

<input type="file" accept="image/gif, image/jpeg" />

Sending Windows key using SendKeys

OK turns out what you really want is this: http://inputsimulator.codeplex.com/

Which has done all the hard work of exposing the Win32 SendInput methods to C#. This allows you to directly send the windows key. This is tested and works:

InputSimulator.SimulateModifiedKeyStroke(VirtualKeyCode.LWIN, VirtualKeyCode.VK_E);

Note however that in some cases you want to specifically send the key to the application (such as ALT+F4), in which case use the Form library method. In others, you want to send it to the OS in general, use the above.


Old

Keeping this here for reference, it will not work in all operating systems, and will not always behave how you want. Note that you're trying to send these key strokes to the app, and the OS usually intercepts them early. In the case of Windows 7 and Vista, too early (before the E is sent).

SendWait("^({ESC}E)") or Send("^({ESC}E)")

Note from here: http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx

To specify that any combination of SHIFT, CTRL, and ALT should be held down while several other keys are pressed, enclose the code for those keys in parentheses. For example, to specify to hold down SHIFT while E and C are pressed, use "+(EC)". To specify to hold down SHIFT while E is pressed, followed by C without SHIFT, use "+EC".

Note that since you want ESC and (say) E pressed at the same time, you need to enclose them in brackets.

Writing an input integer into a cell

I've done this kind of thing with a form that contains a TextBox.

So if you wanted to put this in say cell H1, then use:

ActiveSheet.Range("H1").Value = txtBoxName.Text

How do I increase the cell width of the Jupyter/ipython notebook in my browser?

This is the code I ended up using. It stretches input & output cells to the left and right. Note that the input/output number indication will be gone:

from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
display(HTML("<style>.output_result { max-width:100% !important; }</style>"))
display(HTML("<style>.prompt { display:none !important; }</style>"))

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is guaranteed to be a unsigned integer that is 16 bits large

unsigned short int is guaranteed to be a unsigned short integer, where short integer is defined by the compiler (and potentially compiler flags) you are currently using. For most compilers for x86 hardware a short integer is 16 bits large.

Also note that per the ANSI C standard only the minimum size of 16 bits is defined, the maximum size is up to the developer of the compiler

Minimum Type Limits

Any compiler conforming to the Standard must also respect the following limits with respect to the range of values any particular type may accept. Note that these are lower limits: an implementation is free to exceed any or all of these. Note also that the minimum range for a char is dependent on whether or not a char is considered to be signed or unsigned.

Type Minimum Range

signed char     -127 to +127
unsigned char      0 to 255
short int     -32767 to +32767
unsigned short int 0 to 65535

Java: Add elements to arraylist with FOR loop where element name has increasing number

If you simply need a list, you could use:

List<Answer> answers = Arrays.asList(answer1, answer2, answer3);

If you specifically require an ArrayList, you could use:

ArrayList<Answer> answers = new ArrayList(Arrays.asList(answer1, answer2, answer3));

Removing element from array in component state

As mentioned in a comment to ephrion's answer above, filter() can be slow, especially with large arrays, as it loops to look for an index that appears to have been determined already. This is a clean, but inefficient solution.

As an alternative one can simply 'slice' out the desired element and concatenate the fragments.

var dummyArray = [];    
this.setState({data: dummyArray.concat(this.state.data.slice(0, index), this.state.data.slice(index))})

Hope this helps!

Get current index from foreach loop

You have two options here, 1. Use for instead for foreach for iteration.But in your case the collection is IEnumerable and the upper limit of the collection is unknown so foreach will be the best option. so i prefer to use another integer variable to hold the iteration count: here is the code for that:

int i = 0; // for index
foreach (var row in list)
{
    bool IsChecked;// assign value to this variable
    if (IsChecked)
    {    
       // use i value here                
    }
    i++; // will increment i in each iteration
}

How do I determine if my python shell is executing in 32bit or 64bit?

Try using ctypes to get the size of a void pointer:

import ctypes
print ctypes.sizeof(ctypes.c_voidp)

It'll be 4 for 32 bit or 8 for 64 bit.

Getting number of days in a month

I made it calculate days in month from datetimepicker selected month and year , and I but the code in datetimepicker1 textchanged to return the result in a textbox with this code

private void DateTimePicker1_ValueChanged(object sender, EventArgs e)
{
    int s = System.DateTime.DaysInMonth(DateTimePicker1.Value.Date.Year, DateTimePicker1.Value.Date.Month);

    TextBox1.Text = s.ToString();
} 

Is there a way to continue broken scp (secure copy) command process in Linux?

This is all you need.

 rsync -e ssh file host:/directory/.

What is setup.py?

When you download a package with setup.py open your Terminal (Mac,Linux) or Command Prompt (Windows). Using cd and helping you with Tab button set the path right to the folder where you have downloaded the file and where there is setup.py :

iMac:~ user $ cd path/pakagefolderwithsetupfile/

Press enter, you should see something like this:

iMac:pakagefolderwithsetupfile user$

Then type after this python setup.py install :

iMac:pakagefolderwithsetupfile user$ python setup.py install

Press enter. Done!

java.io.FileNotFoundException: (Access is denied)

Also, in some cases is important to check the target folder permissions. To give write permission for the user might be the solution. That worked for me.

Read HttpContent in WebApi controller

Even though this solution might seem obvious, I just wanted to post it here so the next guy will google it faster.

If you still want to have the model as a parameter in the method, you can create a DelegatingHandler to buffer the content.

internal sealed class BufferizingHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        await request.Content.LoadIntoBufferAsync();
        var result = await base.SendAsync(request, cancellationToken);
        return result;
    }
}

And add it to the global message handlers:

configuration.MessageHandlers.Add(new BufferizingHandler());

This solution is based on the answer by Darrel Miller.

This way all the requests will be buffered.

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

alter table tablename drop (column1, column2, column3......);

Setting Android Theme background color

Open res -> values -> styles.xml and to your <style> add this line replacing with your image path <item name="android:windowBackground">@drawable/background</item>. Example:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowBackground">@drawable/background</item>
    </style>

</resources>

There is a <item name ="android:colorBackground">@color/black</item> also, that will affect not only your main window background but all the component in your app. Read about customize theme here.

If you want version specific styles:

If a new version of Android adds theme attributes that you want to use, you can add them to your theme while still being compatible with old versions. All you need is another styles.xml file saved in a values directory that includes the resource version qualifier. For example:

res/values/styles.xml        # themes for all versions
res/values-v21/styles.xml    # themes for API level 21+ only

Because the styles in the values/styles.xml file are available for all versions, your themes in values-v21/styles.xml can inherit them. As such, you can avoid duplicating styles by beginning with a "base" theme and then extending it in your version-specific styles.

Read more here(doc in theme).

HTML CSS Invisible Button

you must use the following properties for a button element to make it transparent.

Transparent Button With No Text

button {

    background: transparent;
    border: none !important;
    font-size:0;
}

Transparent Button With Visible Text

button {

    background: transparent;
    border: none !important;
}?

and use absolute position to position the element.

For Example

you have the button element under a div. Use position : relative on div and position: absolute on the button to position it within the div.

here is a working JSFiddle

here is an updated JSFiddle that displays only text from the button.

Select multiple columns in data.table by their numeric indices

If you want to use column names to select the columns, simply use .(), which is an alias for list():

library(data.table)
dt <- data.table(a = 1:2, b = 2:3, c = 3:4)
dt[ , .(b, c)] # select the columns b and c
# Result:
#    b c
# 1: 2 3
# 2: 3 4

MySQL CREATE FUNCTION Syntax

You have to override your ; delimiter with something like $$ to avoid this kind of error.

After your function definition, you can set the delimiter back to ;.

This should work:

DELIMITER $$
CREATE FUNCTION F_Dist3D (x1 decimal, y1 decimal) 
RETURNS decimal
DETERMINISTIC
BEGIN 
  DECLARE dist decimal;
  SET dist = SQRT(x1 - y1);
  RETURN dist;
END$$
DELIMITER ;

How to flatten only some dimensions of a numpy array

An alternative approach is to use numpy.resize() as in:

In [37]: shp = (50,100,25)
In [38]: arr = np.random.random_sample(shp)
In [45]: resized_arr = np.resize(arr, (np.prod(shp[:2]), shp[-1]))
In [46]: resized_arr.shape
Out[46]: (5000, 25)

# sanity check with other solutions
In [47]: resized = np.reshape(arr, (-1, shp[-1]))
In [48]: np.allclose(resized_arr, resized)
Out[48]: True

Insert 2 million rows into SQL Server quickly

I use the bcp utility. (Bulk Copy Program) I load about 1.5 million text records each month. Each text record is 800 characters wide. On my server, it takes about 30 seconds to add the 1.5 million text records into a SQL Server table.

The instructions for bcp are at http://msdn.microsoft.com/en-us/library/ms162802.aspx

javascript regex for special characters

How about this:-

var regularExpression = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,}$/;

It will allow a minimum of 6 characters including numbers, alphabets, and special characters

Static Final Variable in Java

Just having final will have the intended effect.

final int x = 5;

...
x = 10; // this will cause a compilation error because x is final

Declaring static is making it a class variable, making it accessible using the class name <ClassName>.x

Default visibility for C# classes and members (fields, methods, etc.)?

From MSDN:

Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.


Nested types, which are members of other types, can have declared accessibilities as indicated in the following table.

Default Nested Member Accessibility & Allowed Accessibility Modifiers

Source: Accessibility Levels (C# Reference) (December 6th, 2017)

How to navigate to a directory in C:\ with Cygwin?

I'll add something that helps me out a lot with cygwin. Whenever setting up a new system, I always do this

ln -s /cygdrive/c /c

This creates a symbolic link to /cygdrive/c with a new file called /c (in the home directory)

Then you can do this in your shell

cd /c/Foo
cd /c/

Very handy.

Why are empty catch blocks a bad idea?

I mean, for instance, sometimes you want to get some additional info from somewhere (webservice, database) and you really don't care if you'll get this info or not. So you try to get it, and if anything happens, that's ok, I'll just add a "catch (Exception ignored) {}" and that's all

So, going with your example, it's a bad idea in that case because you're catching and ignoring all exceptions. If you were catching only EInfoFromIrrelevantSourceNotAvailable and ignoring it, that would be fine, but you're not. You're also ignoring ENetworkIsDown, which may or may not be important. You're ignoring ENetworkCardHasMelted and EFPUHasDecidedThatOnePlusOneIsSeventeen, which are almost certainly important.

An empty catch block is not an issue if it's set up to only catch (and ignore) exceptions of certain types which you know to be unimportant. The situations in which it's a good idea to suppress and silently ignore all exceptions, without stopping to examine them first to see whether they're expected/normal/irrelevant or not, are exceedingly rare.

How do I make Git ignore file mode (chmod) changes?

If

git config --global core.filemode false

does not work for you, do it manually:

cd into yourLovelyProject folder

cd into .git folder:

cd .git

edit the config file:

nano config

change true to false

[core]
        repositoryformatversion = 0
        filemode = true

->

[core]
        repositoryformatversion = 0
        filemode = false

save, exit, go to upper folder:

cd ..

reinit the git

git init

you are done!

Best way to do multiple constructors in PHP

For php7, I compare parameters type as well, you can have two constructors with same number of parameters but different type.

trait GenericConstructorOverloadTrait
{
    /**
     * @var array Constructors metadata
     */
    private static $constructorsCache;
    /**
     * Generic constructor
     * GenericConstructorOverloadTrait constructor.
     */
    public function __construct()
    {
        $params = func_get_args();
        $numParams = func_num_args();

        $finish = false;

        if(!self::$constructorsCache){
            $class = new \ReflectionClass($this);
            $constructors =  array_filter($class->getMethods(),
                function (\ReflectionMethod $method) {
                return preg_match("/\_\_construct[0-9]+/",$method->getName());
            });
            self::$constructorsCache = $constructors;
        }
        else{
            $constructors = self::$constructorsCache;
        }
        foreach($constructors as $constructor){
            $reflectionParams = $constructor->getParameters();
            if(count($reflectionParams) != $numParams){
                continue;
            }
            $matched = true;
            for($i=0; $i< $numParams; $i++){
                if($reflectionParams[$i]->hasType()){
                    $type = $reflectionParams[$i]->getType()->__toString();
                }
                if(
                    !(
                        !$reflectionParams[$i]->hasType() ||
                        ($reflectionParams[$i]->hasType() &&
                            is_object($params[$i]) &&
                            $params[$i] instanceof $type) ||
                        ($reflectionParams[$i]->hasType() &&
                            $reflectionParams[$i]->getType()->__toString() ==
                            gettype($params[$i]))
                    )
                ) {
                    $matched = false;
                    break;
                }

            }

            if($matched){
                call_user_func_array(array($this,$constructor->getName()),
                    $params);
                $finish = true;
                break;
            }
        }

        unset($constructor);

        if(!$finish){
            throw new \InvalidArgumentException("Cannot match construct by params");
        }
    }

}

To use it:

class MultiConstructorClass{

    use GenericConstructorOverloadTrait;

    private $param1;

    private $param2;

    private $param3;

    public function __construct1($param1, array $param2)
    {
        $this->param1 = $param1;
        $this->param2 = $param2;
    }

    public function __construct2($param1, array $param2, \DateTime $param3)
    {
        $this->__construct1($param1, $param2);
        $this->param3 = $param3;
    }

    /**
     * @return \DateTime
     */
    public function getParam3()
    {
        return $this->param3;
    }

    /**
     * @return array
     */
    public function getParam2()
    {
        return $this->param2;
    }

    /**
     * @return mixed
     */
    public function getParam1()
    {
        return $this->param1;
    }
}

Setting action for back button in navigation controller

Easiest way

You can use the UINavigationController's delegate methods. The method willShowViewController is called when the back button of your VC is pressed.do whatever you want when back btn pressed

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated;

pandas: find percentile stats of a given column

assume series s

s = pd.Series(np.arange(100))

Get quantiles for [.1, .2, .3, .4, .5, .6, .7, .8, .9]

s.quantile(np.linspace(.1, 1, 9, 0))

0.1     9.9
0.2    19.8
0.3    29.7
0.4    39.6
0.5    49.5
0.6    59.4
0.7    69.3
0.8    79.2
0.9    89.1
dtype: float64

OR

s.quantile(np.linspace(.1, 1, 9, 0), 'lower')

0.1     9
0.2    19
0.3    29
0.4    39
0.5    49
0.6    59
0.7    69
0.8    79
0.9    89
dtype: int32

Can't import javax.servlet.annotation.WebServlet

Add library 'Server Runtime' to your java build path, and it shall resolve the issue.