Programs & Examples On #Last modified

How to get File Created Date and Modified Date

You can use this code to see the last modified date of a file.

DateTime dt = File.GetLastWriteTime(path);

And this code to see the creation time.

DateTime fileCreatedDate = File.GetCreationTime(@"C:\Example\MyTest.txt");

How to find the most recent file in a directory using .NET, and without looping?

Short and simple:

new DirectoryInfo(path).GetFiles().OrderByDescending(o => o.LastWriteTime).FirstOrDefault();

how to set start value as "0" in chartjs?

Please add this option:

//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,

(Reference: Chart.js)

N.B: The original solution I posted was for Highcharts, if you are not using Highcharts then please remove the tag to avoid confusion

YouTube Video Embedded via iframe Ignoring z-index?

wmode=opaque or transparent at the beginning of my query string didnt solve anything. This issue for me only occurs on Chrome, and not across even all computers. Just one cpu. It occurs in vimeo embeds as well, and possibly others.

My solution to to attach to the 'shown' and 'hidden' event of the bootstrap modals I am using, add a class which sets the iframe to 1x1 pixels, and remove the class when the modal closes. Seems like it works and is simple to implement.

Can you have multiline HTML5 placeholder text in a <textarea>?

On most (see details below) browsers, editing the placeholder in javascript allows multiline placeholder. As it has been said, it's not compliant with the specification and you shouldn't expect it to work in the future (edit: it does work).

This example replaces all multiline textarea's placeholder.

_x000D_
_x000D_
var textAreas = document.getElementsByTagName('textarea');

Array.prototype.forEach.call(textAreas, function(elem) {
    elem.placeholder = elem.placeholder.replace(/\\n/g, '\n');
});
_x000D_
<textarea class="textAreaMultiline" 
          placeholder="Hello, \nThis is multiline example \n\nHave Fun"
          rows="5" cols="35"></textarea>
_x000D_
_x000D_
_x000D_

JsFiddle snippet.

Expected result

Expected result


Based on comments it seems some browser accepts this hack and others don't.
This is the results of tests I ran (with browsertshots and browserstack)

  • Chrome: >= 35.0.1916.69
  • Firefox: >= 35.0 (results varies on platform)
  • IE: >= 10
  • KHTML based browsers: 4.8
  • Safari: No (tested = Safari 8.0.6 Mac OS X 10.8)
  • Opera: No (tested <= 15.0.1147.72)

Fused with theses statistics, this means that it works on about 88.7% of currently (Oct 2015) used browsers.

Update: Today, it works on at least 94.4% of currently (July 2018) used browsers.

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

this issue was driving me insane until i found this post which said to do

brew upgrade python3 

(not using pycharm, using sublime)

Error when importing ssl in Python 3.7.4 on macOS 10.14.6

PHP include relative path

You could always include it using __DIR__:

include(dirname(__DIR__).'/config.php');

__DIR__ is a 'magical constant' and returns the directory of the current file without the trailing slash. It's actually an absolute path, you just have to concatenate the file name to __DIR__. In this case, as we need to ascend a directory we use PHP's dirname which ascends the file tree, and from here we can access config.php.

You could set the root path in this method too:

define('ROOT_PATH', dirname(__DIR__) . '/');

in test.php would set your root to be at the /root/ level.

include(ROOT_PATH.'config.php');

Should then work to include the config file from where you want.

How does one add keyboard languages and switch between them in Linux Mint 16?

For Linux (I am using Fedora 30) the Shortcut is (Window/Start + Space) Try that and tell me. That works for me

Bind event to right mouse click

Is contextmenu an event?

I would use onmousedown or onclick then grab the MouseEvent's button property to determine which button was pressed (0 = left, 1 = middle, 2 = right).

Eclipse error: "Editor does not contain a main type"

Try closing and reopening the file, then press Ctrl+F11.

Verify that the name of the file you are running is the same as the name of the project you are working in, and that the name of the public class in that file is the same as the name of the project you are working in as well.

Otherwise, restart Eclipse. Let me know if this solves the problem! Otherwise, comment, and I'll try and help.

PHP DOMDocument loadHTML not encoding UTF-8 correctly

You could prefix a line enforcing utf-8 encoding, like this:

@$doc->loadHTML('<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $profile);

And you can then continue with the code you already have, like:

$doc->saveXML()

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

I think we're over analyzing and maybe complicating a bit the "continuous" suite of words. In this context continuous means automation. For the other words attached to "continuous" use the English language as your translation guide and please don't try to complicate things! In "continuous build" we automatically build (write/compile/link/etc) our application into something that's executable for a specific platform/container/runtime/etc. "Continuous integration" means that your new functionality tests and performs as intended when interacting with another entity. Obviously, before integration takes place, the build must happen and thorough testing would also be used to validate the integration. So, in "continuous integration" one uses automation to add value to an existing bucket of functionality in a way that doesn't negatively disrupt the existing functionality but rather integrates nicely with it, adding a perceived value to the whole. Integration implies, by its mere English definition, that things jive harmoniously so in code-talk my add compiles, links, tests and runs perfectly within the whole. You wouldn't call something integrated if it failed the end product, would you?! In our context "Continuous deployment" is synonymous with "continuos delivery" since at the end of the day we've provided functionality to our customers. However, by over analyzing this, I could argue that deploy is a subset of delivery because deploying something doesn't necessarily mean that we delivered. We deployed the code but because we haven't effectively communicated to our stakeholders, we failed to deliver from a business perspective! We deployed the troops but we haven't delivered the promised water and food to the nearby town. What if I were to add the "continuous transition" term, would it have its own merit? After all, maybe it's better suited to describe the movement of code through environments since it has the connotation of "from/to" more so than deployment or delivery which could imply one location only, in perpetuity! This is what we get if we don't apply common sense.

In conclusion, this is simple stuff to describe (doing it is a bit more ...complicated!), just use common sense, the English language and you'll be fine.

Java regex capturing groups indexes

Capturing and grouping

Capturing group (pattern) creates a group that has capturing property.

A related one that you might often see (and use) is (?:pattern), which creates a group without capturing property, hence named non-capturing group.

A group is usually used when you need to repeat a sequence of patterns, e.g. (\.\w+)+, or to specify where alternation should take effect, e.g. ^(0*1|1*0)$ (^, then 0*1 or 1*0, then $) versus ^0*1|1*0$ (^0*1 or 1*0$).

A capturing group, apart from grouping, will also record the text matched by the pattern inside the capturing group (pattern). Using your example, (.*):, .* matches ABC and : matches :, and since .* is inside capturing group (.*), the text ABC is recorded for the capturing group 1.

Group number

The whole pattern is defined to be group number 0.

Any capturing group in the pattern start indexing from 1. The indices are defined by the order of the opening parentheses of the capturing groups. As an example, here are all 5 capturing groups in the below pattern:

(group)(?:non-capturing-group)(g(?:ro|u)p( (nested)inside)(another)group)(?=assertion)
|     |                       |          | |      |      ||       |     |
1-----1                       |          | 4------4      |5-------5     |
                              |          3---------------3              |
                              2-----------------------------------------2

The group numbers are used in back-reference \n in pattern and $n in replacement string.

In other regex flavors (PCRE, Perl), they can also be used in sub-routine calls.

You can access the text matched by certain group with Matcher.group(int group). The group numbers can be identified with the rule stated above.

In some regex flavors (PCRE, Perl), there is a branch reset feature which allows you to use the same number for capturing groups in different branches of alternation.

Group name

From Java 7, you can define a named capturing group (?<name>pattern), and you can access the content matched with Matcher.group(String name). The regex is longer, but the code is more meaningful, since it indicates what you are trying to match or extract with the regex.

The group names are used in back-reference \k<name> in pattern and ${name} in replacement string.

Named capturing groups are still numbered with the same numbering scheme, so they can also be accessed via Matcher.group(int group).

Internally, Java's implementation just maps from the name to the group number. Therefore, you cannot use the same name for 2 different capturing groups.

How to reduce the space between <p> tags?

A more real-world example:

p { margin: 10px 0;}

Import/Index a JSON file into Elasticsearch

If you want to import a json file into Elasticsearch and create an index, use this Python script.

import json
from elasticsearch import Elasticsearch

es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
i = 0
with open('el_dharan.json') as raw_data:
    json_docs = json.load(raw_data)
    for json_doc in json_docs:
            i = i + 1
            es.index(index='ind_dharan', doc_type='doc_dharan', id=i, body=json.dumps(json_doc))

How do I concatenate strings in Swift?

You could use SwiftString (https://github.com/amayne/SwiftString) to do this.

"".join(["string1", "string2", "string3"]) // "string1string2string"
" ".join(["hello", "world"]) // "hello world"

DISCLAIMER: I wrote this extension

Create folder with batch but only if it doesn't already exist

set myDIR=LOG
IF not exist %myDIR% (mkdir %myDIR%)

Replace all whitespace characters

Actually it has been worked but

just try this.

take the value /\s/g into a string variable like

String a = /\s/g;

str = str.replaceAll(a,"X");

Getting the base url of the website and globally passing it to twig in Symfony 2

Valid from Symfony v2.1 through v4.1+

If you want the base URL to a Symfony application, you should use getSchemeAndHttpHost() concatenated together with getBaseUrl(), similar to how getUri() works, except without the router path and query string.

{{ app.request.schemeAndHttpHost ~ app.request.baseUrl }}

For example, if your Symfony website URL lives at https://www.stackoverflow.com/app1/, then these two methods return these values:

getSchemeAndHttpHost

https://www.stackoverflow.com

getBaseUrl

/app1

Note: getBaseUrl() includes the script filename (ie /app.php) if it's in your URL.

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

In addition to the other answers, a struct can (but usually doesn't) have virtual functions, in which case the size of the struct will also include the space for the vtbl.

How can I send and receive WebSocket messages on the server side?

Implementation in Go

Encode part (server -> browser)

func encode (message string) (result []byte) {
  rawBytes := []byte(message)
  var idxData int

  length := byte(len(rawBytes))
  if len(rawBytes) <= 125 { //one byte to store data length
    result = make([]byte, len(rawBytes) + 2)
    result[1] = length
    idxData = 2
  } else if len(rawBytes) >= 126 && len(rawBytes) <= 65535 { //two bytes to store data length
    result = make([]byte, len(rawBytes) + 4)
    result[1] = 126 //extra storage needed
    result[2] = ( length >> 8 ) & 255
    result[3] = ( length      ) & 255
    idxData = 4
  } else {
    result = make([]byte, len(rawBytes) + 10)
    result[1] = 127
    result[2] = ( length >> 56 ) & 255
    result[3] = ( length >> 48 ) & 255
    result[4] = ( length >> 40 ) & 255
    result[5] = ( length >> 32 ) & 255
    result[6] = ( length >> 24 ) & 255
    result[7] = ( length >> 16 ) & 255
    result[8] = ( length >>  8 ) & 255
    result[9] = ( length       ) & 255
    idxData = 10
  }

  result[0] = 129 //only text is supported

  // put raw data at the correct index
  for i, b := range rawBytes {
    result[idxData + i] = b
  }
  return
}

Decode part (browser -> server)

func decode (rawBytes []byte) string {
  var idxMask int
  if rawBytes[1] == 126 {
    idxMask = 4
  } else if rawBytes[1] == 127 {
    idxMask = 10
  } else {
    idxMask = 2
  }

  masks := rawBytes[idxMask:idxMask + 4]
  data := rawBytes[idxMask + 4:len(rawBytes)]
  decoded := make([]byte, len(rawBytes) - idxMask + 4)

  for i, b := range data {
    decoded[i] = b ^ masks[i % 4]
  }
  return string(decoded)
}

How to retrieve the LoaderException property?

try
{
  // load the assembly or type
}
catch (Exception ex)
{
  if (ex is System.Reflection.ReflectionTypeLoadException)
  {
    var typeLoadException = ex as ReflectionTypeLoadException;
    var loaderExceptions  = typeLoadException.LoaderExceptions;
  }
}

Array to Hash Ruby

All answers assume the starting array is unique. OP did not specify how to handle arrays with duplicate entries, which result in duplicate keys.

Let's look at:

a = ["item 1", "item 2", "item 3", "item 4", "item 1", "item 5"]

You will lose the item 1 => item 2 pair as it is overridden bij item 1 => item 5:

Hash[*a]
=> {"item 1"=>"item 5", "item 3"=>"item 4"}

All of the methods, including the reduce(&:merge!) result in the same removal.

It could be that this is exactly what you expect, though. But in other cases, you probably want to get a result with an Array for value instead:

{"item 1"=>["item 2", "item 5"], "item 3"=>["item 4"]}

The naïve way would be to create a helper variable, a hash that has a default value, and then fill that in a loop:

result = Hash.new {|hash, k| hash[k] = [] } # Hash.new with block defines unique defaults.
a.each_slice(2) {|k,v| result[k] << v }
a
=> {"item 1"=>["item 2", "item 5"], "item 3"=>["item 4"]}

It might be possible to use assoc and reduce to do above in one line, but that becomes much harder to reason about and read.

Specifying number of decimal places in Python

There's a few ways to do this depending on how you want to hold the value.

You can use basic string formatting, e.g

'Your Meal Price is %.2f' %  mealPrice

You can modify the 2 to whatever precision you need.

However, since you're dealing with money you should look into the decimal module which has a cool method named quantize which is exactly for working with monetary applications. You can use it like so:

from decimal import Decimal, ROUND_DOWN
mealPrice = Decimal(str(mealPrice)).quantize(Decimal('.01'), rounding=ROUND_DOWN)

Note that the rounding attribute is purely optional as well.

how to parse JSONArray in android

Here is a better way for doing it. Hope this helps

protected void onPostExecute(String result) {
                Log.v(TAG + " result);


                if (!result.equals("")) {

                    // Set up variables for API Call
                    ArrayList<String> list = new ArrayList<String>();

                    try {
                        JSONArray jsonArray = new JSONArray(result);

                        for (int i = 0; i < jsonArray.length(); i++) {

                            list.add(jsonArray.get(i).toString());

                        }//end for
                    } catch (JSONException e) {
                        Log.e(TAG, "onPostExecute > Try > JSONException => " + e);
                        e.printStackTrace();
                    }


                    adapter = new ArrayAdapter<String>(ListViewData.this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
                    listView.setAdapter(adapter);
                    listView.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            // ListView Clicked item index
                            int itemPosition = position;

                            // ListView Clicked item value
                            String itemValue = (String) listView.getItemAtPosition(position);

                            // Show Alert
                            Toast.makeText( ListViewData.this, "Position :" + itemPosition + "  ListItem : " + itemValue, Toast.LENGTH_LONG).show();
                        }
                    });

                    adapter.notifyDataSetChanged();
...

The server principal is not able to access the database under the current security context in SQL Server MS 2012

I believe you might be missing a "Grant Connect To" statement when you created the database user.

Below is the complete snippet you will need to create both a login against the SQL Server DBMS as well as a user against the database

USE [master]
GO

CREATE LOGIN [SqlServerLogin] WITH PASSWORD=N'Passwordxyz', DEFAULT_DATABASE=[master], CHECK_EXPIRATION=OFF, CHECK_POLICY=ON
GO

USE [myDatabase]
GO

CREATE USER [DatabaseUser] FOR LOGIN [SqlServerLogin] WITH DEFAULT_SCHEMA=[mySchema]
GO

GRANT CONNECT TO [DatabaseUser]
GO

-- the role membership below will allow you to run a test "select" query against the tables in your database
ALTER ROLE [db_datareader] ADD MEMBER [DatabaseUser]
GO

How do I capture the output of a script if it is being ran by the task scheduler?

This snippet uses wmic.exe to build the date string. It isn't mangled by locale settings

rem DATE as YYYY-MM-DD via WMIC.EXE
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I
set RDATE=%datetime:~0,4%-%datetime:~4,2%-%datetime:~6,2% 

What is the difference between #import and #include in Objective-C?

The #import directive was added to Objective-C as an improved version of #include. Whether or not it's improved, however, is still a matter of debate. #import ensures that a file is only ever included once so that you never have a problem with recursive includes. However, most decent header files protect themselves against this anyway, so it's not really that much of a benefit.

Basically, it's up to you to decide which you want to use. I tend to #import headers for Objective-C things (like class definitions and such) and #include standard C stuff that I need. For example, one of my source files might look like this:

#import <Foundation/Foundation.h>

#include <asl.h>
#include <mach/mach.h>

TLS 1.2 in .NET Framework 4.0

Make the following changes in your Registry and it should work:

1.) .NET Framework strong cryptography registry keys

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

2.) Secure Channel (Schannel) TLS 1.2 registry keys

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2]

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

How to add external library in IntelliJ IDEA?

I've used this process to attach a 3rd party Jar to an Android project in IDEA.

  • Copy the Jar to your libs/ directory
  • Open Project Settings (Ctrl Alt Shift S)
  • Under the Project Settings panel on the left, choose Modules
  • On the larger right pane, choose the Dependencies tab
  • Press the Add... button on the far right of the screen (if you have a smaller screen like me, you may have to drag resize to the right in order to see it)
  • From the dropdown of Add options, choose "Library". A "Choose Libraries" dialog will appear.
  • Press "New Library..."
  • Choose a suitable title for the library
  • Press "Attach Classes..."
  • Choose the Jar from your libs/ directory, and press OK to dismiss

The library should now be recognised.

Insert auto increment primary key to existing table

In order to make the existing primary key as auto_increment, you may use:

ALTER TABLE table_name MODIFY id INT AUTO_INCREMENT;

Execute a stored procedure in another stored procedure in SQL server

Procedure example:

Create  PROCEDURE SP_Name
     @UserName nvarchar(200),
     @Password nvarchar(200)
AS
BEGIN
    DECLARE  @loginID  int

    --Statements for this Store Proc
  --
  -- 
  --

  --execute second store procedure
  --below line calling sencond Store Procedure Exec is used for execute Store Procedure.
    **Exec SP_Name_2 @params** (if any) 


END

Ant build failed: "Target "build..xml" does not exist"

since your ant file's name is build.xml, you should just type ant without ant build.xml. that is: > ant [enter]

How can I style a PHP echo text?

You can "style echo" with adding new HTML code.

echo '<span class="city">' . $ip['cityName'] . '</span>';

JavaScript Array Push key value

You may use:


To create array of objects:

var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));

Demo:

_x000D_
_x000D_
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.map(value => ({[value]: 0}));_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_


Or if you wants to create a single object from values of arrays:

var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});

Demo:

_x000D_
_x000D_
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

What do raw.githubusercontent.com URLs represent?

raw.githubusercontent.com/username/repo-name/branch-name/path

Replace username with the username of the user that created the repo.

Replace repo-name with the name of the repo.

Replace branch-name with the name of the branch.

Replace path with the path to the file.

To reverse to go to GitHub.com:

GitHub.com/username/repo-name/directory-path/blob/branch-name/filename

How to disable <br> tags inside <div> by css?

I used it like this:

@media (max-width: 450px) {
  br {
    display: none;
  }
}

nb: media query via Foundation nb2: this is useful if one of the editor intend to use
tags in his/her copy and you need to deal with it specifically under some conditions—on mobile for example.

Material effect on button with background color

I came to this post looking for a way to have a background color of my ListView Item, yet keep the ripple.

I simply added my color as a background and the selectableItemBackground as a foreground:

<style name="my_list_item">
    <item name="android:background">@color/white</item>
    <item name="android:foreground">?attr/selectableItemBackground</item>
    <item name="android:layout_height">@dimen/my_list_item_height</item>
</style>

and it works like a charm. I guess the same technique could be used for buttons as well. Good luck :)

PDOException SQLSTATE[HY000] [2002] No such file or directory

If you are using Laravel Homestead, here is settings

(include Vagrant-Virtual Machine)

.bash-profile

alias vm="ssh [email protected] -p 2222"

database.php

    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', '127.0.0.1'),
        'database'  => env('DB_DATABASE', 'homestead'),
        'username'  => env('DB_USERNAME', 'homestead'),
        'password'  => env('DB_PASSWORD', 'secret'),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

Terminal

vm

vagrant@homestead:~/Code/projectFolder  php artisan migrate:install

How to hide the keyboard when I press return key in a UITextField?

If you want to hide the keyboard for a particular keyboard use [self.view resignFirstResponder]; If you want to hide any keyboard from view use [self.view endEditing:true];

How can I set the background color of <option> in a <select> element?

_x000D_
_x000D_
select.list1 option.option2
{
    background-color: #007700;
}
_x000D_
<select class="list1">
  <option value="1">Option 1</option>
  <option value="2" class="option2">Option 2</option>
</select>
_x000D_
_x000D_
_x000D_

Headers and client library minor version mismatch

Changing PHP version from 5.6 to 5.5 Fixed it.

You have to go to control panel > CGI Script and change PHP version there.

Select arrow style change

Assume, selectDrop is the class present in your HTML tag.So, this much of code is enough to change default arrow icon:

.selectDrop{
      background: url(../images/icn-down-arrow-light.png) no-repeat right #ddd; /*To change default icon with provided image*/
      -webkit-appearance:none; /*For hiding default pointer of drop-down on Chrome*/
      -moz-appearance:none; /*For hiding default pointer of drop-down on Mozilla*/
      background-position-x: 90%; /*Adjust according to width of dropdown*/
    }

How to use a switch case 'or' in PHP

Try with these following examples in this article : http://phpswitch.com/

Possible Switch Cases :

(i). A simple switch statement

The switch statement is wondrous and magic. It's a piece of the language that allows you to select between different options for a value, and run different pieces of code depending on which value is set.

Each possible option is given by a case in the switch statement.

Example :

switch($bar)
{
    case 4:
        echo "This is not the number you're looking for.\n";
        $foo = 92;
}

(ii). Delimiting code blocks

The major caveat of switch is that each case will run on into the next one, unless you stop it with break. If the simple case above is extended to cover case 5:

Example :

case 4:
    echo "This is not the number you're looking for.\n";
    $foo = 92;
    break;

case 5:
    echo "A copy of Ringworld is on its way to you!\n";
    $foo = 34;
    break;

(iii). Using fallthrough for multiple cases

Because switch will keep running code until it finds a break, it's easy enough to take the concept of fallthrough and run the same code for more than one case:

Example :

case 2:

case 3:
case 4:
    echo "This is not the number you're looking for.\n";
    $foo = 92;
    break;

case 5:
    echo "A copy of Ringworld is on its way to you!\n";
    $foo = 34;
    break;

(iv). Advanced switching: Condition cases

PHP's switch doesn't just allow you to switch on the value of a particular variable: you can use any expression as one of the cases, as long as it gives a value for the case to use. As an example, here's a simple validator written using switch:

Example :

switch(true)
{
    case (strlen($foo) > 30):
        $error = "The value provided is too long.";
    $valid = false;
    break;

    case (!preg_match('/^[A-Z0-9]+$/i', $foo)):
        $error = "The value must be alphanumeric.";
    $valid = false;
    break;

    default:
    $valid = true;
    break;
}

i think this may help you to resolve your problem.

Max tcp/ip connections on Windows Server 2008

How many thousands of users?

I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.

Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.

If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.

Edited to add details from the comment below...

If you're already thinking of multiple servers I'd take the following approach.

  1. Use the free tools that I link to and prove to yourself that you can create a reasonable number of connections onto your target OS (beware of the Windows limits on dynamic ports which may cause your client connections to fail, search for MAX_USER_PORT).

  2. during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html

How can I reload .emacs after changing it?

Very strange that the very convenient

M-x eval-buffer

is not mentioned here.

It immediately evaluates all code in the buffer, its the quickest method, if your .emacs is idempotent.

Show diff between commits

Try

git diff k73ud^..dj374

to make sure to include all changes of k73ud in the resulting diff.

git diff compares two endpoints (instead of a commit range). Since the OP want to see the changes introduced by k73ud, he/she needs to difference between the first parent commit of k73ud: k73ud^ (or k73ud^1 or k73ud~).

That way, the diff results will include changes since k73ud parent (meaning including changes from k73ud itself), instead of changes introduced since k73ud (up to dj374).

Also you can try:

git diff oldCommit..newCommit
git diff k73ud..dj374 

and (1 space, not more):

git diff oldCommit newCommit
git diff k73ud dj374

And if you need to get only files names (e.g. to copy hotfix them manually):

git diff k73ud dj374 --name-only

And you can get changes applied to another branch:

git diff k73ud dj374 > my.patch
git apply my.patch

Prevent form redirect OR refresh on submit?

Just handle the form submission on the submit event, and return false:

$('#contactForm').submit(function () {
 sendContactForm();
 return false;
});

You don't need any more the onclick event on the submit button:

<input class="submit" type="submit" value="Send" />

In SQL, is UPDATE always faster than DELETE+INSERT?

It depends on the product. A product could be implemented that (under the covers) converts all UPDATEs into a (transactionally wrapped) DELETE and INSERT. Provided the results are consistent with the UPDATE semantics.

I'm not saying I'm aware of any product that does this, but it's perfectly legal.

What is difference between sjlj vs dwarf vs seh?

There's a short overview at MinGW-w64 Wiki:

Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?

The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.

The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.

GCC GNU about Exception Handling:

GCC supports two methods for exception handling (EH):

  • DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
  • A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.

[...]

Structured Exception Handling (SEH)

Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]

See also:

Simulation of CONNECT BY PRIOR of Oracle in SQL Server

The SQL standard way to implement recursive queries, as implemented e.g. by IBM DB2 and SQL Server, is the WITH clause. See this article for one example of translating a CONNECT BY into a WITH (technically a recursive CTE) -- the example is for DB2 but I believe it will work on SQL Server as well.

Edit: apparently the original querant requires a specific example, here's one from the IBM site whose URL I already gave. Given a table:

CREATE TABLE emp(empid  INTEGER NOT NULL PRIMARY KEY,
                 name   VARCHAR(10),
                 salary DECIMAL(9, 2),
                 mgrid  INTEGER);

where mgrid references an employee's manager's empid, the task is, get the names of everybody who reports directly or indirectly to Joan. In Oracle, that's a simple CONNECT:

SELECT name 
  FROM emp
  START WITH name = 'Joan'
  CONNECT BY PRIOR empid = mgrid

In SQL Server, IBM DB2, or PostgreSQL 8.4 (as well as in the SQL standard, for what that's worth;-), the perfectly equivalent solution is instead a recursive query (more complex syntax, but, actually, even more power and flexibility):

WITH n(empid, name) AS 
   (SELECT empid, name 
    FROM emp
    WHERE name = 'Joan'
        UNION ALL
    SELECT nplus1.empid, nplus1.name 
    FROM emp as nplus1, n
    WHERE n.empid = nplus1.mgrid)
SELECT name FROM n

Oracle's START WITH clause becomes the first nested SELECT, the base case of the recursion, to be UNIONed with the recursive part which is just another SELECT.

SQL Server's specific flavor of WITH is of course documented on MSDN, which also gives guidelines and limitations for using this keyword, as well as several examples.

Regex in JavaScript for validating decimal numbers

 function CheckValidAmount() {
        var amounttext = document.getElementById('txtRemittanceNumber').value;            
        if (!(/^[-+]?\d*\.?\d*$/.test(amounttext))){
            alert('Please enter only numbers into amount textbox.')
            document.getElementById('txtRemittanceNumber').value = "10.00";
        }
    }

This is the function which will take decimal number with any number of decimal places and without any decimal places.

Thanks ... :)

How to escape a JSON string containing newline characters using JavaScript?

Use encodeURIComponent() to encode the string.

Eg. var myEscapedJSONString = encodeURIComponent(JSON.stringify(myJSON));

You don't need to decode it since the web server automatically do the same.

How to add reference to a method parameter in javadoc?

As you can see in the Java Source of the java.lang.String class:

/**
 * Allocates a new <code>String</code> that contains characters from
 * a subarray of the character array argument. The <code>offset</code>
 * argument is the index of the first character of the subarray and
 * the <code>count</code> argument specifies the length of the
 * subarray. The contents of the subarray are copied; subsequent
 * modification of the character array does not affect the newly
 * created string.
 *
 * @param      value    array that is the source of characters.
 * @param      offset   the initial offset.
 * @param      count    the length.
 * @exception  IndexOutOfBoundsException  if the <code>offset</code>
 *               and <code>count</code> arguments index characters outside
 *               the bounds of the <code>value</code> array.
 */
public String(char value[], int offset, int count) {
    if (offset < 0) {
        throw new StringIndexOutOfBoundsException(offset);
    }
    if (count < 0) {
        throw new StringIndexOutOfBoundsException(count);
    }
    // Note: offset or count might be near -1>>>1.
    if (offset > value.length - count) {
        throw new StringIndexOutOfBoundsException(offset + count);
    }

    this.value = new char[count];
    this.count = count;
    System.arraycopy(value, offset, this.value, 0, count);
}

Parameter references are surrounded by <code></code> tags, which means that the Javadoc syntax does not provide any way to do such a thing. (I think String.class is a good example of javadoc usage).

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

There is a known issue with the new NDIS6 driver, you can install it to use the old NDIS5 driver

Steps I followed:

1.Uninstall Virtualbox and try reinstalling it using command prompt.
2. Run command Prompt in administrative mode;
3.Check your Network Drivers if you are using NDIS6 or 6.+ ;
  Write >VirtualBox-5.0.11-104101-Win.exe -msiparams NETWORKTYPE=NDIS5;
4.Now Follow the install steps and finish installation steps.
5. Now try starting device with VirtualBox.

This worked for me.

In Tkinter is there any way to make a widget not visible?

I was not using grid or pack.
I used just place for my widgets as their size and positioning was fixed.
I wanted to implement hide/show functionality on frame.
Here is demo

from tkinter import *
window=Tk()
window.geometry("1366x768+1+1")
def toggle_graph_visibility():
    graph_state_chosen=show_graph_checkbox_value.get()
    if graph_state_chosen==0:
        frame.place_forget()
    else:
        frame.place(x=1025,y=165)
score_pixel = PhotoImage(width=300, height=430)
show_graph_checkbox_value = IntVar(value=1)
frame=Frame(window,width=300,height=430)
graph_canvas = Canvas(frame, width = 300, height = 430,scrollregion=(0,0,300,300))
my_canvas=graph_canvas.create_image(20, 20, anchor=NW, image=score_pixel)
vbar=Scrollbar(frame,orient=VERTICAL)
vbar.config(command=graph_canvas.yview)
vbar.pack(side=RIGHT,fill=Y)
graph_canvas.config(yscrollcommand=vbar.set)
graph_canvas.pack(side=LEFT,expand=True,fill=BOTH)
frame.place(x=1025,y=165)
Checkbutton(window, text="show graph",variable=show_graph_checkbox_value,command=toggle_graph_visibility).place(x=900,y=165)
window.mainloop()

Note that in above example when 'show graph' is ticked then there is vertical scrollbar.
Graph disappears when checkbox is unselected.
I was fitting some bar graph in that area which I have not shown to keep example simple.
Most important thing to learn from above is the use of frame.place_forget() to hide and frame.place(x=x_pos,y=y_pos) to show back the content.

Repeat command automatically in Linux

To minimize drift more easily, use:

while :; do sleep 1m & some-command; wait; done

there will still be a tiny amount of drift due to bash's time to run the loop structure and the sleep command to actually execute.

hint: ':' evals to 0 ie true.

How can you strip non-ASCII characters from a string? (in C#)

Here is a pure .NET solution that doesn't use regular expressions:

string inputString = "Räksmörgås";
string asAscii = Encoding.ASCII.GetString(
    Encoding.Convert(
        Encoding.UTF8,
        Encoding.GetEncoding(
            Encoding.ASCII.EncodingName,
            new EncoderReplacementFallback(string.Empty),
            new DecoderExceptionFallback()
            ),
        Encoding.UTF8.GetBytes(inputString)
    )
);

It may look cumbersome, but it should be intuitive. It uses the .NET ASCII encoding to convert a string. UTF8 is used during the conversion because it can represent any of the original characters. It uses an EncoderReplacementFallback to to convert any non-ASCII character to an empty string.

Bash foreach loop

cat `cat filenames.txt`

will do the trick

How to scroll to bottom in a ScrollView on activity startup

It needs to be done as following:

    getScrollView().post(new Runnable() {

        @Override
        public void run() {
            getScrollView().fullScroll(ScrollView.FOCUS_DOWN);
        }
    });

This way the view is first updated and then scrolls to the "new" bottom.

Compiling dynamic HTML strings from database

Found in a google discussion group. Works for me.

var $injector = angular.injector(['ng', 'myApp']);
$injector.invoke(function($rootScope, $compile) {
  $compile(element)($rootScope);
});

CORS: credentials mode is 'include'

If it helps, I was using centrifuge with my reactjs app, and, after checking some comments below, I looked at the centrifuge.js library file, which in my version, had the following code snippet:

if ('withCredentials' in xhr) {
 xhr.withCredentials = true;
}

After I removed these three lines, the app worked fine, as expected.

Hope it helps!

jquery remove "selected" attribute of option?

Well, I spent a lot of time on this issue. To get an answer working with Chrome AND IE, I had to change my approach. The idea is to avoid removing the selected option (because cannot remove it properly with IE). => this implies to select option not by adding or setting the selected attribute on the option, but to choose an option at the "select" level using the selectedIndex prop.

Before :

$('#myselect option:contains("value")').attr('selected','selected');
$('#myselect option:contains("value")').removeAttr('selected'); => KO with IE

After :

$('#myselect').prop('selectedIndex', $('#myselect option:contains("value")').index());
$('#myselect').prop('selectedIndex','-1'); => OK with all browsers

Hope it will help

Where does pip install its packages?

pip list -v can be used to list packages' install locations, introduced in https://pip.pypa.io/en/stable/news/#b1-2018-03-31

Show install locations when list command ran with “-v” option. (#979)

>pip list -v
Package                  Version   Location                                                             Installer
------------------------ --------- -------------------------------------------------------------------- ---------
alabaster                0.7.12    c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
apipkg                   1.5       c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
argcomplete              1.10.3    c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
astroid                  2.3.3     c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
...

This feature is introduced in pip 10.0.0b1. On Ubuntu 18.04 (Bionic Beaver), pip or pip3 installed with sudo apt install python-pip or sudo apt install python3-pip is 9.0.1 which doesn't have this feature.

Check https://github.com/pypa/pip/issues/5599 for suitable ways of upgrading pip or pip3.

In JavaScript can I make a "click" event fire programmatically for a file input element?

There are ways to redirect events to the control but don't expect to be able to easily fire events to the fire control yourself as the browsers will try to block that for (good) security reasons.

If you only need the file dialog to show up when a user clicks something, let's say because you want better looking file upload buttons, then you might want to take a look at what Shaun Inman came up with.

I've been able to achieve keyboard triggering with creative shifting of focus in and out of the control between keydown, keypress & keyup events. YMMV.

My sincere advice is to leave this the alone, because this is a world of browser-incompatibility-pain. Minor browser updates may also block tricks without warning and you may have to keep reinventing hacks to keep it working.

How to dynamically change a web page's title?

Using the document.title is how you would accomplish it in JavaScript, but how is this supposed to assist with SEO? Bots don't generally execute javascript code as they traverse through pages.

How to open a website when a Button is clicked in Android application?

Import import android.net.Uri;

Intent openURL = new Intent(android.content.Intent.ACTION_VIEW);
openURL.setData(Uri.parse("http://www.example.com"));
startActivity(openURL);

or it can be done using,

TextView textView = (TextView)findViewById(R.id.yourID);

textView.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        intent.setData(Uri.parse("http://www.typeyourURL.com"));
        startActivity(intent);
    } });

How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker

If in jquery the dateformat option is not working then we can handle this situation in html page in input field of your date:

_x000D_
_x000D_
<input type="text" data-date-format='yyyy-mm-dd'  id="selectdateadmin" class="form-control" required>
_x000D_
_x000D_
_x000D_

And in javascript below this page add your date picker code:

_x000D_
_x000D_
 $('#selectdateadmin').focusin( function()_x000D_
     {_x000D_
       $("#selectdateadmin").datepicker();_x000D_
       _x000D_
     });
_x000D_
_x000D_
_x000D_

Load external css file like scripts in jquery which is compatible in ie also

Quick function based on responses.

loadCSS = function(href) {

  var cssLink = $("<link>");
  $("head").append(cssLink); //IE hack: append before setting href

  cssLink.attr({
    rel:  "stylesheet",
    type: "text/css",
    href: href
  });

};

Usage:

loadCSS("/css/file.css");

You don't have write permissions for the /var/lib/gems/2.3.0 directory

Try using chown -R on the var/lib/gems directory, assigning ownership to the user [rubyusername] in this example, the user that will be installing and developing with gems.

 # chown -R rubyusername:rubyusername /var/lib/gems 

This recursively changes everything under the gems directory. For extra security on multi-user systems, you can also create a group, rather than chowning the individual rubyusername, and add users to that group.

String date to xmlgregoriancalendar conversion

GregorianCalendar c = GregorianCalendar.from((LocalDate.parse("2016-06-22")).atStartOfDay(ZoneId.systemDefault()));
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);

How to randomize (or permute) a dataframe rowwise and columnwise?

Random Samples and Permutations ina dataframe If it is in matrix form convert into data.frame use the sample function from the base package indexes = sample(1:nrow(df1), size=1*nrow(df1)) Random Samples and Permutations

"Call to undefined function mysql_connect()" after upgrade to php-7

From the PHP Manual:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

mysqli_connect()

PDO::__construct()

use MySQLi or PDO

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

&& (AND) and || (OR) in IF statements

All the answers here are great but, just to illustrate where this comes from, for questions like this it's good to go to the source: the Java Language Specification.

Section 15:23, Conditional-And operator (&&), says:

The && operator is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true. [...] At run time, the left-hand operand expression is evaluated first [...] if the resulting value is false, the value of the conditional-and expression is false and the right-hand operand expression is not evaluated. If the value of the left-hand operand is true, then the right-hand expression is evaluated [...] the resulting value becomes the value of the conditional-and expression. Thus, && computes the same result as & on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

And similarly, Section 15:24, Conditional-Or operator (||), says:

The || operator is like | (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false. [...] At run time, the left-hand operand expression is evaluated first; [...] if the resulting value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated. If the value of the left-hand operand is false, then the right-hand expression is evaluated; [...] the resulting value becomes the value of the conditional-or expression. Thus, || computes the same result as | on boolean or Boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

A little repetitive, maybe, but the best confirmation of exactly how they work. Similarly the conditional operator (?:) only evaluates the appropriate 'half' (left half if the value is true, right half if it's false), allowing the use of expressions like:

int x = (y == null) ? 0 : y.getFoo();

without a NullPointerException.

How to count string occurrence in string?

No one will ever see this, but it's good to bring back recursion and arrow functions once in a while (pun gloriously intended)

String.prototype.occurrencesOf = function(s, i) {
 return (n => (n === -1) ? 0 : 1 + this.occurrencesOf(s, n + 1))(this.indexOf(s, (i || 0)));
};

Algorithm to find Largest prime factor of a number

With Java:

For int values:

public static int[] primeFactors(int value) {
    int[] a = new int[31];
    int i = 0, j;
    int num = value;
    while (num % 2 == 0) {
        a[i++] = 2;
        num /= 2;
    }
    j = 3;
    while (j <= Math.sqrt(num) + 1) {
        if (num % j == 0) {
            a[i++] = j;
            num /= j;
        } else {
            j += 2;
        }
    }
    if (num > 1) {
        a[i++] = num;
    }
    int[] b = Arrays.copyOf(a, i);
    return b;
}

For long values:

static long[] getFactors(long value) {
    long[] a = new long[63];
    int i = 0;
    long num = value;
    while (num % 2 == 0) {
        a[i++] = 2;
        num /= 2;
    }
    long j = 3;
    while (j <= Math.sqrt(num) + 1) {
        if (num % j == 0) {
            a[i++] = j;
            num /= j;
        } else {
            j += 2;
        }
    }
    if (num > 1) {
        a[i++] = num;
    }
    long[] b = Arrays.copyOf(a, i);
    return b;
}

How can I install the Beautiful Soup module on the Mac?

Brian beat me too it, but since I already have the transcript:

easy_install

aaron@ares ~$ sudo easy_install BeautifulSoup
Searching for BeautifulSoup
Best match: BeautifulSoup 3.0.7a
Processing BeautifulSoup-3.0.7a-py2.5.egg
BeautifulSoup 3.0.7a is already the active version in easy-install.pth

Using /Library/Python/2.5/site-packages/BeautifulSoup-3.0.7a-py2.5.egg
Processing dependencies for BeautifulSoup
Finished processing dependencies for BeautifulSoup

.. or the normal boring way:

aaron@ares ~/Downloads$ curl http://www.crummy.com/software/BeautifulSoup/download/BeautifulSoup.tar.gz > bs.tar.gz
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 71460  100 71460    0     0  84034      0 --:--:-- --:--:-- --:--:--  111k

aaron@ares ~/Downloads$ tar -xzvf bs.tar.gz 
BeautifulSoup-3.1.0.1/
BeautifulSoup-3.1.0.1/BeautifulSoup.py
BeautifulSoup-3.1.0.1/BeautifulSoup.py.3.diff
BeautifulSoup-3.1.0.1/BeautifulSoupTests.py
BeautifulSoup-3.1.0.1/BeautifulSoupTests.py.3.diff
BeautifulSoup-3.1.0.1/CHANGELOG
BeautifulSoup-3.1.0.1/README
BeautifulSoup-3.1.0.1/setup.py
BeautifulSoup-3.1.0.1/testall.sh
BeautifulSoup-3.1.0.1/to3.sh
BeautifulSoup-3.1.0.1/PKG-INFO
BeautifulSoup-3.1.0.1/BeautifulSoup.pyc
BeautifulSoup-3.1.0.1/BeautifulSoupTests.pyc

aaron@ares ~/Downloads$ cd BeautifulSoup-3.1.0.1/

aaron@ares ~/Downloads/BeautifulSoup-3.1.0.1$ sudo python setup.py install
running install
<... snip ...>

How do you use the "WITH" clause in MySQL?

In Sql the with statement specifies a temporary named result set, known as a common table expression (CTE). It can be used for recursive queries, but in this case, it specifies as subset. If mysql allows for subselectes i would try

select t1.* 
from  (
            SELECT  article.*, 
                    userinfo.*, 
                    category.* 
            FROM    question INNER JOIN 
                    userinfo ON userinfo.user_userid=article.article_ownerid INNER JOIN category ON article.article_categoryid=category.catid
            WHERE   article.article_isdeleted = 0
     ) t1
ORDER BY t1.article_date DESC Limit 1, 3

Why calling react setState method doesn't mutate the state immediately?

You could try using ES7 async/await. For instance using your example:

handleChange: async function(event) {
    console.log(this.state.value);
    await this.setState({value: event.target.value});
    console.log(this.state.value);
}

How do I add slashes to a string in Javascript?

if (!String.prototype.hasOwnProperty('addSlashes')) {
    String.prototype.addSlashes = function() {
        return this.replace(/&/g, '&amp;') /* This MUST be the 1st replacement. */
             .replace(/'/g, '&apos;') /* The 4 other predefined entities, required. */
             .replace(/"/g, '&quot;')
             .replace(/\\/g, '\\\\')
             .replace(/</g, '&lt;')
             .replace(/>/g, '&gt;').replace(/\u0000/g, '\\0');
        }
}

Usage: alert(str.addSlashes());

ref: https://stackoverflow.com/a/9756789/3584667

How to use variables in a command in sed?

This may also can help

input="inputtext"
output="outputtext"
sed "s/$input/${output}/" inputfile > outputfile

Are multiple `.gitignore`s frowned on?

You can have multiple .gitignore, each one of course in its own directory.
To check which gitignore rule is responsible for ignoring a file, use git check-ignore: git check-ignore -v -- afile.

And you can have different version of a .gitignore file per branch: I have already seen that kind of configuration for ensuring one branch ignores a file while the other branch does not: see this question for instance.

If your repo includes several independent projects, it would be best to reference them as submodules though.
That would be the actual best practices, allowing each of those projects to be cloned independently (with their respective .gitignore files), while being referenced by a specific revision in a global parent project.
See true nature of submodules for more.


Note that, since git 1.8.2 (March 2013) you can do a git check-ignore -v -- yourfile in order to see which gitignore run (from which .gitignore file) is applied to 'yourfile', and better understand why said file is ignored.
See "which gitignore rule is ignoring my file?"

Why the switch statement cannot be applied on strings?

C++ 11 update of apparently not @MarmouCorp above but http://www.codeguru.com/cpp/cpp/cpp_mfc/article.php/c4067/Switch-on-Strings-in-C.htm

Uses two maps to convert between the strings and the class enum (better than plain enum because its values are scoped inside it, and reverse lookup for nice error messages).

The use of static in the codeguru code is possible with compiler support for initializer lists which means VS 2013 plus. gcc 4.8.1 was ok with it, not sure how much farther back it would be compatible.

/// <summary>
/// Enum for String values we want to switch on
/// </summary>
enum class TestType
{
    SetType,
    GetType
};

/// <summary>
/// Map from strings to enum values
/// </summary>
std::map<std::string, TestType> MnCTest::s_mapStringToTestType =
{
    { "setType", TestType::SetType },
    { "getType", TestType::GetType }
};

/// <summary>
/// Map from enum values to strings
/// </summary>
std::map<TestType, std::string> MnCTest::s_mapTestTypeToString
{
    {TestType::SetType, "setType"}, 
    {TestType::GetType, "getType"}, 
};

...

std::string someString = "setType";
TestType testType = s_mapStringToTestType[someString];
switch (testType)
{
    case TestType::SetType:
        break;

    case TestType::GetType:
        break;

    default:
        LogError("Unknown TestType ", s_mapTestTypeToString[testType]);
}

Why does Oracle not find oci.dll?

I was also looking for solving this issue. Maybe this answer will help someone.

In my case similar issue have appeared when I used Oracle Instant Client 18.5 for connecting to DB using Toad 13.1.1.5

To solve it I've downloaded more recent version of OIC - Oracle Instant Client 19.3 and Toad connected to Oracle's DB without issues.

Maybe there was version incompatibility issue. New version of Toad require a new version of oci library.

Both OICs were 64 bit and folders of both of them I've added into the user's Path variable.

Client OS: Win10

Server: OL7.7,

DB: 18c

Changing factor levels with dplyr mutate

You can use the recode function from dplyr.

df <- iris %>%
     mutate(Species = recode(Species, setosa = "SETOSA",
         versicolor = "VERSICOLOR",
         virginica = "VIRGINICA"
     )
)

How to run a script as root on Mac OS X?

As in any unix-based environment, you can use the sudo command:

$ sudo script-name

It will ask for your password (your own, not a separate root password).

What's the CMake syntax to set and use variables?

Here are a couple basic examples to get started quick and dirty.

One item variable

Set variable:

SET(INSTALL_ETC_DIR "etc")

Use variable:

SET(INSTALL_ETC_CROND_DIR "${INSTALL_ETC_DIR}/cron.d")

Multi-item variable (ie. list)

Set variable:

SET(PROGRAM_SRCS
        program.c
        program_utils.c
        a_lib.c
        b_lib.c
        config.c
        )

Use variable:

add_executable(program "${PROGRAM_SRCS}")

CMake docs on variables

Creating random colour in Java?

import android.graphics.Color;

import java.util.Random;

public class ColorDiagram {
    // Member variables (properties about the object)
    public String[] mColors = {
            "#39add1", // light blue
            "#3079ab", // dark blue
            "#c25975", // mauve
            "#e15258", // red
            "#f9845b", // orange
            "#838cc7", // lavender
            "#7d669e", // purple
            "#53bbb4", // aqua
            "#51b46d", // green
            "#e0ab18", // mustard
            "#637a91", // dark gray
            "#f092b0", // pink
            "#b7c0c7"  // light gray
    };

    // Method (abilities: things the object can do)
    public int getColor() {
        String color = "";

        // Randomly select a fact
        Random randomGenerator = new Random(); // Construct a new Random number generator
        int randomNumber = randomGenerator.nextInt(mColors.length);

        color = mColors[randomNumber];
        int colorAsInt = Color.parseColor(color);

        return colorAsInt;
    }
}

Short form for Java if statement

I'm always forgeting how to use the ?: ternary operator. This supplemental answer is a quick reminder. It is shorthand for if-then-else.

myVariable = (testCondition) ? someValue : anotherValue;

where

  • () holds the if
  • ? means then
  • : means else

It is the same as

if (testCondition) {
    myVariable = someValue;
} else {
    myVariable = anotherValue;
}

c++ exception : throwing std::string

Though this question is rather old and has already been answered, I just want to add a note on how to do proper exception handling in C++11:

Use std::nested_exception and std::throw_with_nested

Using these, in my opinion, leads to cleaner exception design and makes it unnecessary to create an exception class hierarchy.

Note that this enables you to get a backtrace on your exceptions inside your code without need for a debugger or cumbersome logging. It is described on StackOverflow here and here, how to write a proper exception handler which will rethrow nested exceptions.

Since you can do this with any derived exception class, you can add a lot of information to such a backtrace! You may also take a look at my MWE on GitHub, where a backtrace would look something like this:

Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"

"The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"

In Ubuntu In the conf file: /etc/apache2/sites-enabled/your-file.conf

change

AddHandler application/x-httpd-php .js .xml .htc .css

to:

AddHandler application/x-httpd-php .js .xml .htc

Multiple INNER JOIN SQL ACCESS

Access requires parentheses in the FROM clause for queries which include more than one join. Try it this way ...

FROM
    ((tbl_employee
    INNER JOIN tbl_netpay
    ON tbl_employee.emp_id = tbl_netpay.emp_id)
    INNER JOIN tbl_gross
    ON tbl_employee.emp_id = tbl_gross.emp_ID)
    INNER JOIN tbl_tax
    ON tbl_employee.emp_id = tbl_tax.emp_ID;

If possible, use the Access query designer to set up your joins. The designer will add parentheses as required to keep the db engine happy.

In NetBeans how do I change the Default JDK?

If I remember correctly, you'll need to set the netbeans_jdkhome property in your netbeans config file. Should be in your etc/netbeans.conf file.

How to delete an object by id with entity framework

The same as @Nix with a small change to be strongly typed:

If you don't want to query for it just create an entity, and then delete it.

                Customer customer = new Customer () { Id = id };
                context.Customers.Attach(customer);
                context.Customers.DeleteObject(customer);
                context.SaveChanges();

How to replace (null) values with 0 output in PIVOT

If you have a situation where you are using dynamic columns in your pivot statement you could use the following:

DECLARE @cols               NVARCHAR(MAX)
DECLARE @colsWithNoNulls    NVARCHAR(MAX)
DECLARE @query              NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(Name) 
            FROM Hospital
            WHERE Active = 1 AND StateId IS NOT NULL
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

SET @colsWithNoNulls = STUFF(
            (
                SELECT distinct ',ISNULL(' + QUOTENAME(Name) + ', ''No'') ' + QUOTENAME(Name)
                FROM Hospital
                WHERE Active = 1 AND StateId IS NOT NULL
                FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

EXEC ('
        SELECT Clinician, ' + @colsWithNoNulls + '
        FROM
        (
            SELECT DISTINCT p.FullName AS Clinician, h.Name, CASE WHEN phl.personhospitalloginid IS NOT NULL THEN ''Yes'' ELSE ''No'' END AS HasLogin
            FROM Person p
            INNER JOIN personlicense pl ON pl.personid = p.personid
            INNER JOIN LicenseType lt on lt.licensetypeid = pl.licensetypeid
            INNER JOIN licensetypegroup ltg ON ltg.licensetypegroupid = lt.licensetypegroupid
            INNER JOIN Hospital h ON h.StateId = pl.StateId
            LEFT JOIN PersonHospitalLogin phl ON phl.personid = p.personid AND phl.HospitalId = h.hospitalid
            WHERE ltg.Name = ''RN'' AND
                pl.licenseactivestatusid = 2 AND
                h.Active = 1 AND
                h.StateId IS NOT NULL
        ) AS Results
        PIVOT
        (
            MAX(HasLogin)
            FOR Name IN (' + @cols + ')
        ) p
')

Sort a list of numerical strings in ascending order

The recommended approach in this case is to sort the data in the database, adding an ORDER BY at the end of the query that fetches the results, something like this:

SELECT temperature FROM temperatures ORDER BY temperature ASC;  -- ascending order
SELECT temperature FROM temperatures ORDER BY temperature DESC; -- descending order

If for some reason that is not an option, you can change the sorting order like this in Python:

templist = [25, 50, 100, 150, 200, 250, 300, 33]
sorted(templist, key=int)               # ascending order
> [25, 33, 50, 100, 150, 200, 250, 300]
sorted(templist, key=int, reverse=True) # descending order
> [300, 250, 200, 150, 100, 50, 33, 25]

As has been pointed in the comments, the int key (or float if values with decimals are being stored) is required for correctly sorting the data if the data received is of type string, but it'd be very strange to store temperature values as strings, if that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.

Is there any way to redraw tmux window when switching smaller monitor to bigger one?

ps ax | grep tmux
17685 pts/22   S+     0:00 tmux a -t 13g2
17920 pts/11   S+     0:00 tmux a -t 13g2
18065 pts/19   S+     0:00 grep tmux

kill the other one.

CSS performance relative to translateZ(0)

If you want implications, in some scenarios Google Chrome performance is horrible with hardware acceleration enabled. Oddly enough, changing the "trick" to -webkit-transform: rotateZ(360deg); worked just fine.

I don't believe we ever figured out why.

What are the differences between stateless and stateful systems, and how do they impact parallelism?

A stateful server keeps state between connections. A stateless server does not.

So, when you send a request to a stateful server, it may create some kind of connection object that tracks what information you request. When you send another request, that request operates on the state from the previous request. So you can send a request to "open" something. And then you can send a request to "close" it later. In-between the two requests, that thing is "open" on the server.

When you send a request to a stateless server, it does not create any objects that track information regarding your requests. If you "open" something on the server, the server retains no information at all that you have something open. A "close" operation would make no sense, since there would be nothing to close.

HTTP and NFS are stateless protocols. Each request stands on its own.

Sometimes cookies are used to add some state to a stateless protocol. In HTTP (web pages), the server sends you a cookie and then the browser holds the state, only to send it back to the server on a subsequent request.

SMB is a stateful protocol. A client can open a file on the server, and the server may deny other clients access to that file until the client closes it.

How to find out which package version is loaded in R?

Old question, but not among the answers is my favorite command to get a quick and short overview of all loaded packages:

(.packages())

To see which version is installed of all loaded packages, just use the above command to subset installed.packages().

installed.packages()[(.packages()),3]

By changing the column number (3 for package version) you can get any other information stored in installed.packages() in an easy-to-read matrix. Below is an example for version number and dependency:

installed.packages()[(.packages()),c(3,5)]

Difference between __getattr__ vs __getattribute__

  • getattribute: Is used to retrieve an attribute from an instance. It captures every attempt to access an instance attribute by using dot notation or getattr() built-in function.
  • getattr: Is executed as the last resource when attribute is not found in an object. You can choose to return a default value or to raise AttributeError.

Going back to the __getattribute__ function; if the default implementation was not overridden; the following checks are done when executing the method:

  • Check if there is a descriptor with the same name (attribute name) defined in any class in the MRO chain (method object resolution)
  • Then looks into the instance’s namespace
  • Then looks into the class namespace
  • Then into each base’s namespace and so on.
  • Finally, if not found, the default implementation calls the fallback getattr() method of the instance and it raises an AttributeError exception as default implementation.

This is the actual implementation of the object.__getattribute__ method:

.. c:function:: PyObject* PyObject_GenericGetAttr(PyObject *o, PyObject *name) Generic attribute getter function that is meant to be put into a type object's tp_getattro slot. It looks for a descriptor in the dictionary of classes in the object's MRO as well as an attribute in the object's :attr:~object.dict (if present). As outlined in :ref:descriptors, data descriptors take preference over instance attributes, while non-data descriptors don't. Otherwise, an :exc:AttributeError is raised.

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

Does --disable-web-security Work In Chrome Anymore?

If you want to automate this: Kill chrome from task Manager First. In Windows - Right Click (or Shift+right click, in-case of taskbar) on Chrome Icon. Select Properties. In "Target" text-box, add --disable-web-security flag.

So text in text-box should look like

C:\Users\njadhav\AppData\Local\Google\Chrome SxS\Application\chrome.exe" --disable-web-security

Click Ok and launch chrome.

Why are arrays of references illegal?

Comment to your edit:

Better solution is std::reference_wrapper.

Details: http://www.cplusplus.com/reference/functional/reference_wrapper/

Example:

#include <iostream>
#include <functional>
using namespace std;

int main() {
    int a=1,b=2,c=3,d=4;
    using intlink = std::reference_wrapper<int>;
    intlink arr[] = {a,b,c,d};
    return 0;
}

White space at top of page

Try this

html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}

jQuery checkbox change and click event

Well .. just for the sake of saving a headache (its past midnight here), I could come up with:

$('#checkbox1').click(function() {
  if (!$(this).is(':checked')) {
    var ans = confirm("Are you sure?");
     $('#textbox1').val(ans);
  }
});

Hope it helps

MySQL: Quick breakdown of the types of joins

Based on your comment, simple definitions of each is best found at W3Schools The first line of each type gives a brief explanation of the join type

  • JOIN: Return rows when there is at least one match in both tables
  • LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
  • RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
  • FULL JOIN: Return rows when there is a match in one of the tables

END EDIT

In a nutshell, the comma separated example you gave of

SELECT * FROM a, b WHERE b.id = a.beeId AND ...

is selecting every record from tables a and b with the commas separating the tables, this can be used also in columns like

SELECT a.beeName,b.* FROM a, b WHERE b.id = a.beeId AND ...

It is then getting the instructed information in the row where the b.id column and a.beeId column have a match in your example. So in your example it will get all information from tables a and b where the b.id equals a.beeId. In my example it will get all of the information from the b table and only information from the a.beeName column when the b.id equals the a.beeId. Note that there is an AND clause also, this will help to refine your results.

For some simple tutorials and explanations on mySQL joins and left joins have a look at Tizag's mySQL tutorials. You can also check out Keith J. Brown's website for more information on joins that is quite good also.

I hope this helps you

Merge trunk to branch in Subversion

Is there something that prevents you from merging all revisions on trunk since the last merge?

svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc

should work just fine. At least if you want to merge all changes on trunk to your branch.

Convert string to hex-string in C#

few Unicode alternatives

var s = "0";

var s1 = string.Concat(s.Select(c => $"{(int)c:x4}"));  // left padded with 0 - "0030d835dfcfd835dfdad835dfe5d835dff0d835dffb"

var sL = BitConverter.ToString(Encoding.Unicode.GetBytes(s)).Replace("-", "");       // Little Endian "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF"
var sB = BitConverter.ToString(Encoding.BigEndianUnicode.GetBytes(s)).Replace("-", ""); // Big Endian "0030D835DFCFD835DFDAD835DFE5D835DFF0D835DFFB"

// no encodding "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF"
byte[] b = new byte[s.Length * sizeof(char)];
Buffer.BlockCopy(s.ToCharArray(), 0, b, 0, b.Length);
var sb = BitConverter.ToString(b).Replace("-", "");

Call external javascript functions from java code

Let us say your jsfunctions.js file has a function "display" and this file is stored in C:/Scripts/Jsfunctions.js

jsfunctions.js

var display = function(name) {
print("Hello, I am a Javascript display function",name);
return "display function return"
}

Now, in your java code, I would recommend you to use Java8 Nashorn. In your java class,

import java.io.FileNotFoundException;
import java.io.FileReader;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

class Test {
public void runDisplay() {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
try {
  engine.eval(new FileReader("C:/Scripts/Jsfunctions.js"));
  Invocable invocable = (Invocable) engine;
  Object result;
  result = invocable.invokeFunction("display", helloWorld);
  System.out.println(result);
  System.out.println(result.getClass());
  } catch (FileNotFoundException | NoSuchMethodException | ScriptException e) {
    e.printStackTrace();
    }
  }
}

Note: Get the absolute path of your javascript file and replace in FileReader() and run the java code. It should work.

Forward declaring an enum in C++

You define an enumeration to restrict the possible values of elements of the type to a limited set. This restriction is to be enforced at compile time.

When forward declaring the fact that you will use a 'limited set' later on doesn't add any value: subsequent code needs to know the possible values in order to benefit from it.

Although the compiler is concerned about the size of the enumerated type, the intent of the enumeration gets lost when you forward declare it.

How to remove and clear all localStorage data

Something like this should do:

function cleanLocalStorage() {
    for(key in localStorage) {
        delete localStorage[key];
    }
}

Be careful about using this, though, as the user may have other data stored in localStorage and would probably be pretty ticked if you deleted that. I'd recommend either a) not storing the user's data in localStorage or b) storing the user's account stuff in a single variable, and then clearing that instead of deleting all the keys in localStorage.


Edit: As Lyn pointed out, you'll be good with localStorage.clear(). My previous points still stand, however.

How can I determine browser window size on server side C#

Here's an Ajax, asxh handler and session variables approach:

Handler:

using System;
using System.Web;

public class windowSize : IHttpHandler , System.Web.SessionState.IRequiresSessionState  {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "application/json";

        var json = new System.Web.Script.Serialization.JavaScriptSerializer();
        var output = json.Serialize(new { isFirst = context.Session["BrowserWidth"] == null });
        context.Response.Write(output);

        context.Session["BrowserWidth"] =  context.Request.QueryString["Width"]; 
        context.Session["BrowserHeight"] = context.Request.QueryString["Height"];
    }

    public bool IsReusable
    {
        get { throw new NotImplementedException(); }
    }
}

Javascript:

window.onresize = function (event) {
    SetWidthHeight();
}
function SetWidthHeight() {
    var height = $(window).height();
    var width = $(window).width();
    $.ajax({
        url: "windowSize.ashx",
        data: {
            'Height': height,
            'Width': width
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (data) {     
        if (data.isFirst) {
            window.location.reload();
        };
    }).fail(function (xhr) {
        alert("Problem to retrieve browser size.");
    });

}
$(function () {
    SetWidthHeight();
});

On aspx file:

...
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/BrowserWindowSize.js"></script>
...
<asp:Label ID="lblDim" runat="server" Text=""></asp:Label>
...

Code behind:

protected void Page_Load(object sender, EventArgs e)
  {
      if (Session["BrowserWidth"] != null)
      {
          // Do all code here to avoid double execution first time
          // ....
          lblDim.Text = "Width: " + Session["BrowserWidth"] + " Height: " + Session["BrowserHeight"];
      }
  }

Source: https://techbrij.com/browser-height-width-server-responsive-design-asp-net

How to catch and print the full exception traceback without halting/exiting the program?

I don't see this mentioned in any of the other answers. If you're passing around an Exception object for whatever reason...

In Python 3.5+ you can get a trace from an Exception object using traceback.TracebackException.from_exception(). For example:

import traceback


def stack_lvl_3():
    raise Exception('a1', 'b2', 'c3')


def stack_lvl_2():
    try:
        stack_lvl_3()
    except Exception as e:
        # raise
        return e


def stack_lvl_1():
    e = stack_lvl_2()
    return e

e = stack_lvl_1()

tb1 = traceback.TracebackException.from_exception(e)
print(''.join(tb1.format()))

However, the above code results in:

Traceback (most recent call last):
  File "exc.py", line 10, in stack_lvl_2
    stack_lvl_3()
  File "exc.py", line 5, in stack_lvl_3
    raise Exception('a1', 'b2', 'c3')
Exception: ('a1', 'b2', 'c3')

This is just two levels of the stack, as opposed to what would have been printed on screen had the exception been raised in stack_lvl_2() and not intercepted (uncomment the # raise line).

As I understand it, that's because an exception records only the current level of the stack when it is raised, stack_lvl_3() in this case. As it's passed back up through the stack, more levels are being added to its __traceback__. But we intercepted it in stack_lvl_2(), meaning all it got to record was levels 3 and 2. To get the full trace as printed on stdout we'd have to catch it at the highest (lowest?) level:

import traceback


def stack_lvl_3():
    raise Exception('a1', 'b2', 'c3')


def stack_lvl_2():
    stack_lvl_3()


def stack_lvl_1():
    stack_lvl_2()


try:
    stack_lvl_1()
except Exception as exc:
    tb = traceback.TracebackException.from_exception(exc)

print('Handled at stack lvl 0')
print(''.join(tb.stack.format()))

Which results in:

Handled at stack lvl 0
  File "exc.py", line 17, in <module>
    stack_lvl_1()
  File "exc.py", line 13, in stack_lvl_1
    stack_lvl_2()
  File "exc.py", line 9, in stack_lvl_2
    stack_lvl_3()
  File "exc.py", line 5, in stack_lvl_3
    raise Exception('a1', 'b2', 'c3')

Notice that the stack print is different, the first and last lines are missing. Because it's a different format().

Intercepting the exception as far away from the point where it was raised as possible makes for simpler code while also giving more information.

What are the differences among grep, awk & sed?

I just want to mention a thing, there are many tools can do text processing, e.g. sort, cut, split, join, paste, comm, uniq, column, rev, tac, tr, nl, pr, head, tail.....

they are very handy but you have to learn their options etc.

A lazy way (not the best way) to learn text processing might be: only learn grep , sed and awk. with this three tools, you can solve almost 99% of text processing problems and don't need to memorize above different cmds and options. :)

AND, if you 've learned and used the three, you knew the difference. Actually, the difference here means which tool is good at solving what kind of problem.

a more lazy way might be learning a script language (python, perl or ruby) and do every text processing with it.

Xcode couldn't find any provisioning profiles matching

You can get this issue if Apple update their terms. Simply log into your dev account and accept any updated terms and you should be good (you will need to goto Xcode -> project->signing and capabilities and retry the certificate check. This should get you going if terms are the issue.

What is the difference between POST and GET?

Whilst not a description of the differences, below are a couple of things to think about when choosing the correct method.

  • GET requests can get cached by the browser which can be a problem (or benefit) when using ajax.
  • GET requests expose parameters to users (POST does as well but they are less visible).
  • POST can pass much more information to the server and can be of almost any length.

How to align td elements in center

The best way to center content in a table (for example <video> or <img>) is to do the following:

_x000D_
_x000D_
<table width="100%" border="0" cellspacing="0" cellpadding="100%">
<tr>
<td>Video Tag 1 Here</td>
<td>Video Tag 2 Here</td>
</tr>
</table>
_x000D_
_x000D_
_x000D_

How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

Actually, you need to update your repo first, then an upgrade of your Glibc can fix this issue.

Do checkbox inputs only post data if they're checked?

Checkboxes are posting value 'on' if and only if the checkbox is checked. Insted of catching checkbox value you can use hidden inputs

JS:

var chk = $('input[type="checkbox"]');
    chk.each(function(){
        var v = $(this).attr('checked') == 'checked'?1:0;
        $(this).after('<input type="hidden" name="'+$(this).attr('rel')+'" value="'+v+'" />');
    });

chk.change(function(){ 
        var v = $(this).is(':checked')?1:0;
        $(this).next('input[type="hidden"]').val(v);
    });

HTML:

<label>Active</label><input rel="active" type="checkbox" />

Calculate difference between two dates (number of days)?

There often is a debate on time (hours) when it comes to counting days between two dates. The responses to the question and their comments show no exception.

If performance is not a concern, I would strongly recommend documenting your calculation through intermediate conversions. For example, (EndDate - StartDate).Days is unintuitive because rounding will depend on the hour component of StartDate and EndDate.

  • If you want the duration in days to include fractions of days, then as already suggested use (EndDate - StartDate).TotalDays.
  • If you want the duration to reflect the distance between two days, then use (EndDate.Date - StartDate.Date).Days
  • If you want the duration to reflect the duration between the morning of the start date, and the evening of the end date (what you typically see in project management software), then use (EndDate.Date - StartDate.Date).Days + 1

Unexpected 'else' in "else" error

I would suggest to read up a bit on the syntax. See here.

if (dsnt<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE) 
} else if (dst<0.05) {
    wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else 
  t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)

How to terminate process from Python using pid?

Using the awesome psutil library it's pretty simple:

p = psutil.Process(pid)
p.terminate()  #or p.kill()

If you don't want to install a new library, you can use the os module:

import os
import signal

os.kill(pid, signal.SIGTERM) #or signal.SIGKILL 

See also the os.kill documentation.


If you are interested in starting the command python StripCore.py if it is not running, and killing it otherwise, you can use psutil to do this reliably.

Something like:

import psutil
from subprocess import Popen

for process in psutil.process_iter():
    if process.cmdline() == ['python', 'StripCore.py']:
        print('Process found. Terminating it.')
        process.terminate()
        break
else:
    print('Process not found: starting it.')
    Popen(['python', 'StripCore.py'])

Sample run:

$python test_strip.py   #test_strip.py contains the code above
Process not found: starting it.
$python test_strip.py 
Process found. Terminating it.
$python test_strip.py 
Process not found: starting it.
$killall python
$python test_strip.py 
Process not found: starting it.
$python test_strip.py 
Process found. Terminating it.
$python test_strip.py 
Process not found: starting it.

Note: In previous psutil versions cmdline was an attribute instead of a method.

No increment operator (++) in Ruby?

From a posting by Matz:

(1) ++ and -- are NOT reserved operator in Ruby.

(2) C's increment/decrement operators are in fact hidden assignment. They affect variables, not objects. You cannot accomplish assignment via method. Ruby uses +=/-= operator instead.

(3) self cannot be a target of assignment. In addition, altering the value of integer 1 might cause severe confusion throughout the program.

                      matz.

Adding ID's to google map markers

Just adding another solution that works for me.. You can simply append it in the marker options:

var marker = new google.maps.Marker({
    map: map, 
    position: position,

    // Custom Attributes / Data / Key-Values
    store_id: id,
    store_address: address,
    store_type: type
});

And then retrieve them with:

marker.get('store_id');
marker.get('store_address');
marker.get('store_type');

Kill detached screen session

"kill" will only kill one screen window. To "kill" the complete session, use quit.

Example

$ screen -X -S [session # you want to kill] quit

For dead sessions use: $ screen -wipe

MySQL: How to allow remote connection to mysql

I had to this challenge when working on a Java Project with MySQL server as the database.

Here's how I did it:

First, confirm that your MySQL server configuration to allow for remote connections. Use your preferred text editor to open the MySQL server configuration file:

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

Scroll down to the bind-address line and ensure that is either commented out or replaced with 0.0.0.0 (to allow all remote connections) or replaced with Ip-Addresses that you want remote connections from.

Once you make the necessary changes, save and exit the configuration file. Apply the changes made to the MySQL config file by restarting the MySQL service:

sudo systemctl restart mysql

Next, log into the MySQL server console on the server it was installed:

mysql -u root -p

Enter your mysql user password

Check the hosts that the user you want has access to already. In my case the user is root:

SELECT host FROM mysql.user WHERE user = "root";

This gave me this output:

+-----------+
| host      |
+-----------+
| localhost |
+-----------+

Next, I ran the command below to grant the root user remote access to the database named my_database:

USE my_database;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'my-password';

Note: % grants a user remote access from all hosts on a network. You can specify the Ip-Address of the individual hosts that you want to grant the user access from using the command - GRANT ALL PRIVILEGES ON *.* TO 'root'@'Ip-Address' IDENTIFIED BY 'my-password';

Afterwhich I checked the hosts that the user now has access to. In my case the user is root:

SELECT host FROM mysql.user WHERE user = "root";

This gave me this output:

+-----------+
| host      |
+-----------+
| %         |
| localhost |
+-----------+

Finally, you can try connecting to the MySQL server from another server using the command:

mysql -u username -h mysql-server-ip-address -p

Where u represents user, h represents mysql-server-ip-address and p represents password. So in my case it was:

mysql -u root -h 34.69.261.158 -p

Enter your mysql user password

You should get this output depending on your MySQL server version:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.31 MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

Resources: How to Allow Remote Connections to MySQL

That's all.

I hope this helps

long long in C/C++

It depends in what mode you are compiling. long long is not part of the C++ standard but only (usually) supported as extension. This affects the type of literals. Decimal integer literals without any suffix are always of type int if int is big enough to represent the number, long otherwise. If the number is even too big for long the result is implementation-defined (probably just a number of type long int that has been truncated for backward compatibility). In this case you have to explicitly use the LL suffix to enable the long long extension (on most compilers).

The next C++ version will officially support long long in a way that you won't need any suffix unless you explicitly want the force the literal's type to be at least long long. If the number cannot be represented in long the compiler will automatically try to use long long even without LL suffix. I believe this is the behaviour of C99 as well.

CSS property to pad text inside of div

I see a lot of answers here that have you subtracting from the width of the div and/or using box-sizing, but all you need to do is apply the padding the child elements of the div in question. So, for example, if you have some markup like this:

<div id="container">
    <p id="text">Find Agents</p>
</div>

All you need to do is apply this CSS:

#text {
    padding: 10px;
}

Here is a fiddle showing the difference: http://jsfiddle.net/CHCVF/2/

Or, better yet, if you have multiple elements and don't feel like giving them all the same class, you can do something like this:

.container * {
    padding: 5px 10px;
}

Which will select all of the child elements and assign them the padding you want. Here is a fiddle of that in action: http://jsfiddle.net/CHCVF/3/

How to check for registry value using VbScript

Try something like this:

Dim windowsShell
Dim regValue
Set windowsShell = CreateObject("WScript.Shell")
regValue = windowsShell.RegRead("someRegKey")

How to upgrade Angular CLI project?

JJB's answer got me on the right track, but the upgrade didn't go very smoothly. My process is detailed below. Hopefully the process becomes easier in the future and JJB's answer can be used or something even more straightforward.

Solution Details

I have followed the steps captured in JJB's answer to update the angular-cli precisely. However, after running npm install angular-cli was broken. Even trying to do ng version would produce an error. So I couldn't do the ng init command. See error below:

$ ng init
core_1.Version is not a constructor
TypeError: core_1.Version is not a constructor
    at Object.<anonymous> (C:\_git\my-project\code\src\main\frontend\node_modules\@angular\compiler-cli\src\version.js:18:19)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    ...

To be able to use any angular-cli commands, I had to update my package.json file by hand and bump the @angular dependencies to 2.4.1, then do another npm install.

After this I was able to do ng init. I updated my configuration files, but none of my app/* files. When this was done, I was still getting errors. The first one is detailed below, the second was the same type of error but in a different file.

ERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function (position 62:9 in the original .ts file), resolving symbol AppModule in C:/_git/my-project/code/src/main/frontend/src/app/app.module.ts

This error is tied to the following factory provider in my AppModule

{ provide: Http, useFactory: 
    (backend: XHRBackend, options: RequestOptions, router: Router, navigationService: NavigationService, errorService: ErrorService) => {
    return new HttpRerouteProvider(backend, options, router, navigationService, errorService);  
  }, deps: [XHRBackend, RequestOptions, Router, NavigationService, ErrorService]
}

To address this error, I had use an exported function and made the following change to the provider.

    { 
      provide: Http, 
      useFactory: httpFactory, 
      deps: [XHRBackend, RequestOptions, Router, NavigationService, ErrorService]
    }

... // elsewhere in AppModule

export function httpFactory(backend: XHRBackend, 
                            options: RequestOptions, 
                            router: Router, 
                            navigationService: NavigationService, 
                            errorService: ErrorService) {
  return new HttpRerouteProvider(backend, options, router, navigationService, errorService);
}

Summary

To summarize what I understand to be the most important details, the following changes were required:

  1. Update angular-cli version using the steps detailed in JJB's answer (and on their github page).

  2. Updating @angular version by hand, 2.0.0 did not seem to be supported by angular-cli version 1.0.0-beta.24

  3. With the assistance of angular-cli and the ng init command, I updated my configuration files. I think the critical changes were to angular-cli.json and package.json. See configuration file changes at the bottom.

  4. Make code changes to export functions before I reference them, as captured in the solution details.

Key Configuration Changes

angular-cli.json changes

{
  "project": {
    "version": "1.0.0-beta.16",
    "name": "frontend"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": "assets",
...

changed to...

{
  "project": {
    "version": "1.0.0-beta.24",
    "name": "frontend"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
...

My package.json looks like this after a manual merge that considers the versions used by ng-init. Note my angular version is not 2.4.1, but the change I was after was component inheritance which was introduced in 2.3, so I was fine with these versions. The original package.json is in the question.

{
  "name": "frontend",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ng test",
    "pree2e": "webdriver-manager update --standalone false --gecko false",
    "e2e": "protractor",
    "build": "ng build",
    "buildProd": "ng build --env=prod"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.3.1",
    "@angular/compiler": "^2.3.1",
    "@angular/core": "^2.3.1",
    "@angular/forms": "^2.3.1",
    "@angular/http": "^2.3.1",
    "@angular/platform-browser": "^2.3.1",
    "@angular/platform-browser-dynamic": "^2.3.1",
    "@angular/router": "^3.3.1",
    "@angular/material": "^2.0.0-beta.1",
    "@types/google-libphonenumber": "^7.4.8",
    "angular2-datatable": "^0.4.2",
    "apollo-client": "^0.4.22",
    "core-js": "^2.4.1",
    "rxjs": "^5.0.1",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.7.2",
    "google-libphonenumber": "^2.0.4",
    "graphql-tag": "^0.1.15",
    "hammerjs": "^2.0.8",
    "ng2-bootstrap": "^1.1.16"
  },
  "devDependencies": {
    "@types/hammerjs": "^2.0.33",
    "@angular/compiler-cli": "^2.3.1",
    "@types/jasmine": "2.5.38",
    "@types/lodash": "^4.14.39",
    "@types/node": "^6.0.42",
    "angular-cli": "1.0.0-beta.24",
    "codelyzer": "~2.0.0-beta.1",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.2.1",
    "protractor": "~4.0.13",
    "ts-node": "1.2.1",
    "tslint": "^4.0.2",
    "typescript": "~2.0.3",
    "typings": "1.4.0"
  }
}

How can I get a specific number child using CSS?

For IE 7 & 8 (and other browsers without CSS3 support not including IE6) you can use the following to get the 2nd and 3rd children:

2nd Child:

td:first-child + td

3rd Child:

td:first-child + td + td

Then simply add another + td for each additional child you wish to select.

If you want to support IE6 that can be done too! You simply need to use a little javascript (jQuery in this example):

$(function() {
    $('td:first-child').addClass("firstChild");
    $(".table-class tr").each(function() {
        $(this).find('td:eq(1)').addClass("secondChild");
        $(this).find('td:eq(2)').addClass("thirdChild");
    });
});

Then in your css you simply use those class selectors to make whatever changes you like:

table td.firstChild { /*stuff here*/ }
table td.secondChild { /*stuff to apply to second td in each row*/ }

How to unpack an .asar file?

It is possible to upack without node installed using the following 7-Zip plugin:
http://www.tc4shell.com/en/7zip/asar/

Thanks @MayaPosch for mentioning that in this comment.

SQL LEFT JOIN Subquery Alias

I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres.

SELECT wpoi.order_id As No_Commande
FROM  wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id 
                            AND wpp.meta_key = '_shipping_first_name'
WHERE  wpoi.order_id =2198 

how does Request.QueryString work?

A query string is an array of parameters sent to a web page.

This url: http://page.asp?x=1&y=hello

Request.QueryString[0] is the same as 
Request.QueryString["x"] and holds a string value "1"

Request.QueryString[1] is the same as 
Request.QueryString["y"] and holds a string value "hello"

How to check sbt version?

run sbt console then type sbtVersion to check sbt version, and scalaVersion for scala version

How do I create the small icon next to the website tab for my site?

This is for the icon in the browser (most of the sites omit the type):

<link rel="icon" type="image/vnd.microsoft.icon"
     href="http://example.com/favicon.ico" />

or

<link rel="icon" type="image/png"
     href="http://example.com/image.png" />

or

<link rel="apple-touch-icon"
     href="http://example.com//apple-touch-icon.png">

for the shortcut icon:

<link rel="shortcut icon"
     href="http://example.com/favicon.ico" />

Place them in the <head></head> section.

Edit may 2019 some additional examples from MDN

Links not going back a directory?

You need to give a relative file path of <a href="../index.html">Home</a>

Alternately you can specify a link from the root of your site with <a href="/pages/en/index.html">Home</a>

.. and . have special meanings in file paths, .. means up one directory and . means current directory.

so <a href="index.html">Home</a> is the same as <a href="./index.html">Home</a>

How can I check if a view is visible or not in Android?

Or you could simply use

View.isShown()

How can I suppress the newline after a print statement?

print didn't transition from statement to function until Python 3.0. If you're using older Python then you can suppress the newline with a trailing comma like so:

print "Foo %10s bar" % baz,

How to wait for the 'end' of 'resize' event and only then perform an action?

Internet Explorer provides a resizeEnd event. Other browsers will trigger the resize event many times while you're resizing.

There are other great answers here that show how to use setTimeout and the .throttle, .debounce methods from lodash and underscore, so I will mention Ben Alman's throttle-debounce jQuery plugin which accomplishes what you're after.

Suppose you have this function that you want to trigger after a resize:

function onResize() {
  console.log("Resize just happened!");
};

Throttle Example
In the following example, onResize() will only be called once every 250 milliseconds during a window resize.

$(window).resize( $.throttle( 250, onResize) );

Debounce Example
In the following example, onResize() will only be called once at the end of a window resizing action. This achieves the same result that @Mark presents in his answer.

$(window).resize( $.debounce( 250, onResize) );

Is it possible for UIStackView to scroll?

Just add this to viewdidload:

let insets = UIEdgeInsetsMake(20.0, 0.0, 0.0, 0.0)
scrollVIew.contentInset = insets
scrollVIew.scrollIndicatorInsets = insets

source: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/LayoutUsingStackViews.html

Python conditional assignment operator

There is conditional assignment in Python 2.5 and later - the syntax is not very obvious hence it's easy to miss. Here's how you do it:

x = true_value if condition else false_value

For further reference, check out the Python 2.5 docs.

Logger slf4j advantages of formatting with {} instead of string concatenation

Since, String is immutable in Java, so the left and right String have to be copied into the new String for every pair of concatenation. So, better go for the placeholder.

how to change attribute "hidden" in jquery

You can use jquery attr method

$("#delete").attr("hidden",true);

How can I create C header files

  1. Open your favorite text editor
  2. Create a new file named whatever.h
  3. Put your function prototypes in it

DONE.

Example whatever.h

#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif

Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once but it is not guaranteed to be supported on every compiler.

Example whatever.c

#include "whatever.h"

int f(int a) { return a + 1; }

And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.

Like this:

sample.c

#include "whatever.h"

int main(int argc, char **argv)
{
    printf("%d\n", f(2)); /* prints 3 */
    return 0;
}

To compile it (if you use GCC):

$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o

To link the files to create an executable file:

$ gcc sample.o whatever.o -o sample

You can test sample:

$ ./sample
3
$

How to set auto increment primary key in PostgreSQL?

Auto incrementing primary key in postgresql:

Step 1, create your table:

CREATE TABLE epictable
(
    mytable_key    serial primary key,
    moobars        VARCHAR(40) not null,
    foobars        DATE
);

Step 2, insert values into your table like this, notice that mytable_key is not specified in the first parameter list, this causes the default sequence to autoincrement.

insert into epictable(moobars,foobars) values('delicious moobars','2012-05-01')
insert into epictable(moobars,foobars) values('worldwide interblag','2012-05-02')

Step 3, select * from your table:

el@voyager$ psql -U pgadmin -d kurz_prod -c "select * from epictable"

Step 4, interpret the output:

mytable_key  |        moobars        |  foobars   
-------------+-----------------------+------------
           1 | delicious moobars     | 2012-05-01
           2 | world wide interblags | 2012-05-02
(2 rows)

Observe that mytable_key column has been auto incremented.

ProTip:

You should always be using a primary key on your table because postgresql internally uses hash table structures to increase the speed of inserts, deletes, updates and selects. If a primary key column (which is forced unique and non-null) is available, it can be depended on to provide a unique seed for the hash function. If no primary key column is available, the hash function becomes inefficient as it selects some other set of columns as a key.

Re-render React component when prop changes

componentWillReceiveProps(nextProps) { // your code here}

I think that is the event you need. componentWillReceiveProps triggers whenever your component receive something through props. From there you can have your checking then do whatever you want to do.

How to get names of enum entries?

There are already a lot of answers here but I figure I'll throw my solution onto the stack anyway.

TypeScript Playground

enum AccountType {
  Google = 'goo',
  Facebook = 'boo',
  Twitter = 'wit',
}

type Key = keyof typeof AccountType // "Google" | "Facebook" | "Twitter"

// this creates a POJO of the enum "reversed" using TypeScript's Record utility
const reversed = (Object.keys(AccountType) as Key[]).reduce((acc, key) => {
  acc[AccountType[key]] = key
  return acc
}, {} as Record<AccountType, string>)

For Clarity:

/*
 * reversed == {
 *   "goo": "Google",
 *   "boo": "Facebook",
 *   "wit": "Twitter",
 * }
 * reversed[AccountType.Google] === "Google" 
 */

Reference for TypeScript Record

A nice helper function:

const getAccountTypeName = (type: AccountType) => {
  return reversed[type]
};

// getAccountTypeName(AccountType.Twitter) === 'Twitter'

Use Excel pivot table as data source for another Pivot Table

I guess your end goal is to show Distinct (unique) values inside your original Pivot table.

For example you could have data set with OrderNumber, OrderDate, OrderItem, orderQty

First pivot table will show you OrderDate and sum of OrderQty and you probably want to see Count of unique orders in the same Pivot. You woudln't be able to do so within standard pivot table

If you want to do it, you would need Office 2016 (or perhaps pover Pivot might work). In office 2016 select your data > Insert > Pivot Table > choose tick "Add this data to the Data Model"

After that, you would be able to select grouping method as Distinct (Count)

How do I trim whitespace from a string?

I could not find a solution to what I was looking for so I created some custom functions. You can try them out.

def cleansed(s: str):
    """:param s: String to be cleansed"""
    assert s is not (None or "")
    # return trimmed(s.replace('"', '').replace("'", ""))
    return trimmed(s)


def trimmed(s: str):
    """:param s: String to be cleansed"""
    assert s is not (None or "")
    ss = trim_start_and_end(s).replace('  ', ' ')
    while '  ' in ss:
        ss = ss.replace('  ', ' ')
    return ss


def trim_start_and_end(s: str):
    """:param s: String to be cleansed"""
    assert s is not (None or "")
    return trim_start(trim_end(s))


def trim_start(s: str):
    """:param s: String to be cleansed"""
    assert s is not (None or "")
    chars = []
    for c in s:
        if c is not ' ' or len(chars) > 0:
            chars.append(c)
    return "".join(chars).lower()


def trim_end(s: str):
    """:param s: String to be cleansed"""
    assert s is not (None or "")
    chars = []
    for c in reversed(s):
        if c is not ' ' or len(chars) > 0:
            chars.append(c)
    return "".join(reversed(chars)).lower()


s1 = '  b Beer '
s2 = 'Beer  b    '
s3 = '      Beer  b    '
s4 = '  bread butter    Beer  b    '

cdd = trim_start(s1)
cddd = trim_end(s2)
clean1 = cleansed(s3)
clean2 = cleansed(s4)

print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s1, len(s1), cdd, len(cdd)))
print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s2, len(s2), cddd, len(cddd)))
print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s3, len(s3), clean1, len(clean1)))
print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s4, len(s4), clean2, len(clean2)))

Execute a terminal command from a Cocoa app

in the spirit of sharing... this is a method I use frequently to run shell scripts. you can add a script to your product bundle (in the copy phase of the build) and then have the script be read and run at runtime. note: this code looks for the script in the privateFrameworks sub-path. warning: this could be a security risk for deployed products, but for our in-house development it is an easy way to customize simple things (like which host to rsync to...) without re-compiling the application, but just editing the shell script in the bundle.

//------------------------------------------------------
-(void) runScript:(NSString*)scriptName
{
    NSTask *task;
    task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/sh"];

    NSArray *arguments;
    NSString* newpath = [NSString stringWithFormat:@"%@/%@",[[NSBundle mainBundle] privateFrameworksPath], scriptName];
    NSLog(@"shell script path: %@",newpath);
    arguments = [NSArray arrayWithObjects:newpath, nil];
    [task setArguments: arguments];

    NSPipe *pipe;
    pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];

    NSFileHandle *file;
    file = [pipe fileHandleForReading];

    [task launch];

    NSData *data;
    data = [file readDataToEndOfFile];

    NSString *string;
    string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    NSLog (@"script returned:\n%@", string);    
}
//------------------------------------------------------

Edit: Included fix for NSLog problem

If you are using NSTask to run a command-line utility via bash, then you need to include this magic line to keep NSLog working:

//The magic line that keeps your log where it belongs
[task setStandardInput:[NSPipe pipe]];

In context:

NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
//The magic line that keeps your log where it belongs
[task setStandardInput:[NSPipe pipe]];

An explanation is here: http://www.cocoadev.com/index.pl?NSTask

Replace non ASCII character from string

Or you can use the function below for removing non-ascii character from the string. You will get know internal working.

private static String removeNonASCIIChar(String str) {
    StringBuffer buff = new StringBuffer();
    char chars[] = str.toCharArray();

    for (int i = 0; i < chars.length; i++) {
        if (0 < chars[i] && chars[i] < 127) {
            buff.append(chars[i]);
        }
    }
    return buff.toString();
}

Why can't non-default arguments follow default arguments?

SyntaxError: non-default argument follows default argument

If you were to allow this, the default arguments would be rendered useless because you would never be able to use their default values, since the non-default arguments come after.

In Python 3 however, you may do the following:

def fun1(a="who is you", b="True", *, x, y):
    pass

which makes x and y keyword only so you can do this:

fun1(x=2, y=2)

This works because there is no longer any ambiguity. Note you still can't do fun1(2, 2) (that would set the default arguments).

How do I concatenate const/literal strings in C?

int main()
{
    char input[100];
    gets(input);

    char str[101];
    strcpy(str, " ");
    strcat(str, input);

    char *p = str;

    while(*p) {
       if(*p == ' ' && isalpha(*(p+1)) != 0)
           printf("%c",*(p+1));
       p++;
    }

    return 0;
}

What's wrong with using == to compare floats in Java?

First of all, are they float or Float? If one of them is a Float, you should use the equals() method. Also, probably best to use the static Float.compare method.

Why can't decimal numbers be represented exactly in binary?

The root (mathematical) reason is that when you are dealing with integers, they are countably infinite.

Which means, even though there are an infinite amount of them, we could "count out" all of the items in the sequence, without skipping any. That means if we want to get the item in the 610000000000000th position in the list, we can figure it out via a formula.

However, real numbers are uncountably infinite. You can't say "give me the real number at position 610000000000000" and get back an answer. The reason is because, even between 0 and 1, there are an infinite number of values, when you are considering floating-point values. The same holds true for any two floating point numbers.

More info:

http://en.wikipedia.org/wiki/Countable_set

http://en.wikipedia.org/wiki/Uncountable_set

Update: My apologies, I appear to have misinterpreted the question. My response is about why we cannot represent every real value, I hadn't realized that floating point was automatically classified as rational.

How to turn off magic quotes on shared hosting?

  1. Does it work if you remove the AddType line? I'm not quite sure why that's relevant to turning magic quotes off.

  2. If PHP isn't running under mod_php, htaccess won't work. Does it work as a CGI?

This is one for your hosting company really.

What is the difference between '@' and '=' in directive scope in AngularJS?

Why do I have to use "{{title}}" with '@' and "title" with '='?

@ binds a local/directive scope property to the evaluated value of the DOM attribute. If you use title=title1 or title="title1", the value of DOM attribute "title" is simply the string title1. If you use title="{{title}}", the value of the DOM attribute "title" is the interpolated value of {{title}}, hence the string will be whatever parent scope property "title" is currently set to. Since attribute values are always strings, you will always end up with a string value for this property in the directive's scope when using @.

= binds a local/directive scope property to a parent scope property. So with =, you use the parent model/scope property name as the value of the DOM attribute. You can't use {{}}s with =.

With @, you can do things like title="{{title}} and then some" -- {{title}} is interpolated, then the string "and them some" is concatenated with it. The final concatenated string is what the local/directive scope property gets. (You can't do this with =, only @.)

With @, you will need to use attr.$observe('title', function(value) { ... }) if you need to use the value in your link(ing) function. E.g., if(scope.title == "...") won't work like you expect. Note that this means you can only access this attribute asynchronously. You don't need to use $observe() if you are only using the value in a template. E.g., template: '<div>{{title}}</div>'.

With =, you don't need to use $observe.

Can I also access the parent scope directly, without decorating my element with an attribute?

Yes, but only if you don't use an isolate scope. Remove this line from your directive

scope: { ... }

and then your directive will not create a new scope. It will use the parent scope. You can then access all of the parent scope properties directly.

The documentation says "Often it's desirable to pass data from the isolated scope via an expression and to the parent scope", but that seems to work fine with bidirectional binding too. Why would the expression route be better?

Yes, bidirectional binding allows the local/directive scope and the parent scope to share data. "Expression binding" allows the directive to call an expression (or function) defined by a DOM attribute -- and you can also pass data as arguments to the expression or function. So, if you don't need to share data with the parent -- you just want to call a function defined in the parent scope -- you can use the & syntax.

See also

How to add number of days to today's date?

Date.prototype.addDays = function(days)
{
    var dat = new Date(this.valueOf() + days * 24 * 60 * 60 * 1000 );
    return dat;
}

React-router urls don't work when refreshing or writing manually

We used express' 404 handling approach

// path to the static react build directory    
const frontend = path.join(__dirname, 'react-app/build');

// map the requests to the static react build directory
app.use('/', express.static(frontend));

// all the unknown requests are redirected to the react SPA
app.use(function (req, res, next) {
    res.sendFile(path.join(frontend, 'index.html'));
});

Works like a charm. A live demo is our site

PHP session lost after redirect

When i use relative path "dir/file.php" with in the header() function in works for me. I think that the session is not saved for some reason when you redirect using the full url...

//Does retain the session info for some reason
header("Location: dir");

//Does not retain the session for some reason
header("Location: https://mywebz.com/dir")

How to properly upgrade node using nvm

This may work:

nvm install NEW_VERSION --reinstall-packages-from=OLD_VERSION

For example:

nvm install 6.7 --reinstall-packages-from=6.4

then, if you want, you can delete your previous version with:

nvm uninstall OLD_VERSION

Where, in your case, NEW_VERSION = 5.4 OLD_VERSION = 5.0

Alternatively, try:

nvm install stable --reinstall-packages-from=current

jQuery if statement to check visibility

You can use .is(':visible') to test if something is visible and .is(':hidden') to test for the opposite:

$('#offers').toggle(!$('#column-left form').is(':visible')); // or:
$('#offers').toggle($('#column-left form').is(':hidden'));

Reference:

How to get the previous page URL using JavaScript?

You can use the following to get the previous URL.

var oldURL = document.referrer;
alert(oldURL);

Equal sized table cells to fill the entire width of the containing table

Just use percentage widths and fixed table layout:

<table>
<tr>
  <td>1</td>
  <td>2</td>
  <td>3</td>
</tr>
</table>

with

table { table-layout: fixed; }
td { width: 33%; }

Fixed table layout is important as otherwise the browser will adjust the widths as it sees fit if the contents don't fit ie the widths are otherwise a suggestion not a rule without fixed table layout.

Obviously, adjust the CSS to fit your circumstances, which usually means applying the styling only to a tables with a given class or possibly with a given ID.

How To limit the number of characters in JTextField?

I have solved this problem by using the following code segment:

private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {
    boolean max = jTextField1.getText().length() > 4;
    if ( max ){
        evt.consume();
    }        
}

How to create a new img tag with JQuery, with the src and id from a JavaScript object?

You save some bytes by avoiding the .attr altogether by passing the properties to the jQuery constructor:

var img = $('<img />',
             { id: 'Myid',
               src: 'MySrc.gif', 
               width: 300
             })
              .appendTo($('#YourDiv'));

How to get a unique computer identifier in Java (like disk ID or motherboard ID)?

Not Knowing all of your requirements. For example, are you trying to uniquely identify a computer from all of the computers in the world, or are you just trying to uniquely identify a computer from a set of users of your application. Also, can you create files on the system?

If you are able to create a file. You could create a file and use the creation time of the file as your unique id. If you create it in user space then it would uniquely identify a user of your application on a particular machine. If you created it somewhere global then it could uniquely identify the machine.

Again, as most things, How fast is fast enough.. or in this case, how unique is unique enough.

When do you use map vs flatMap in RxJava?

In that scenario use map, you don't need a new Observable for it.

you should use Exceptions.propagate, which is a wrapper so you can send those checked exceptions to the rx mechanism

Observable<String> obs = Observable.from(jsonFile).map(new Func1<File, String>() { 
    @Override public String call(File file) {
        try { 
            return new Gson().toJson(new FileReader(file), Object.class);
        } catch (FileNotFoundException e) {
            throw Exceptions.propagate(t); /will propagate it as error
        } 
    } 
});

You then should handle this error in the subscriber

obs.subscribe(new Subscriber<String>() {
    @Override 
    public void onNext(String s) { //valid result }

    @Override 
    public void onCompleted() { } 

    @Override 
    public void onError(Throwable e) { //e might be the FileNotFoundException you got }
};); 

There is an excellent post for it: http://blog.danlew.net/2015/12/08/error-handling-in-rxjava/

How to access parent Iframe from JavaScript

Simply call window.frameElement from your framed page. If the page is not in a frame then frameElement will be null.

The other way (getting the window element inside a frame is less trivial) but for sake of completeness:

/**
 * @param f, iframe or frame element
 * @return Window object inside the given frame
 * @effect will append f to document.body if f not yet part of the DOM
 * @see Window.frameElement
 * @usage myFrame.document = getFramedWindow(myFrame).document;
 */
function getFramedWindow(f)
{
    if(f.parentNode == null)
        f = document.body.appendChild(f);
    var w = (f.contentWindow || f.contentDocument);
    if(w && w.nodeType && w.nodeType==9)
        w = (w.defaultView || w.parentWindow);
    return w;
}

Are list-comprehensions and functional functions faster than "for loops"?

If you check the info on python.org, you can see this summary:

Version Time (seconds)
Basic loop 3.47
Eliminate dots 2.45
Local variable & no dots 1.79
Using map function 0.54

But you really should read the above article in details to understand the cause of the performance difference.

I also strongly suggest you should time your code by using timeit. At the end of the day, there can be a situation where, for example, you may need to break out of for loop when a condition is met. It could potentially be faster than finding out the result by calling map.

Method call if not null in C#

From C# 6 onwards, you can just use:

MyEvent?.Invoke();

or:

obj?.SomeMethod();

The ?. is the null-propagating operator, and will cause the .Invoke() to be short-circuited when the operand is null. The operand is only accessed once, so there is no risk of the "value changes between check and invoke" problem.

===

Prior to C# 6, no: there is no null-safe magic, with one exception; extension methods - for example:

public static void SafeInvoke(this Action action) {
    if(action != null) action();
}

now this is valid:

Action act = null;
act.SafeInvoke(); // does nothing
act = delegate {Console.WriteLine("hi");}
act.SafeInvoke(); // writes "hi"

In the case of events, this has the advantage of also removing the race-condition, i.e. you don't need a temporary variable. So normally you'd need:

var handler = SomeEvent;
if(handler != null) handler(this, EventArgs.Empty);

but with:

public static void SafeInvoke(this EventHandler handler, object sender) {
    if(handler != null) handler(sender, EventArgs.Empty);
}

we can use simply:

SomeEvent.SafeInvoke(this); // no race condition, no null risk

How to select the last record from MySQL table using SQL syntax

User order by with desc order:

select * from t
order by id desc
limit 1

XPath to get all child nodes (elements, comments, and text) without parent

Use this XPath expression:

/*/*/X/node()

This selects any node (element, text node, comment or processing instruction) that is a child of any X element that is a grand-child of the top element of the XML document.

To verify what is selected, here is this XSLT transformation that outputs exactly the selected nodes:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>
 <xsl:template match="/">
  <xsl:copy-of select="/*/*/X/node()"/>
 </xsl:template>
</xsl:stylesheet>

and it produces exactly the wanted, correct result:

   First Text Node #1            
    <y> Y can Have Child Nodes #                
        <child> deep to it </child>
    </y>            Second Text Node #2 
    <z />

Explanation:

  1. As defined in the W3 XPath 1.0 Spec, "child::node() selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.

  2. node() is an abbreviation of child::node() (because child:: is the primary axis and is used when no axis is explicitly specified).

Run a PostgreSQL .sql file using command line arguments

Via the terminal log on to your database and try this:

database-# >@pathof_mysqlfile.sql

or

database-#>-i pathof_mysqlfile.sql

or

database-#>-c pathof_mysqlfile.sql

In Android EditText, how to force writing uppercase?

I'm using Visual Studio 2015/Xamarin to build my app for both Android 5.1 and Android 6.0 (same apk installed on both).

When I specified android:inputType="textCapCharacters" in my axml, the AllCaps keyboard appeared as expected on Android 6.0, but not Android 5.1. I added android:textAllCaps="true" to my axml and still no AllCaps keyboard on Android 5.1. I set a filter using EditText.SetFilters(new IInputFilter[] { new InputFilterAllCaps() }); and while the soft keyboard shows lower case characters on Android 5.1, the input field is now AllCaps.

EDIT: The behavioral differences that I observed and assumed to be OS-related were actually because I had different versions of Google Keyboard on the test devices. Once I updated the devices to the latest Google Keyboard (released July 2016 as of this writing), the 'All Caps' behavior was consistent across OSes. Now, all devices show lower-case characters on the keyboard, but the input is All Caps because of SetFilters(new IInputFilter[] { new InputFilterAllCaps() });

Implementing INotifyPropertyChanged - does a better way exist?

Whilst there are obviously lots of ways to do this, with the exception of the AOP magic answers, none of the answers seem to look at setting a Model's property directly from the view model without having a local field to reference.

The issue is you can't reference a property. However, you can use an Action to set that property.

protected bool TrySetProperty<T>(Action<T> property, T newValue, T oldValue, [CallerMemberName] string propertyName = null)
{
    if (EqualityComparer<T>.Default.Equals(oldValue, newValue))
    {
        return false;
    }

    property(newValue);
    RaisePropertyChanged(propertyName);
    return true;
}

This can be used like the following code extract.

public int Prop {
    get => model.Prop;
    set => TrySetProperty(x => model.Prop = x, value, model.Prop);
}

Check out this BitBucket repo for a full implementation of the method and a few different ways of achieving the same result, including a method that uses LINQ and a method that uses reflection. Do note that these methods are slower performance wise.

How to specify a port number in SQL Server connection string?

Use a comma to specify a port number with SQL Server:

mycomputer.test.xxx.com,1234

It's not necessary to specify an instance name when specifying the port.

Lots more examples at http://www.connectionstrings.com/. It's saved me a few times.

log4j logging hierarchy order

This table might be helpful for you:

Log Level

Going down the first column, you will see how the log works in each level. i.e for WARN, (FATAL, ERROR and WARN) will be visible. For OFF, nothing will be visible.

How to edit binary file on Unix systems

Bless is a high quality, full featured hex editor.

It is written in mono/Gtk# and its primary platform is GNU/Linux. However it should be able to run without problems on every platform that mono and Gtk# run. Main Features Bless currently provides the following features:

  • Efficient editing of large data files and block devices.
  • Multilevel undo - redo operations.
  • Customizable data views.
  • Fast data rendering on screen.
  • Multiple tabs.
  • Fast find and replace operations.
  • A data conversion table.
  • Advanced copy/paste capabilities.
  • Highlighting of selection pattern matches in the file.
  • Plugin based architecture.
  • Export of data to text and html (others with plugins).
  • Bitwise operations on data.
  • A comprehensive user manual.

copied from http://home.gna.org/bless/

How to center and crop an image to always appear in square shape with CSS?

<div>
    <img class="crop" src="http://lorempixel.com/500/200"/>
</div>

<img src="http://lorempixel.com/500/200"/>




div {
    width: 200px;
    height: 200px;
    overflow: hidden;
    margin: 10px;
    position: relative;
}
.crop {
    position: absolute;
    left: -100%;
    right: -100%;
    top: -100%;
    bottom: -100%;
    margin: auto; 
    height: auto;
    width: auto;
}

http://jsfiddle.net/J7a5R/56/

Include PHP inside JavaScript (.js) files

You can't include server side PHP in your client side javascript, you will have to port it over to javascript. If you wish, you can use php.js, which ports all PHP functions over to javascript. You can also create a new php file that returns the results of calling your PHP function, and then call that file using AJAX to get the results.

Export DataTable to Excel with Open Xml SDK in c#

I also wrote a C#/VB.Net "Export to Excel" library, which uses OpenXML and (more importantly) also uses OpenXmlWriter, so you won't run out of memory when writing large files.

Full source code, and a demo, can be downloaded here:

Export to Excel

It's dead easy to use. Just pass it the filename you want to write to, and a DataTable, DataSet or List<>.

CreateExcelFile.CreateExcelDocument(myDataSet, "MyFilename.xlsx");

And if you're calling it from an ASP.Net application, pass it the HttpResponse to write the file out to.

CreateExcelFile.CreateExcelDocument(myDataSet, "MyFilename.xlsx", Response);

python save image from url

import random
import urllib.request

def download_image(url):
    name = random.randrange(1,100)
    fullname = str(name)+".jpg"
    urllib.request.urlretrieve(url,fullname)     
download_image("http://site.meishij.net/r/58/25/3568808/a3568808_142682562777944.jpg")

How can I modify the size of column in a MySQL table?

Have you tried this?

ALTER TABLE <table_name> MODIFY <col_name> VARCHAR(65353);

This will change the col_name's type to VARCHAR(65353)

How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)?

The proper function is int fileno(FILE *stream). It can be found in <stdio.h>, and is a POSIX standard but not standard C.

HTML5 best practices; section/header/aside/article elements

Why not have the item_1, item_2, etc. IDs on the article tags themselves? Like this:

<article id="item_1">
...
</article>
<article id="item_2">
...
</article>
...

It seems unnecessary to add the wrapper divs. ID values have no semantic meaning in HTML, so I think it would be perfectly valid to do this - you're not saying that the first article is always item_1, just item_1 within the context of the current page. IDs are not required to have any meaning that is independent of context.

Also, as to your question on line 26, I don't think the <header> tag is required there, and I think you could omit it since it's on its own in the "main-left" div. If it were in the main list of articles you might want to include the <header> tag just for the sake of consistency.

Where is the .NET Framework 4.5 directory?

The official way to find out if you have 4.5 installed (and not 4.0) is in the registry keys :

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full

Relesae DWORD needs to be bigger than 378675 Here is the Microsoft doc for it

all the other answers of checking the minor version after 4.0.30319.xxxxx seem correct though (msbuild.exe -version , or properties of clr.dll), i just needed something documented (not a blog)

PHP function to build query string from array

As this question is quite old and for PHP, here is a way to do it in the (currently) very popular PHP framework Laravel.

To encode the query string for a path in your application, give your routes names and then use the route() helper function like so:

route('documents.list.', ['foo' => 'bar']);

The result will look something like:

http://localhost/documents/list?foo=bar

Also be aware that if your route has any path segment parameters e.g. /documents/{id}, then make sure you pass an id argument to the route() parameters too, otherwise it will default to using the value of the first parameter.

How can I wrap text in a label using WPF?

You can put a TextBlock inside the label:

<Label> 
  <TextBlock Text="Long Text . . . ." TextWrapping="Wrap" /> 
</Label> 

React prevent event bubbling in nested components on click

The new way to do this is a lot more simple and will save you some time! Just pass the event into the original click handler and call preventDefault();.

clickHandler(e){
    e.preventDefault();
    //Your functionality here
}

MySQL SELECT statement for the "length" of the field is greater than 1

How about:

SELECT * FROM sometable WHERE CHAR_LENGTH(LINK) > 1

Here's the MySql string functions page (5.0).

Note that I chose CHAR_LENGTH instead of LENGTH, as if there are multibyte characters in the data you're probably really interested in how many characters there are, not how many bytes of storage they take. So for the above, a row where LINK is a single two-byte character wouldn't be returned - whereas it would when using LENGTH.

Note that if LINK is NULL, the result of CHAR_LENGTH(LINK) will be NULL as well, so the row won't match.

How to trigger HTML button when you press Enter in textbox?

Based on some previous answers, I came up with this:

<form>
  <button id='but' type='submit'>do not click me</button>
  <input type='text' placeholder='press enter'>
</form>

$('#but').click(function(e) {
  alert('button press');
  e.preventDefault();
});

Take a look at the Fiddle

EDIT: If you dont want to add additional html elements, you can do this with JS only:

    $("input").keyup(function(event) {
        if (event.keyCode === 13) {
            $("button").click();
        }
    });     

How do I install Composer on a shared hosting?

SIMPLE SOLUTION (tested on Red Hat):

run command: curl -sS https://getcomposer.org/installer | php

to use it: php composer.phar

SYSTEM WIDE SOLLUTION (tested on Red Hat):

run command: mv composer.phar /usr/local/bin/composer

to use it: composer update

now you can call composer from any directory.

Source: http://www.agix.com.au/install-composer-on-centosredhat/

Validate phone number using angular js

You can also use ng-pattern ,[7-9] = > mobile number must start with 7 or 8 or 9 ,[0-9] = mobile number accepts digits ,{9} mobile number should be 10 digits.

_x000D_
_x000D_
function form($scope){_x000D_
    $scope.onSubmit = function(){_x000D_
        alert("form submitted");_x000D_
    }_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>_x000D_
<div ng-app ng-controller="form">_x000D_
<form name="myForm" ng-submit="onSubmit()">_x000D_
    <input type="number" ng-model="mobile_number" name="mobile_number" ng-pattern="/^[7-9][0-9]{9}$/" required>_x000D_
    <span ng-show="myForm.mobile_number.$error.pattern">Please enter valid number!</span>_x000D_
    <input type="submit" value="submit"/>_x000D_
</form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Sum all values in every column of a data.frame in R

mapply(sum,people[,-1])

Height Weight 
   199    425 

CentOS: Copy directory to another directory

To copy all files, including hidden files use:

cp -r /home/server/folder/test/. /home/server/

Converting HTML files to PDF

Check out iText; it is a pure Java PDF toolkit which has support for reading data from HTML. I used it recently in a project when I needed to pull content from our CMS and export as PDF files, and it was all rather straightforward. The support for CSS and style tags is pretty limited, but it does render tables without any problems (I never managed to set column width though).

Creating a PDF from HTML goes something like this:

Document doc = new Document(PageSize.A4);
PdfWriter.getInstance(doc, out);
doc.open();
HTMLWorker hw = new HTMLWorker(doc);
hw.parse(new StringReader(html));
doc.close();