Programs & Examples On #Icomparer

IComparer is an interface provided by the .NET framework, used in conjunction with the Array.Sort and Array.BinarySearch methods. It provides a way to customize the sort order of a collection. It contains a single Compare method that compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other. There is also a generic version of this interface. Supported in .NET 4, 3.5, 3.0, 2.0, 1.1, 1.0. Source: MSDN

C# Sort and OrderBy comparison

I just want to add that orderby is way more useful.

Why? Because I can do this:

Dim thisAccountBalances = account.DictOfBalances.Values.ToList
thisAccountBalances.ForEach(Sub(x) x.computeBalanceOtherFactors())
thisAccountBalances=thisAccountBalances.OrderBy(Function(x) x.TotalBalance).tolist
listOfBalances.AddRange(thisAccountBalances)

Why complicated comparer? Just sort based on a field. Here I am sorting based on TotalBalance.

Very easy.

I can't do that with sort. I wonder why. Do fine with orderBy.

As for speed it's always O(n).

How to select min and max values of a column in a datatable?

Easiar approach on datatable could be:

int minLavel = Convert.ToInt32(dt.Compute("min([AccountLevel])", string.Empty));

add/remove active class for ul list with jquery?

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $('.cliked').click(function() {_x000D_
        $(".cliked").removeClass("liactive");_x000D_
        $(this).addClass("liactive");_x000D_
    });_x000D_
});
_x000D_
.liactive {_x000D_
    background: orange;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul_x000D_
  className="sidebar-nav position-fixed "_x000D_
  style="height:450px;overflow:scroll"_x000D_
>_x000D_
    <li>_x000D_
        <a className="cliked liactive" href="#">_x000D_
            check Kyc Status_x000D_
        </a>_x000D_
    </li>_x000D_
    <li>_x000D_
        <a className="cliked" href="#">_x000D_
            My Investments_x000D_
        </a>_x000D_
    </li>_x000D_
    <li>_x000D_
        <a className="cliked" href="#">_x000D_
            My SIP_x000D_
        </a>_x000D_
    </li>_x000D_
    <li>_x000D_
        <a className="cliked" href="#">_x000D_
            My Tax Savers Fund_x000D_
        </a>_x000D_
    </li>_x000D_
    <li>_x000D_
        <a className="cliked" href="#">_x000D_
            Transaction History_x000D_
        </a>_x000D_
    </li>_x000D_
    <li>_x000D_
        <a className="cliked" href="#">_x000D_
            Invest Now_x000D_
        </a>_x000D_
    </li>_x000D_
    <li>_x000D_
        <a className="cliked" href="#">_x000D_
            My Profile_x000D_
        </a>_x000D_
    </li>_x000D_
    <li>_x000D_
        <a className="cliked" href="#">_x000D_
            FAQ`s_x000D_
        </a>_x000D_
    </li>_x000D_
    <li>_x000D_
        <a className="cliked" href="#">_x000D_
            Suggestion Portfolio_x000D_
        </a>_x000D_
    </li>_x000D_
    <li>_x000D_
        <a className="cliked" href="#">_x000D_
            Bluk Lumpsum / Bulk SIP_x000D_
        </a>_x000D_
    </li>_x000D_
</ul>;
_x000D_
_x000D_
_x000D_

Git: force user and password prompt

Add a -v flag with your git command . e.g. git pull -v

v stands for verify .

JavaScript - cannot set property of undefined

In javascript almost everything is an object, null and undefined are exception.

Instances of Array is an object. so you can set property of an array, for the same reason,you can't set property of a undefined, because its NOT an object

Best way to randomize an array with .NET

        int[] numbers = {0,1,2,3,4,5,6,7,8,9};
        List<int> numList = new List<int>();
        numList.AddRange(numbers);

        Console.WriteLine("Original Order");
        for (int i = 0; i < numList.Count; i++)
        {
            Console.Write(String.Format("{0} ",numList[i]));
        }

        Random random = new Random();
        Console.WriteLine("\n\nRandom Order");
        for (int i = 0; i < numList.Capacity; i++)
        {
            int randomIndex = random.Next(numList.Count);
            Console.Write(String.Format("{0} ", numList[randomIndex]));
            numList.RemoveAt(randomIndex);
        }
        Console.ReadLine();

CS0234: Mvc does not exist in the System.Web namespace

Check your runtime tag inside the web.config, and verify you have something like this declared:

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
.....
</runtime>

sizing div based on window width

Viewport units for CSS

1vw = 1% of viewport width
1vh = 1% of viewport height

This way, you don't have to write many different media queries or javascript.

If you prefer JS

window.innerWidth;
window.innerHeight;

CSS hover vs. JavaScript mouseover

There is another difference to keep in mind between the two. With CSS, the :hover state is always deactivated when the mouse moves off an element. However, with JavaScript, the onmouseout event is not fired when the mouse moves off the element onto browser chrome rather than onto the rest of the page.

This happens more often than you might think, especially when you're making a navbar at the top of your page with custom hover states.

Responsive css styles on mobile devices ONLY

I had to solve a similar problem--I wanted certain styles to only apply to mobile devices in landscape mode. Essentially the fonts and line spacing looked fine in every other context, so I just needed the one exception for mobile landscape. This media query worked perfectly:

@media all and (max-width: 600px) and (orientation:landscape) 
{
    /* styles here */
}

Do I need a content-type header for HTTP GET requests?

Get requests should not have content-type because they do not have request entity (that is, a body)

How to navigate through textfields (Next / Done Buttons)

Here's one without delegation:

tf1.addTarget(tf2, action: #selector(becomeFirstResponder), for: .editingDidEndOnExit)
tf2.addTarget(tf3, action: #selector(becomeFirstResponder), for: .editingDidEndOnExit)

ObjC:

[tf1 addTarget:tf2 action:@selector(becomeFirstResponder) forControlEvents:UIControlEventEditingDidEndOnExit];
[tf2 addTarget:tf3 action:@selector(becomeFirstResponder) forControlEvents:UIControlEventEditingDidEndOnExit];

Works using the (mostly unknown) UIControlEventEditingDidEndOnExit UITextField action.

You can also easily hook this up in the storyboard, so no delegation or code is required.

Edit: actually I cannot figure out how to hook this up in storyboard. becomeFirstResponder does not seem to be a offered action for this control-event, which is a pity. Still, you can hook all your textfields up to a single action in your ViewController which then determines which textField to becomeFirstResponder based on the sender (though then it is not as elegant as the above programmatic solution so IMO do it with the above code in viewDidLoad).

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

JAX-WS client : what's the correct path to access the local WSDL?

Thanks a ton for Bhaskar Karambelkar's answer which explains in detail and fixed my issue. But also I would like to re phrase the answer in three simple steps for someone who is in a hurry to fix

  1. Make your wsdl local location reference as wsdlLocation= "http://localhost/wsdl/yourwsdlname.wsdl"
  2. Create a META-INF folder right under the src. Put your wsdl file/s in a folder under META-INF, say META-INF/wsdl
  3. Create an xml file jax-ws-catalog.xml under META-INF as below

    <catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog" prefer="system"> <system systemId="http://localhost/wsdl/yourwsdlname.wsdl" uri="wsdl/yourwsdlname.wsdl" /> </catalog>

Now package your jar. No more reference to the local directory, it's all packaged and referenced within

importing jar libraries into android-studio

This is the way I just did on Android Studio version 1.0.2

  • I have created a folder libs in [your project dir]\app\src
  • I have copied the jtwitter.jar (or the yambaclientlib.jar) into the [your project dir]\app\src\libs directory
  • The following the menu path: File -> Project Structure -> Dependencies -> Add -> File Dependency, Android Studio opens a dialog box where you can drag&drop the jar library. Then I clicked the OK button.

At this point Gradle will rebuild the project importing the library and resolving the dependencies.

IF EXISTS before INSERT, UPDATE, DELETE for optimization

Yes this will affect performance (the degree to which performance will be affected will be affected by a number of factors). Effectively you are doing the same query "twice" (in your example). Ask yourself whether or not you need to be this defensive in your query and in what situations would the row not be there? Also, with an update statement the rows affected is probably a better way to determine if anything has been updated.

Python int to binary string?

Python 3.6 added a new string formatting approach called formatted string literals or “f-strings”. Example:

name = 'Bob'
number = 42
f"Hello, {name}, your number is {number:>08b}"

Output will be 'Hello, Bob, your number is 00001010!'

A discussion of this question can be found here - Here

How to join multiple lines of file names into one with custom delimiter?

ls has the option -m to delimit the output with ", " a comma and a space.

ls -m | tr -d ' ' | tr ',' ';'

piping this result to tr to remove either the space or the comma will allow you to pipe the result again to tr to replace the delimiter.

in my example i replace the delimiter , with the delimiter ;

replace ; with whatever one character delimiter you prefer since tr only accounts for the first character in the strings you pass in as arguments.

How do I get a substring of a string in Python?

A common way to achieve this is by string slicing.

MyString[a:b] gives you a substring from index a to (b - 1).

Java SecurityException: signer information does not match

this happened to me when using JUnit + rest assured + hamcrest, in this case, dont add junit to build path, if you have the maven project, this resolved me, below is the pom.xml

<dependencies>

    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>3.0.0</version>
    </dependency>

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-all</artifactId>
        <version>1.3</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>

    </dependency>


</dependencies>

How to call a .NET Webservice from Android using KSOAP2?

Typecast the envelope to SoapPrimitive:

SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
String strRes = result.toString();

and it will work.

How to view Plugin Manager in Notepad++

It can be installed with one command for N++ installer version:

choco install notepadplusplus-nppPluginManager

Eclipse Generate Javadoc Wizard: what is "Javadoc Command"?

Yes, it is asking for the application/executable that is capable of creating Javadoc. There is a javadoc executable inside the jdk's bin folder.

How to download the latest artifact from Artifactory repository?

You could also use Artifactory Query Language to get the latest artifact.

The following shell script is just an example. It uses 'items.find()' (which is available in the non-Pro version), e.g. items.find({ "repo": {"$eq":"my-repo"}, "name": {"$match" : "my-file*"}}) that searches for files that have a repository name equal to "my-repo" and match all files that start with "my-file". Then it uses the shell JSON parser ./jq to extract the latest file by sorting by the date field 'updated'. Finally it uses wget to download the artifact.

#!/bin/bash

# Artifactory settings
host="127.0.0.1"
username="downloader"
password="my-artifactory-token"

# Use Artifactory Query Language to get the latest scraper script (https://www.jfrog.com/confluence/display/RTF/Artifactory+Query+Language)
resultAsJson=$(curl -u$username:"$password" -X POST  http://$host/artifactory/api/search/aql -H "content-type: text/plain" -d 'items.find({ "repo": {"$eq":"my-repo"}, "name": {"$match" : "my-file*"}})')

# Use ./jq to pars JSON
latestFile=$(echo $resultAsJson | jq -r '.results | sort_by(.updated) [-1].name')

# Download the latest scraper script
wget -N -P ./libs/ --user $username --password $password http://$host/artifactory/my-repo/$latestFile

What is the simplest way to SSH using Python?

Have a look at spurplus, a wrapper around spur and paramiko that we developed to manage remote machines and perform file operations.

Spurplus provides a check_output() function out-of-the-box:

import spurplus
with spurplus.connect_with_retries(
        hostname='some-machine.example.com', username='devop') as shell:
     out = shell.check_output(['/path/to/the/command', '--some_argument']) 
     print(out)

How to iterate object keys using *ngFor

You have to create custom pipe.

import { Injectable, Pipe } from '@angular/core';
@Pipe({
   name: 'keyobject'
})
@Injectable()
export class Keyobject {

transform(value, args:string[]):any {
    let keys = [];
    for (let key in value) {
        keys.push({key: key, value: value[key]});
    }
    return keys;
}}

And then use it in your *ngFor

*ngFor="let item of data | keyobject"

:last-child not working as expected?

I encounter similar situation. I would like to have background of the last .item to be yellow in the elements that look like...

<div class="container">
  <div class="item">item 1</div>
  <div class="item">item 2</div>
  <div class="item">item 3</div>
  ...
  <div class="item">item x</div>
  <div class="other">I'm here for some reasons</div>
</div>

I use nth-last-child(2) to achieve it.

.item:nth-last-child(2) {
  background-color: yellow;
}

It strange to me because nth-last-child of item suppose to be the second of the last item but it works and I got the result as I expect. I found this helpful trick from CSS Trick

C#: Looping through lines of multiline string

I know this has been answered, but I'd like to add my own answer:

using (var reader = new StringReader(multiLineString))
{
    for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
    {
        // Do something with the line
    }
}

Multi-dimensional associative arrays in JavaScript

Get the value for an array of associative arrays's property when the property name is an integer:

Starting with an Associative Array where the property names are integers:

var categories = [
    {"1":"Category 1"},
    {"2":"Category 2"},
    {"3":"Category 3"},
    {"4":"Category 4"}
];

Push items to the array:

categories.push({"2300": "Category 2300"});
categories.push({"2301": "Category 2301"});

Loop through array and do something with the property value.

for (var i = 0; i < categories.length; i++) {
    for (var categoryid in categories[i]) {
        var category = categories[i][categoryid];
        // log progress to the console
        console.log(categoryid + " : " + category);
        //  ... do something
    }
}

Console output should look like this:

1 : Category 1
2 : Category 2
3 : Category 3
4 : Category 4
2300 : Category 2300
2301 : Category 2301

As you can see, you can get around the associative array limitation and have a property name be an integer.

NOTE: The associative array in my example is the json you would have if you serialized a Dictionary[] object.

Changing default shell in Linux

You can change the passwd file directly for the particular user or use the below command

chsh -s /usr/local/bin/bash username

Then log out and log in

Install NuGet via PowerShell script

None of the above solutions worked for me, I found an article that explained the issue. The security protocols on the system were deprecated and therefore displayed an error message that no match was found for the ProviderPackage.

Here is a the basic steps for upgrading your security protocols:

Run both cmdlets to set .NET Framework strong cryptography registry keys. After that, restart PowerShell and check if the security protocol TLS 1.2 is added. As of last, install the PowerShellGet module.

The first cmdlet is to set strong cryptography on 64 bit .Net Framework (version 4 and above).

[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
1
[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
The second cmdlet is to set strong cryptography on 32 bit .Net Framework (version 4 and above).

[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
1
[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
Restart Powershell and check for supported security protocols.

[PS] C:\>[Net.ServicePointManager]::SecurityProtocol
Tls, Tls11, Tls12
1
2
[PS] C:\>[Net.ServicePointManager]::SecurityProtocol
Tls, Tls11, Tls12
Run the command Install-Module PowershellGet -Force and press Y to install NuGet provider, follow with Enter.

[PS] C:\>Install-Module PowershellGet -Force
 
NuGet provider is required to continue
PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories. The NuGet provider must be available in 'C:\Program Files\PackageManagement\ProviderAssemblies' or
'C:\Users\administrator.EXOIP\AppData\Local\PackageManagement\ProviderAssemblies'. You can also install the NuGet provider by running 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force'. Do you want PowerShellGet to install
and import the NuGet provider now?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): Y

[PS] C:\>Install-Module PowershellGet -Force
 
NuGet provider is required to continue
PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories. The NuGet provider must be available in 'C:\Program Files\PackageManagement\ProviderAssemblies' or
'C:\Users\administrator.EXOIP\AppData\Local\PackageManagement\ProviderAssemblies'. You can also install the NuGet provider by running 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force'. Do you want PowerShellGet to install
and import the NuGet provider now?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): Y

sprintf like functionality in Python

Two approaches are to write to a string buffer or to write lines to a list and join them later. I think the StringIO approach is more pythonic, but didn't work before Python 2.6.

from io import StringIO

with StringIO() as s:
   print("Hello", file=s)
   print("Goodbye", file=s)
   # And later...
   with open('myfile', 'w') as f:
       f.write(s.getvalue())

You can also use these without a ContextMananger (s = StringIO()). Currently, I'm using a context manager class with a print function. This fragment might be useful to be able to insert debugging or odd paging requirements:

class Report:
    ... usual init/enter/exit
    def print(self, *args, **kwargs):
        with StringIO() as s:
            print(*args, **kwargs, file=s)
            out = s.getvalue()
        ... stuff with out

with Report() as r:
   r.print(f"This is {datetime.date.today()}!", 'Yikes!', end=':')

How to change colour of blue highlight on select box dropdown

try this.. I know it's an old post but it might help somebody

select option:hover,
    select option:focus,
    select option:active {
        background: linear-gradient(#000000, #000000);
        background-color: #000000 !important; /* for IE */
        color: #ffed00 !important;
    }

    select option:checked {
        background: linear-gradient(#d6d6d6, #d6d6d6);
        background-color: #d6d6d6 !important; /* for IE */
        color: #000000 !important;
    }

How to add image in a TextView text?

I tried many different solutions and this for me was the best:

SpannableStringBuilder ssb = new SpannableStringBuilder(" Hello world!");
ssb.setSpan(new ImageSpan(context, R.drawable.image), 0, 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
tv_text.setText(ssb, TextView.BufferType.SPANNABLE);

This code uses a minimum of memory.

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

You can also retrieve it from the environment variables, but that is probably not secure, so I would go with Andrew's answer.

printenv USER

If you need to retrieve it from an app, like Node, it's easier to get it from the environment variables, such as

process.env.USER.

Define constant variables in C++ header

I like the namespace better for this kind of purpose.

Option 1 :

#ifndef MYLIB_CONSTANTS_H
#define MYLIB_CONSTANTS_H

//  File Name : LibConstants.hpp    Purpose : Global Constants for Lib Utils
namespace LibConstants
{
  const int CurlTimeOut = 0xFF;     // Just some example
  ...
}
#endif

// source.cpp
#include <LibConstants.hpp>
int value = LibConstants::CurlTimeOut;

Option 2 :

#ifndef MYLIB_CONSTANTS_H
#define MYLIB_CONSTANTS_H
//  File Name : LibConstants.hpp    Purpose : Global Constants for Lib Utils
namespace CurlConstants
{
  const int CurlTimeOut = 0xFF;     // Just some example
  ...
}

namespace MySQLConstants
{
  const int DBPoolSize = 0xFF;      // Just some example
  ...
}
#endif



// source.cpp
#include <LibConstants.hpp>
int value = CurlConstants::CurlTimeOut;
int val2  = MySQLConstants::DBPoolSize;

And I would never use a Class to hold this type of HardCoded Const variables.

pip broke. how to fix DistributionNotFound error?

In my case (sam problem, but other packages) there was no version dependency. A sequence of pip uninstall and pip insstall did help.

How to get to a particular element in a List in java?

The List interface supports random access via the get method - to get line 0, use list.get(0). You'll need to use array access on that, ie, lines.get(0)[0] is the first element of the first line.

See the javadoc here.

How to Lock/Unlock screen programmatically?

The androidmanifest.xml and policies.xml files on the sample page are invisible in my browser due to it trying to format the XML files as HTML. I'm only posting this for reference for the convenience of others, this is sourced from the sample page.

Thanks all for this helpful question!

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.kns"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".LockScreenActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".MyAdmin"
                android:permission="android.permission.BIND_DEVICE_ADMIN">
            <meta-data android:name="android.app.device_admin"
                       android:resource="@xml/policies" />
            <intent-filter>
                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
            </intent-filter>
        </receiver>

    </application>
</manifest>

policies.xml

<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <limit-password />
        <watch-login />
        <reset-password />
        <force-lock />
        <wipe-data />
    </uses-policies>
</device-admin>

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

it is because you already defined the 'abuse_id' as auto increment, then there is no need to insert its value. it will be inserted automatically. the error comes because you are inserting 1 many times that is duplication of data. the primary key should be unique. should not be repeated.

the thing you have to do is to change your insertion query as below

INSERT INTO  `abuses` (  `user_id` ,  `abuser_username` ,  `comment` ,  `reg_date` , `auction_id` ) 
VALUES ( 100020,  'artictundra', 'I placed a bid for it more than an hour ago. It is still active. I     thought I was supposed to get an email after 15 minutes.', 1338052850, 108625 ) ;

Increase JVM max heap size for Eclipse

It is possible to increase heap size allocated by the Java Virtual Machine (JVM) by using command line options.

-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size

If you are using the tomcat server, you can change the heap size by going to Eclipse/Run/Run Configuration and select Apache Tomcat/your_server_name/Arguments and under VM arguments section use the following:

-XX:MaxPermSize=256m
-Xms256m -Xmx512M

If you are not using any server, you can type the following on the command line before you run your code:

java -Xms64m -Xmx256m HelloWorld

More information on increasing the heap size can be found here

Error message "Forbidden You don't have permission to access / on this server"

I was getting the same error and couldn't figure out the problem for ages. If you happen to be on a Linux distribution that includes SELinux such as CentOS, you need to make sure SELinux permissions are set correctly for your document root files or you will get this error. This is a completely different set of permissions to the standard file system permissions.

I happened to use the tutorial Apache and SELinux, but there seems to be plenty around once you know what to look for.

iOS: present view controller programmatically

Try this code:

[self.navigationController presentViewController:controller animated:YES completion:nil];

UTF-8 problems while reading CSV file with fgetcsv

Encountered similar problem: parsing CSV file with special characters like é, è, ö etc ...

The following worked fine for me:

To represent the characters correctly on the html page, the header was needed :

header('Content-Type: text/html; charset=UTF-8');

In order to parse every character correctly, I used:

utf8_encode(fgets($file));

Dont forget to use in all following string operations the 'Multibyte String Functions', like:

mb_strtolower($value, 'UTF-8');

How to set the environmental variable LD_LIBRARY_PATH in linux

Put export LD_LIBRARY_PATH=/usr/local/lib in ~/.bashrc [preferably towards end of script to avoid any overrides in between, Default ~/.bashrc comes with many if-else statements]

Post that whenever you open a new terminal/konsole, LD_LIBRARY_PATH will be reflected

Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to

Go for stable version or gradle in app level gradle file in my case it was
classpath 'com.android.tools.build:gradle:2.2.0-alpha3'

I changed it with

classpath 'com.android.tools.build:gradle:2.1.2'

Implicit type conversion rules in C++ operators

In C++ operators (for POD types) always act on objects of the same type.
Thus if they are not the same one will be promoted to match the other.
The type of the result of the operation is the same as operands (after conversion).

If either is      long          double the other is promoted to      long          double
If either is                    double the other is promoted to                    double
If either is                    float  the other is promoted to                    float
If either is long long unsigned int    the other is promoted to long long unsigned int
If either is long long          int    the other is promoted to long long          int
If either is long      unsigned int    the other is promoted to long      unsigned int
If either is long               int    the other is promoted to long               int
If either is           unsigned int    the other is promoted to           unsigned int
If either is                    int    the other is promoted to                    int
Both operands are promoted to int

Note. The minimum size of operations is int. So short/char are promoted to int before the operation is done.

In all your expressions the int is promoted to a float before the operation is performed. The result of the operation is a float.

int + float =>  float + float = float
int * float =>  float * float = float
float * int =>  float * float = float
int / float =>  float / float = float
float / int =>  float / float = float
int / int                     = int
int ^ float =>  <compiler error>

Ruby: kind_of? vs. instance_of? vs. is_a?

It is more Ruby-like to ask objects whether they respond to a method you need or not, using respond_to?. This allows both minimal interface and implementation unaware programming.

It is not always applicable of course, thus there is still a possibility to ask about more conservative understanding of "type", which is class or a base class, using the methods you're asking about.

How to implement __iter__(self) for a container object (Python)

One option that might work for some cases is to make your custom class inherit from dict. This seems like a logical choice if it acts like a dict; maybe it should be a dict. This way, you get dict-like iteration for free.

class MyDict(dict):
    def __init__(self, custom_attribute):
        self.bar = custom_attribute

mydict = MyDict('Some name')
mydict['a'] = 1
mydict['b'] = 2

print mydict.bar
for k, v in mydict.items():
    print k, '=>', v

Output:

Some name
a => 1
b => 2

How do I REALLY reset the Visual Studio window layout?

Try devenv.exe /resetuserdata. I think it's more aggressive than the Tools > Import and Export options suggested.

Also check Tools > Add In Manager and make sure there aren't any orphans there.

How can I edit a .jar file?

Here's what I did:

  • Extracted the files using WinRAR
  • Made my changes to the extracted files
  • Opened the original JAR file with WinRAR
  • Used the ADD button to replace the files that I modified

That's it. I have tested it with my Nokia and it's working for me.

Facebook key hash does not match any stored key hashes

Follow these steps in order to generate the correct key hashes.

  1. Open your project in android studio and run the project.
  2. Click on Gradle menu.
  3. Select your app and expand task tree.
  4. Double click on android -> signingReport and see the magic Sample Image
  5. Result after clicking above tab Result after clicking above tab
  6. Copy the SHA1 key and browse SHA1 key to key hash
  7. After converting the SHA1 key to key hash copy the new key hash and paste it in facebook console. This will work like charm.

Browser detection

if (Request.Browser.Type.Contains("Firefox")) // replace with your check
{
    ...
} 
else if (Request.Browser.Type.ToUpper().Contains("IE")) // replace with your check
{
    if (Request.Browser.MajorVersion  < 7)
    { 
        DoSomething(); 
    }
    ...
}
else { }

Fetch API request timeout?

  fetchTimeout (url,options,timeout=3000) {
    return new Promise( (resolve, reject) => {
      fetch(url, options)
      .then(resolve,reject)
      setTimeout(reject,timeout);
    })
  }

How to use aria-expanded="true" to change a css property

If you were open to using JQuery, you could modify the background color for any link that has the property aria-expanded set to true by doing the following...

$("a[aria-expanded='true']").css("background-color", "#42DCA3");

Depending on how specific you want to be regarding which links this applies to, you may have to slightly modify your selector.

$('body').on('click', '.anything', function(){})

You can try this:

You must follow the following format

    $('element,id,class').on('click', function(){....});

*JQuery code*

    $('body').addClass('.anything').on('click', function(){
      //do some code here i.e
      alert("ok");
    });

What is an API key?

Think of it this way, the "Public API Key" is similar to a user name that your database is using as a login to a verification server. The "Private API Key" would then be similar to the password. By the site/databse using this method, the security is maintained on the third party/verification server in order to authentic request of posting or editing your site/database.

The API string is just the URL of the login for your site/database to contact the verification server.

Get user profile picture by Id

Use url as:https://graph.facebook.com/user_id/picture?type=square in src of img tag. type may be small,large.

"CSV file does not exist" for a filename with embedded quotes

You are missing '/' before Users. I assume that you are using a MAC guessing from the file path names. You root directory is '/'.

How to detect idle time in JavaScript elegantly?

You can use the below mentioned solution

var idleTime;
$(document).ready(function () {
         reloadPage();
        $('html').bind('mousemove click mouseup mousedown keydown keypress keyup submit change mouseenter scroll resize dblclick', function () {
            clearTimeout(idleTime);
            reloadPage();
        });
});
function reloadPage() {
    clearTimeout(idleTime);
    idleTime = setTimeout(function () {
        location.reload();
    }, 3000);
}

How to add header row to a pandas DataFrame

To fix your code you can simply change [Cov] to Cov.values, the first parameter of pd.DataFrame will become a multi-dimensional numpy array:

Cov = pd.read_csv("path/to/file.txt", sep='\t')
Frame=pd.DataFrame(Cov.values, columns = ["Sequence", "Start", "End", "Coverage"])
Frame.to_csv("path/to/file.txt", sep='\t')

But the smartest solution still is use pd.read_excel with header=None and names=columns_list.

"Cloning" row or column vectors

If you have a pandas dataframe and want to preserve the dtypes, even the categoricals, this is a fast way to do it:

import numpy as np
import pandas as pd
df = pd.DataFrame({1: [1, 2, 3], 2: [4, 5, 6]})
number_repeats = 50
new_df = df.reindex(np.tile(df.index, number_repeats))

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

Passing environment-dependent variables in webpack

To add to the bunch of answers:

Use ExtendedDefinePlugin instead of DefinePlugin

npm install extended-define-webpack-plugin --save-dev.

ExtendedDefinePlugin is much simpler to use and is documented :-) link

Because DefinePlugin lacks good documentation, I want to help out, by saying that it actually works like #DEFINE in c#.

#if (DEBUG)
        Console.WriteLine("Debugging is enabled.");
#endif

Thus, if you want to understand how DefinePlugin works, read the c# #define doucmentation. link

How is the default max Java heap size determined?

This is changed in Java 6 update 18.

Assuming that we have more than 1 GB of physical memory (quite common these days), it's always 1/4th of your physical memory for the server vm.

Force an Android activity to always use landscape mode

Add The Following Lines in Activity

You need to enter in every Activity

for landscape

android:screenOrientation="landscape"
tools:ignore="LockedOrientationActivity"

for portrait

android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity"

Here The Example of MainActivity

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="org.thcb.app">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity"
            android:screenOrientation="landscape"
            tools:ignore="LockedOrientationActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".MainActivity2"
            android:screenOrientation="portrait"
            tools:ignore="LockedOrientationActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

How to check if a scope variable is undefined in AngularJS template?

Using undefined to make a decision is usually a sign of bad design in Javascript. You might consider doing something else.

However, to answer your question: I think the best way of doing so would be adding a helper function.

$scope.isUndefined = function (thing) {
    return (typeof thing === "undefined");
}

and in the template

<div ng-show="isUndefined(foo)"></div>

How to show Bootstrap table with sort icon

You could try using FontAwesome. It contains a sort-icon (http://fontawesome.io/icon/sort/).

To do so, you would

  1. need to include fontawesome:

    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
    
  2. and then simply use the fontawesome-icon instead of the default-bootstrap-icons in your th's:

    <th><b>#</b> <i class="fa fa-fw fa-sort"></i></th>
    

Hope that helps.

Crop image in android

hope you are doing well. you can use my code to crop image.you just have to make a class and use this class into your XMl and java classes. Crop image. you can crop your selected image into circle and square into many of option. hope fully it will works for you.because this is totally manageable for you and you can change it according to you.

enjoy your work :)

Display a float with two decimal places in Python

f-string formatting:

This was new in Python 3.6 - the string is placed in quotation marks as usual, prepended with f'... in the same way you would r'... for a raw string. Then you place whatever you want to put within your string, variables, numbers, inside braces f'some string text with a {variable} or {number} within that text' - and Python evaluates as with previous string formatting methods, except that this method is much more readable.

>>> foobar = 3.141592
>>> print(f'My number is {foobar:.2f} - look at the nice rounding!')

My number is 3.14 - look at the nice rounding!

You can see in this example we format with decimal places in similar fashion to previous string formatting methods.

NB foobar can be an number, variable, or even an expression eg f'{3*my_func(3.14):02f}'.

Going forward, with new code I prefer f-strings over common %s or str.format() methods as f-strings can be far more readable, and are often much faster.

What is lexical scope?

Here's a different angle on this question that we can get by taking a step back and looking at the role of scoping in the larger framework of interpretation (running a program). In other words, imagine that you were building an interpreter (or compiler) for a language and were responsible for computing the output, given a program and some input to it.

Interpretation involves keeping track of three things:

  1. State - namely, variables and referenced memory locations on the heap and stack.

  2. Operations on that state - namely, every line of code in your program

  3. The environment in which a given operation runs - namely, the projection of state on an operation.

An interpreter starts at the first line of code in a program, computes its environment, runs the line in that environment and captures its effect on the program's state. It then follows the program's control flow to execute the next line of code, and repeats the process till the program ends.

The way you compute the environment for any operation is through a formal set of rules defined by the programming language. The term "binding" is frequently used to describe the mapping of the overall state of the program to a value in the environment. Note that by "overall state" we do not mean global state, but rather the sum total of every reachable definition, at any point in the execution).

This is the framework in which the scoping problem is defined. Now to the next part of what our options are.

  • As the implementor of the interpreter, you could simplify your task by making the environment as close as possible to the program's state. Accordingly, the environment of a line of code would simply be defined by environment of the previous line of code with the effects of that operation applied to it, regardless of whether the previous line was an assignment, a function call, return from a function, or a control structure such as a while loop.

This is the gist of dynamic scoping, wherein the environment that any code runs in is bound to the state of the program as defined by its execution context.

  • Or, you could think of a programmer using your language and simplify his or her task of keeping track of the values a variable can take. There are way too many paths and too much complexity involved in reasoning about the outcome the totality of past execution. Lexical Scoping helps do this by restricting the current environment to the portion of state defined in the current block, function or other unit of scope, and its parent (i.e. the block enclosing the current clock, or the function that called the present function).

In other words, with lexical scope the environment that any code sees is bound to state associated with a scope defined explicitly in the language, such as a block or a function.

List all devices, partitions and volumes in Powershell

We have multiple volumes per drive (some are mounted on subdirectories on the drive). This code shows a list of the mount points and volume labels. Obviously you can also extract free space and so on:

gwmi win32_volume|where-object {$_.filesystem -match "ntfs"}|sort {$_.name} |foreach-object {
  echo "$(echo $_.name) [$(echo $_.label)]"
}

JQuery Validate input file type

So, I had the same issue and sadly just adding to the rules didn't work. I found out that accept: and extension: are not part of JQuery validate.js by default and it requires an additional-Methods.js plugin to make it work.

So for anyone else who followed this thread and it still didn't work, you can try adding additional-Methods.js to your tag in addition to the answer above and it should work.

Python style - line continuation with strings?

Just pointing out that it is use of parentheses that invokes auto-concatenation. That's fine if you happen to already be using them in the statement. Otherwise, I would just use '\' rather than inserting parentheses (which is what most IDEs do for you automatically). The indent should align the string continuation so it is PEP8 compliant. E.g.:

my_string = "The quick brown dog " \
            "jumped over the lazy fox"

How to make URL/Phone-clickable UILabel?

Use this i liked it so much since creates link with blue color to particular text only not on whole label text: FRHyperLabel

Smartly applying hyperlink on Terms of Use

To do:

  1. Download from above link and copy FRHyperLabel.h, FRHyperLabel.m to your project.

  2. Drag drop UILabel in your Storyboard and define custom class name to FRHyperLabel in identify inspector as shown in image.

enter image description here

  1. Connect your UILabel from storyboard to your viewController.h file

@property (weak, nonatomic) IBOutlet FRHyperLabel *label;

  1. Now in your viewController.m file add following code.

`NSString *string = @"By uploading I agree to the Terms of Use"; NSDictionary *attributes = @{NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]};

_label.attributedText = [[NSAttributedString alloc]initWithString:string attributes:attributes];
[_label setFont:[_label.font fontWithSize:13.0]];

[_label setLinkForSubstring:@"Terms of Use" withLinkHandler:^(FRHyperLabel *label, NSString *substring){
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.com"]];
}];`
  1. And run it.

How do I convert date/time from 24-hour format to 12-hour AM/PM?

I think you can use date() function to achive this

$date = '19:24:15 06/13/2013'; 
echo date('h:i:s a m/d/Y', strtotime($date));

This will output

07:24:15 pm 06/13/2013

Live Sample

h is used for 12 digit time
i stands for minutes
s seconds
a will return am or pm (use in uppercase for AM PM)
m is used for months with digits
d is used for days in digit
Y uppercase is used for 4 digit year (use it lowercase for two digit)

Updated

This is with DateTime

$date = new DateTime('19:24:15 06/13/2013');
echo $date->format('h:i:s a m/d/Y') ;

Live Sample

UDP vs TCP, how much faster is it?

If you need to quickly blast a message across the net between two IP's that haven't even talked yet, then a UDP is going to arrive at least 3 times faster, usually 5 times faster.

How long to brute force a salted SHA-512 hash? (salt provided)

There isn't a single answer to this question as there are too many variables, but SHA2 is not yet really cracked (see: Lifetimes of cryptographic hash functions) so it is still a good algorithm to use to store passwords in. The use of salt is good because it prevents attack from dictionary attacks or rainbow tables. Importance of a salt is that it should be unique for each password. You can use a format like [128-bit salt][512-bit password hash] when storing the hashed passwords.

The only viable way to attack is to actually calculate hashes for different possibilities of password and eventually find the right one by matching the hashes.

To give an idea about how many hashes can be done in a second, I think Bitcoin is a decent example. Bitcoin uses SHA256 and to cut it short, the more hashes you generate, the more bitcoins you get (which you can trade for real money) and as such people are motivated to use GPUs for this purpose. You can see in the hardware overview that an average graphic card that costs only $150 can calculate more than 200 million hashes/s. The longer and more complex your password is, the longer time it will take. Calculating at 200M/s, to try all possibilities for an 8 character alphanumberic (capital, lower, numbers) will take around 300 hours. The real time will most likely less if the password is something eligible or a common english word.

As such with anything security you need to look at in context. What is the attacker's motivation? What is the kind of application? Having a hash with random salt for each gives pretty good protection against cases where something like thousands of passwords are compromised.

One thing you can do is also add additional brute force protection by slowing down the hashing procedure. As you only hash passwords once, and the attacker has to do it many times, this works in your favor. The typical way to do is to take a value, hash it, take the output, hash it again and so forth for a fixed amount of iterations. You can try something like 1,000 or 10,000 iterations for example. This will make it that many times times slower for the attacker to find each password.

Zipping a file in bash fails

Run dos2unix or similar utility on it to remove the carriage returns (^M).

This message indicates that your file has dos-style lineendings:

-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory 

Utilities like dos2unix will fix it:

 dos2unix <backup.bash >improved-backup.sh 

Or, if no such utility is installed, you can accomplish the same thing with translate:

tr -d "\015\032" <backup.bash >improved-backup.sh 

As for how those characters got there in the first place, @MadPhysicist had some good comments.

How can I implement prepend and append with regular JavaScript?

If you want to insert a raw HTML string no matter how complex, you can use: insertAdjacentHTML, with appropriate first argument:

'beforebegin' Before the element itself. 'afterbegin' Just inside the element, before its first child. 'beforeend' Just inside the element, after its last child. 'afterend' After the element itself.

Hint: you can always call Element.outerHTML to get the HTML string representing the element to be inserted.

An example of usage:

document.getElementById("foo").insertAdjacentHTML("beforeBegin",
          "<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");

DEMO

Caution: insertAdjacentHTML does not preserve listeners that where attached with .addEventLisntener.

Why don't self-closing script elements work?

XHTML 1 specification says:

?.3. Element Minimization and Empty Element Content

Given an empty instance of an element whose content model is not EMPTY (for example, an empty title or paragraph) do not use the minimized form (e.g. use <p> </p> and not <p />).

XHTML DTD specifies script elements as:

<!-- script statements, which may include CDATA sections -->
<!ELEMENT script (#PCDATA)>

How to import RecyclerView for Android L-preview

-Go to the DESIGN part in activity_main.xml -In the drag drop pallet select appCompactivity -In appCompactivity Select RecyclerView -On Selection a dialog shall appear click OK -Your project app:gradle will automatically get updated

Guzzlehttp - How get the body of a response from Guzzle 6?

Guzzle implements PSR-7. That means that it will by default store the body of a message in a Stream that uses PHP temp streams. To retrieve all the data, you can use casting operator:

$contents = (string) $response->getBody();

You can also do it with

$contents = $response->getBody()->getContents();

The difference between the two approaches is that getContents returns the remaining contents, so that a second call returns nothing unless you seek the position of the stream with rewind or seek .

$stream = $response->getBody();
$contents = $stream->getContents(); // returns all the contents
$contents = $stream->getContents(); // empty string
$stream->rewind(); // Seek to the beginning
$contents = $stream->getContents(); // returns all the contents

Instead, usings PHP's string casting operations, it will reads all the data from the stream from the beginning until the end is reached.

$contents = (string) $response->getBody(); // returns all the contents
$contents = (string) $response->getBody(); // returns all the contents

Documentation: http://docs.guzzlephp.org/en/latest/psr7.html#responses

What is Bit Masking?

Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-

enter image description here

We are doing AND operation in this example. There are also other masking operators- OR, XOR.


Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-

     1 1 1 0 1 1 0 1   [input]
(&)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     0 0 1 0 1 1 0 0  [output]

So, only the middle 4 bits (as these bits are 1 in this mask) remain.

Lets see this with XOR-

     1 1 1 0 1 1 0 1   [input]
(^)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     1 1 0 1 0 0 0 1  [output]

Now, the middle 4 bits are flipped (1 became 0, 0 became 1).


So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-

bool isOdd(int i) {
    return i%2;
}

This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-

bool isOdd(int i) {
    return i&1;
}

Short Explanation: If the least significant bit of a binary number is 1 then it is odd; for 0 it will be even. So, by doing AND with 1 we are removing all other bits except for the least significant bit i.e.:

     55  ->  0 0 1 1 0 1 1 1   [input]
(&)   1  ->  0 0 0 0 0 0 0 1    [mask]
---------------------------------------
      1  <-  0 0 0 0 0 0 0 1  [output]

When should I use File.separator and when File.pathSeparator?

If you mean File.separator and File.pathSeparator then:

  • File.pathSeparator is used to separate individual file paths in a list of file paths. Consider on windows, the PATH environment variable. You use a ; to separate the file paths so on Windows File.pathSeparator would be ;.

  • File.separator is either / or \ that is used to split up the path to a specific file. For example on Windows it is \ or C:\Documents\Test

How to know what the 'errno' means?

#include <errno.h> 
#include <stdio.h> 
#include <stdlib.h> 

int main(int i, char *c[]) { 
  if (i != 2)  
    fprintf(stderr, "Usage: perror errno\n"); 
  else { 
    errno = atoi(c[1]); 
    perror(""); 
  } 
  exit(0); 
}    

Works on Solaris.
cc perror.c -o perror << use this line to compile it

How do I view Android application specific cache?

Question: Where is application-specific cache located on Android?

Answer: /data/data

How to test enum types?

If you use all of the months in your code, your IDE won't let you compile, so I think you don't need unit testing.

But if you are using them with reflection, even if you delete one month, it will compile, so it's valid to put a unit test.

ESRI : Failed to parse source map

Chrome recently added support for source maps in the developer tools. If you go under settings on the chrome developer toolbar you can see the following two options:

Chrome Developer Tools Source Maps

If you disable those two options, and refresh the browser, it should no longer ask for source maps.

These settings can be found here:

Chrome Developer Tools Source Maps

Converting a view to Bitmap without displaying it in Android?

I used this just a few days ago:

fun generateBitmapFromView(view: View): Bitmap {
    val specWidth = View.MeasureSpec.makeMeasureSpec(1324, View.MeasureSpec.AT_MOST)
    val specHeight = View.MeasureSpec.makeMeasureSpec(521, View.MeasureSpec.AT_MOST)
    view.measure(specWidth, specHeight)
    val width = view.measuredWidth
    val height = view.measuredHeight
    val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)
    view.layout(view.left, view.top, view.right, view.bottom)
    view.draw(canvas)
    return bitmap
}

This code is based in this gist

What does the "map" method do in Ruby?

The map method takes an enumerable object and a block, and runs the block for each element, outputting each returned value from the block (the original object is unchanged unless you use map!):

[1, 2, 3].map { |n| n * n } #=> [1, 4, 9]

Array and Range are enumerable types. map with a block returns an Array. map! mutates the original array.

Where is this helpful, and what is the difference between map! and each? Here is an example:

names = ['danil', 'edmund']

# here we map one array to another, convert each element by some rule
names.map! {|name| name.capitalize } # now names contains ['Danil', 'Edmund']

names.each { |name| puts name + ' is a programmer' } # here we just do something with each element

The output:

Danil is a programmer
Edmund is a programmer

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

Expected initializer before function name

You are missing a semicolon at the end of your 'struct' definition.

Also,

*sotrudnik

needs to be

sotrudnik*

How to change option menu icon in the action bar?

you can achieve this by doing

<item
    android:id="@+id/menus"
    android:actionProviderClass="@android:style/Widget.Holo.ActionButton.Overflow"
    android:icon="@drawable/your_icon"
    android:showAsAction="always">
  <item android:id="@+id/Bugreport"
   android:title="@string/option_bugreport" />

  <item android:id="@+id/Info"
  android:title="@string/option_info" />

 <item android:id="@+id/About"
   android:title="@string/option_about" />
  </item>

Run as java application option disabled in eclipse

Run As > Java Application wont show up if the class that you want to run does not contain the main method. Make sure that the class you trying to run has main defined in it.

How can I change a button's color on hover?

Seems your selector is wrong, try using:

a.button:hover{
     background: #383;
}

Your code

a.button a:hover

Means it is going to search for an a element inside a with class button.

Inline functions in C#?

I know this question is about C#. However, you can write inline functions in .NET with F#. see: Use of `inline` in F#

How to update Identity Column in SQL Server?

You can not update identity column.

SQL Server does not allow to update the identity column unlike what you can do with other columns with an update statement.

Although there are some alternatives to achieve a similar kind of requirement.

  • When Identity column value needs to be updated for new records

Use DBCC CHECKIDENT which checks the current identity value for the table and if it's needed, changes the identity value.

DBCC CHECKIDENT('tableName', RESEED, NEW_RESEED_VALUE)
  • When Identity column value needs to be updated for existing records

Use IDENTITY_INSERT which allows explicit values to be inserted into the identity column of a table.

SET IDENTITY_INSERT YourTable {ON|OFF}

Example:

-- Set Identity insert on so that value can be inserted into this column
SET IDENTITY_INSERT YourTable ON
GO
-- Insert the record which you want to update with new value in the identity column
INSERT INTO YourTable(IdentityCol, otherCol) VALUES(13,'myValue')
GO
-- Delete the old row of which you have inserted a copy (above) (make sure about FK's)
DELETE FROM YourTable WHERE ID=3
GO
--Now set the idenetity_insert OFF to back to the previous track
SET IDENTITY_INSERT YourTable OFF

I want to compare two lists in different worksheets in Excel to locate any duplicates

Without VBA...

If you can use a helper column, you can use the MATCH function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match

To simply identify duplicates, use a helper column

Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:

=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")

Drag/copy this forumla down, and it should identify the duplicates.

To highlight cells, use conditional formatting:

With some tinkering, you can use this MATCH function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.

Something like:

=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))

Conditional formatting for Excel 2010

For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:

=B1="Duplicate"

This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.

Conditional formatting using helper column for rule

How to manually set an authenticated user in Spring Security / SpringMVC

The new filtering feature in Servlet 2.4 basically alleviates the restriction that filters can only operate in the request flow before and after the actual request processing by the application server. Instead, Servlet 2.4 filters can now interact with the request dispatcher at every dispatch point. This means that when a Web resource forwards a request to another resource (for instance, a servlet forwarding the request to a JSP page in the same application), a filter can be operating before the request is handled by the targeted resource. It also means that should a Web resource include the output or function from other Web resources (for instance, a JSP page including the output from multiple other JSP pages), Servlet 2.4 filters can work before and after each of the included resources. .

To turn on that feature you need:

web.xml

<filter>   
    <filter-name>springSecurityFilterChain</filter-name>   
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
</filter>  
<filter-mapping>   
    <filter-name>springSecurityFilterChain</filter-name>   
    <url-pattern>/<strike>*</strike></url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

RegistrationController

return "forward:/login?j_username=" + registrationModel.getUserEmail()
        + "&j_password=" + registrationModel.getPassword();

Lowercase and Uppercase with jQuery

If it's just for display purposes, you can render the text as upper or lower case in pure CSS, without any Javascript using the text-transform property:

.myclass {
    text-transform: lowercase;
}

See https://developer.mozilla.org/en/CSS/text-transform for more info.

However, note that this doesn't actually change the value to lower case; it just displays it that way. This means that if you examine the contents of the element (ie using Javascript), it will still be in its original format.

ADB server version (36) doesn't match this client (39) {Not using Genymotion}

I think you have multiple adb server running, genymotion could be one of them, but also Xamarin - Visual studio for mac OS could be running an adb server, closing Visual studio worked for me

Evaluate empty or null JSTL c tags

Here's the one liner.

Ternary operator inside EL

${empty value?'value is empty or null':'value is NOT empty or null'}

Can I execute a function after setState is finished updating?

render will be called every time you setState to re-render the component if there are changes. If you move your call to drawGrid there rather than calling it in your update* methods, you shouldn't have a problem.

If that doesn't work for you, there is also an overload of setState that takes a callback as a second parameter. You should be able to take advantage of that as a last resort.

How to position two divs horizontally within another div

When you float sub-left and sub-right they no longer take up any space within sub-title. You need to add another div with style = "clear: both" beneath them to expand the containing div or they appear below it.

HTML:

<div id="sub-title">
   <div id="sub-left">
      sub-left
   </div>
   <div id="sub-right">
      sub-right
   </div>
   <div class="clear-both"></div>
</div>

CSS:

#sub-left {
   float: left;
}
#sub-right {
   float: right;
}
.clear-both {
   clear: both;
}

How to have git log show filenames like svn log -v

I use this on a daily basis to show history with files that changed:

git log --stat --pretty=short --graph

To keep it short, add an alias in your .gitconfig by doing:

git config --global alias.ls 'log --stat --pretty=short --graph'

How to read integer values from text file

use FileInputStream's readLine() method to read and parse the returned String to int using Integer.parseInt() method.

Rails Active Record find(:all, :order => ) issue

isn't it only :order => 'column1 ASC, column2 DESC'?

GSON - Date format

As M.L. pointed out, JsonSerializer works here. However, if you are formatting database entities, use java.sql.Date to register you serializer. Deserializer is not needed.

Gson gson = new GsonBuilder()
   .registerTypeAdapter(java.sql.Date.class, ser).create();

This bug report might be related: http://code.google.com/p/google-gson/issues/detail?id=230. I use version 1.7.2 though.

Tar archiving that takes input from a list of files

Yes:

tar -cvf allfiles.tar -T mylist.txt

How do I push to GitHub under a different username?

If you use ssh and get

Permission to some_username/repository.git denied to Alice_username

while you don't wanna push as Alice_username, make sure Alice_username doesn't have your computer's ssh key added to its github account.

I deleted my ssh key from alice's github account and the push worked.

How to update a single pod without touching other dependencies

You can never get 100% isolation. Because a pod may have some shared dependencies and if you attempt to update your single pod, then it would update the dependencies of other pods as well. If that is ok then:

tl;dr use:

pod update podName

Why? Read below.

  • pod update will NOT respect the podfile.lock. It will override it — pertaining to that single pod
  • pod install will respect the podfile.lock, but will try installing every pod mentioned in the podfile based on the versions its locked to (in the Podfile.lock).

This diagram helps better understand the differences:

enter image description here


The major problem comes from the ~> aka optimistic operator.

Using exact versions in the Podfile is not enough

Some might think that specifying exact versions of their pods in their Podfile, like pod 'A', '1.0.0', is enough to guarantee that every user will have the same version as other people on the team.

Then they might even use pod update, even when just adding a new pod, thinking it would never risk updating other pods because they are fixed to a specific version in the Podfile.

But in fact, that is not enough to guarantee that user1 and user2 in our above scenario will always get the exact same version of all their pods.

One typical example is if the pod A has a dependency on pod A2 — declared in A.podspec as dependency 'A2', '~> 3.0'. In such case, using pod 'A', '1.0.0' in your Podfile will indeed force user1 and user2 to both always use version 1.0.0 of the pod A, but:

  • user1 might end up with pod A2 in version 3.4 (because that was A2's latest version at that time)
  • while when user2 runs pod install when joining the project later, they might get pod A2 in version 3.5 (because the maintainer of A2 might have released a new version in the meantime). That's why the only way to ensure every team member work with the same versions of all the pod on each's the computer is to use the Podfile.lock and properly use pod install vs. pod update.

The above excerpt was all derived from pod install vs. pod update

I also highly recommend watching what does a podfile.lock do

Android: where are downloaded files saved?

In my experience all the files which i have downloaded from internet,gmail are stored in

/sdcard/download

on ics

/sdcard/Download

You can access it using

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

Android - Handle "Enter" in an EditText

A dependable way to respond to an <enter> in an EditText is with a TextWatcher, a LocalBroadcastManager, and a BroadcastReceiver. You need to add the v4 support library to use the LocalBroadcastManager. I use the tutorial at vogella.com: 7.3 "Local broadcast events with LocalBroadcastManager" because of its complete concise code Example. In onTextChanged before is the index of the end of the change before the change>;minus start. When in the TextWatcher the UI thread is busy updating editText's editable, so we send an Intent to wake up the BroadcastReceiver when the UI thread is done updating editText.

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.Editable;
//in onCreate:
editText.addTextChangedListener(new TextWatcher() {
  public void onTextChanged
  (CharSequence s, int start, int before, int count) {
    //check if exactly one char was added and it was an <enter>
    if (before==0 && count==1 && s.charAt(start)=='\n') {
    Intent intent=new Intent("enter")
    Integer startInteger=new Integer(start);
    intent.putExtra("Start", startInteger.toString()); // Add data
    mySendBroadcast(intent);
//in the BroadcastReceiver's onReceive:
int start=Integer.parseInt(intent.getStringExtra("Start"));
editText.getText().replace(start, start+1,""); //remove the <enter>
//respond to the <enter> here

PHP: Calling another class' method

File 1

class ClassA {

    public $name = 'A';

    public function getName(){
        return $this->name;
    }

}

File 2

include("file1.php");
class ClassB {

    public $name = 'B';

    public function getName(){
        return $this->name;
    }

    public function callA(){
        $a = new ClassA();
        return $a->getName();
    }

    public static function callAStatic(){
        $a = new ClassA();
        return $a->getName();
    }

}

$b = new ClassB();
echo $b->callA();
echo $b->getName();
echo ClassB::callAStatic();

Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?

Differences

  • KEY or INDEX refers to a normal non-unique index. Non-distinct values for the index are allowed, so the index may contain rows with identical values in all columns of the index. These indexes don't enforce any restraints on your data so they are used only for access - for quickly reaching certain ranges of records without scanning all records.

  • UNIQUE refers to an index where all rows of the index must be unique. That is, the same row may not have identical non-NULL values for all columns in this index as another row. As well as being used to quickly reach certain record ranges, UNIQUE indexes can be used to enforce restraints on data, because the database system does not allow the distinct values rule to be broken when inserting or updating data.

    Your database system may allow a UNIQUE index to be applied to columns which allow NULL values, in which case two rows are allowed to be identical if they both contain a NULL value (the rationale here is that NULL is considered not equal to itself). Depending on your application, however, you may find this undesirable: if you wish to prevent this, you should disallow NULL values in the relevant columns.

  • PRIMARY acts exactly like a UNIQUE index, except that it is always named 'PRIMARY', and there may be only one on a table (and there should always be one; though some database systems don't enforce this). A PRIMARY index is intended as a primary means to uniquely identify any row in the table, so unlike UNIQUE it should not be used on any columns which allow NULL values. Your PRIMARY index should be on the smallest number of columns that are sufficient to uniquely identify a row. Often, this is just one column containing a unique auto-incremented number, but if there is anything else that can uniquely identify a row, such as "countrycode" in a list of countries, you can use that instead.

    Some database systems (such as MySQL's InnoDB) will store a table's records on disk in the order in which they appear in the PRIMARY index.

  • FULLTEXT indexes are different from all of the above, and their behaviour differs significantly between database systems. FULLTEXT indexes are only useful for full text searches done with the MATCH() / AGAINST() clause, unlike the above three - which are typically implemented internally using b-trees (allowing for selecting, sorting or ranges starting from left most column) or hash tables (allowing for selection starting from left most column).

    Where the other index types are general-purpose, a FULLTEXT index is specialised, in that it serves a narrow purpose: it's only used for a "full text search" feature.

Similarities

  • All of these indexes may have more than one column in them.

  • With the exception of FULLTEXT, the column order is significant: for the index to be useful in a query, the query must use columns from the index starting from the left - it can't use just the second, third or fourth part of an index, unless it is also using the previous columns in the index to match static values. (For a FULLTEXT index to be useful to a query, the query must use all columns of the index.)

Using a bitmask in C#

if ( ( param & karen ) == karen )
{
  // Do stuff
}

The bitwise 'and' will mask out everything except the bit that "represents" Karen. As long as each person is represented by a single bit position, you could check multiple people with a simple:

if ( ( param & karen ) == karen )
{
  // Do Karen's stuff
}
if ( ( param & bob ) == bob )
  // Do Bob's stuff
}

Cannot set property 'display' of undefined

I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.

In this code we add multiple styles in an element:

_x000D_
_x000D_
let_x000D_
    element = document.querySelector('span')_x000D_
  , cssStyle = (el, styles) => {_x000D_
      for (var property in styles) {_x000D_
          el.style[property] = styles[property];_x000D_
      }_x000D_
  }_x000D_
;_x000D_
_x000D_
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
_x000D_
span{_x000D_
font-family: sans-serif;_x000D_
color: #323232;_x000D_
background: #fff;_x000D_
}
_x000D_
<span>_x000D_
lorem ipsum_x000D_
</span>
_x000D_
_x000D_
_x000D_

Recommended way to save uploaded files in a servlet application

I post my final way of doing it based on the accepted answer:

@SuppressWarnings("serial")
@WebServlet("/")
@MultipartConfig
public final class DataCollectionServlet extends Controller {

    private static final String UPLOAD_LOCATION_PROPERTY_KEY="upload.location";
    private String uploadsDirName;

    @Override
    public void init() throws ServletException {
        super.init();
        uploadsDirName = property(UPLOAD_LOCATION_PROPERTY_KEY);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // ...
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Collection<Part> parts = req.getParts();
        for (Part part : parts) {
            File save = new File(uploadsDirName, getFilename(part) + "_"
                + System.currentTimeMillis());
            final String absolutePath = save.getAbsolutePath();
            log.debug(absolutePath);
            part.write(absolutePath);
            sc.getRequestDispatcher(DATA_COLLECTION_JSP).forward(req, resp);
        }
    }

    // helpers
    private static String getFilename(Part part) {
        // courtesy of BalusC : http://stackoverflow.com/a/2424824/281545
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim()
                        .replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1)
                        .substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }
}

where :

@SuppressWarnings("serial")
class Controller extends HttpServlet {

    static final String DATA_COLLECTION_JSP="/WEB-INF/jsp/data_collection.jsp";
    static ServletContext sc;
    Logger log;
    // private
    // "/WEB-INF/app.properties" also works...
    private static final String PROPERTIES_PATH = "WEB-INF/app.properties";
    private Properties properties;

    @Override
    public void init() throws ServletException {
        super.init();
        // synchronize !
        if (sc == null) sc = getServletContext();
        log = LoggerFactory.getLogger(this.getClass());
        try {
            loadProperties();
        } catch (IOException e) {
            throw new RuntimeException("Can't load properties file", e);
        }
    }

    private void loadProperties() throws IOException {
        try(InputStream is= sc.getResourceAsStream(PROPERTIES_PATH)) {
                if (is == null)
                    throw new RuntimeException("Can't locate properties file");
                properties = new Properties();
                properties.load(is);
        }
    }

    String property(final String key) {
        return properties.getProperty(key);
    }
}

and the /WEB-INF/app.properties :

upload.location=C:/_/

HTH and if you find a bug let me know

create table with sequence.nextval in oracle

In Oracle 12c you can also declare an identity column

CREATE TABLE identity_test_tab (
  id          NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
  description VARCHAR2(30)
);

examples & performance tests here ... where, is shorts, the conclusion is that the direct use of the sequence or the new identity column are much faster than the triggers.

How to Load Ajax in Wordpress

Personally i prefer to do ajax in wordpress the same way that i would do ajax on any other site. I create a processor php file that handles all my ajax requests and just use that URL. So this is, because of htaccess not exactly possible in wordpress so i do the following.

1.in my htaccess file that lives in my wp-content folder i add this below what's already there

<FilesMatch "forms?\.php$">
Order Allow,Deny
Allow from all
</FilesMatch>

In this case my processor file is called forms.php - you would put this in your wp-content/themes/themeName folder along with all your other files such as header.php footer.php etc... it just lives in your theme root.

2.) In my ajax code i can then use my url like this

$.ajax({
    url:'/wp-content/themes/themeName/forms.php',
    data:({
        someVar: someValue
    }),
    type: 'POST'
});

obviously you can add in any of your before, success or error type things you'd like ...but yea this is (i believe) the easier way to do it because you avoid all the silliness of telling wordpress in 8 different places what's going to happen and this also let's you avoid doing other things you see people doing where they put js code on the page level so they can dip into php where i prefer to keep my js files separate.

How can I create a correlation matrix in R?

Have a look at qtlcharts. It allows you to create interactive correlation matrices:

library(qtlcharts)
data(iris)
iris$Species <- NULL
iplotCorr(iris, reorder=TRUE)

enter image description here

It's more impressive when you correlate more variables, like in the package's vignette: enter image description here

How do I customize Facebook's sharer.php

It appears the following answer no longer works, and Facebook no longer accepts parameters on the Feed Dialog links

You can use the Feed Dialog via URL to emulate the behavior of Sharer.php, but it's a little more complicated. You need a Facebook App setup with the Base URL of the URL you plan to share configured. Then you can do the following:

1) Create a link like:

   http://www.facebook.com/dialog/feed?app_id=[FACEBOOK_APP_ID]' +
        '&link=[FULLY_QUALIFIED_LINK_TO_SHARE_CONTENT]' +
        '&picture=[LINK_TO_IMAGE]' +
        '&name=' + encodeURIComponent('[CONTENT_TITLE]') +
        '&caption=' + encodeURIComponent('[CONTENT_CAPTION]) +
        '&description=' + encodeURIComponent('[CONTENT_DESCRIPTION]') +
        '&redirect_uri=' + FBVars.baseURL + '[URL_TO_REDIRECT_TO_AFTER_SHARE]' +
        '&display=popup';

(obviously replace the [CONTENT] with the appropriate content. Documentation here: https://developers.facebook.com/docs/reference/dialogs/feed)

2) Open that link in a popup window with JavaScript on click of the share link

3) I like to create file (i.e. popupclose.html) to redirect users back to when they finish sharing, this file will contain <script>window.close();</script> to close the popup window

The only downside of using the Feed Dialog (besides setup) is that, if you manage Pages as well, you don't have the ability to choose to share via a Page, only a regular user account can share. And it can give you some really cryptic error messages, most of them are related to the setup of your Facebook app or problems with either the content or URL you are sharing.

"%%" and "%/%" for the remainder and the quotient

In R, you can assign your own operators using %[characters]%. A trivial example:

'%p%' <- function(x, y){x^2 + y}

2 %p% 3 # result: 7

While I agree with BlueTrin that %% is pretty standard, I have a suspicion %/% may have something to do with the sort of operator definitions I showed above - perhaps it was easier to implement, and makes sense: %/% means do a special sort of division (integer division)

Angular ng-repeat add bootstrap row every 3 or 4 cols

Little bit modification in @alpar 's solution

<div data-ng-app="" data-ng-init="products=['A','B','C','D','E','F', 'G','H','I','J','K','L']" class="container">
    <div ng-repeat="product in products" ng-if="$index % 6 == 0" class="row">
        <div class="col-xs-2" ng-repeat="idx in [0,1,2,3,4,5]">
        {{products[idx+$parent.$index]}} <!-- When this HTML is Big it's useful approach -->
        </div>
    </div>
</div>

jsfiddle

What is the difference between encrypting and signing in asymmetric encryption?

Signing is producing a "hash" with your private key that can be verified with your public key. The text is sent in the clear.

Encrypting uses the receiver's public key to encrypt the data; decoding is done with their private key.

So, the use of keys is not reversed (otherwise your private key wouldn't be private anymore!).

Add ArrayList to another ArrayList in java

Then you need a ArrayList of ArrayLists:

ArrayList<ArrayList<String>> nodes = new ArrayList<ArrayList<String>>();
ArrayList<String> nodeList = new ArrayList<String>();
nodes.add(nodeList);

Note that NodeList has been changed to nodeList. In Java Naming Conventions variables start with a lower case. Classes start with an upper case.

Java Regex Capturing Groups

This is totally OK.

  1. The first group (m.group(0)) always captures the whole area that is covered by your regular expression. In this case, it's the whole string.
  2. Regular expressions are greedy by default, meaning that the first group captures as much as possible without violating the regex. The (.*)(\\d+) (the first part of your regex) covers the ...QT300 int the first group and the 0 in the second.
  3. You can quickly fix this by making the first group non-greedy: change (.*) to (.*?).

For more info on greedy vs. lazy, check this site.

Using Regular Expressions to Extract a Value in Java

In addition to Pattern, the Java String class also has several methods that can work with regular expressions, in your case the code will be:

"ab123abc".replaceFirst("\\D*(\\d*).*", "$1")

where \\D is a non-digit character.

How to make vim paste from (and copy to) system's clipboard?

If you are using vim in MAC OSX, unfortunately it comes with older verion, and not complied with clipboard options. Luckily, homebrew can easily solve this problem.

install vim:

brew install vim --with-lua --with-override-system-vim

install gui verion of vim:

brew install macvim --with-lua --with-override-system-vim

restart the terminal to take effect.


append the following line to ~/.vimrc
set clipboard=unnamed

now you can copy the line in vim with yy and paste it system-wide.

In Laravel, the best way to pass different types of flash messages in the session

I came across this elegant way to flash messages. It was made by Jeffrey Way from Laracast. check it out... https://github.com/laracasts/flash

How to check if a variable is an integer or a string?

In my opinion you have two options:

  • Just try to convert it to an int, but catch the exception:

    try:
        value = int(value)
    except ValueError:
        pass  # it was a string, not an int.
    

    This is the Ask Forgiveness approach.

  • Explicitly test if there are only digits in the string:

    value.isdigit()
    

    str.isdigit() returns True only if all characters in the string are digits (0-9).

    The unicode / Python 3 str type equivalent is unicode.isdecimal() / str.isdecimal(); only Unicode decimals can be converted to integers, as not all digits have an actual integer value (U+00B2 SUPERSCRIPT 2 is a digit, but not a decimal, for example).

    This is often called the Ask Permission approach, or Look Before You Leap.

The latter will not detect all valid int() values, as whitespace and + and - are also allowed in int() values. The first form will happily accept ' +10 ' as a number, the latter won't.

If your expect that the user normally will input an integer, use the first form. It is easier (and faster) to ask for forgiveness rather than for permission in that case.

Why can't I do <img src="C:/localfile.jpg">?

what about having the image be something selected by the user? Use a input:file tag and then after they select the image, show it on the clientside webpage? That is doable for most things. Right now i am trying to get it working for IE, but as with all microsoft products, it is a cluster fork().

How to redirect docker container logs to a single file?

The easiest way that I use is this command on terminal:

docker logs elk > /home/Desktop/output.log

structure is:

docker logs <Container Name> > path/filename.log

Why can't I use the 'await' operator within the body of a lock statement?

This is just an extension to this answer.

using System;
using System.Threading;
using System.Threading.Tasks;

public class SemaphoreLocker
{
    private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);

    public async Task LockAsync(Func<Task> worker)
    {
        await _semaphore.WaitAsync();
        try
        {
            await worker();
        }
        finally
        {
            _semaphore.Release();
        }
    }

    // overloading variant for non-void methods with return type (generic T)
    public async Task<T> LockAsync<T>(Func<Task<T>> worker)
    {
        await _semaphore.WaitAsync();

        T result = default;

        try
        {
            result = await worker();
        }
        finally
        {
            _semaphore.Release();
        }

        return result;
    }
}

Usage:

public class Test
{
    private static readonly SemaphoreLocker _locker = new SemaphoreLocker();

    public async Task DoTest()
    {
        await _locker.LockAsync(async () =>
        {
            // [async] calls can be used within this block 
            // to handle a resource by one thread. 
        });
        // OR
        var result = await _locker.LockAsync(async () =>
        {
            // [async] calls can be used within this block 
            // to handle a resource by one thread. 
        }
    }
}

How is a CRC32 checksum calculated?

The polynomial for CRC32 is:

x32 + x26 + x23 + x22 + x16 + x12 + x11 + x10 + x8 + x7 + x5 + x4 + x2 + x + 1

Or in hex and binary:

0x 01 04 C1 1D B7
1 0000 0100 1100 0001 0001 1101 1011 0111

The highest term (x32) is usually not explicitly written, so it can instead be represented in hex just as

0x 04 C1 1D B7

Feel free to count the 1s and 0s, but you'll find they match up with the polynomial, where 1 is bit 0 (or the first bit) and x is bit 1 (or the second bit).

Why this polynomial? Because there needs to be a standard given polynomial and the standard was set by IEEE 802.3. Also it is extremely difficult to find a polynomial that detects different bit errors effectively.

You can think of the CRC-32 as a series of "Binary Arithmetic with No Carries", or basically "XOR and shift operations". This is technically called Polynomial Arithmetic.

To better understand it, think of this multiplication:

(x^3 + x^2 + x^0)(x^3 + x^1 + x^0)
= (x^6 + x^4 + x^3
 + x^5 + x^3 + x^2
 + x^3 + x^1 + x^0)
= x^6 + x^5 + x^4 + 3*x^3 + x^2 + x^1 + x^0

If we assume x is base 2 then we get:

x^7 + x^3 + x^2 + x^1 + x^0

Why? Because 3x^3 is 11x^11 (but we need only 1 or 0 pre digit) so we carry over:

=1x^110 + 1x^101 + 1x^100          + 11x^11 + 1x^10 + 1x^1 + x^0
=1x^110 + 1x^101 + 1x^100 + 1x^100 + 1x^11 + 1x^10 + 1x^1 + x^0
=1x^110 + 1x^101 + 1x^101          + 1x^11 + 1x^10 + 1x^1 + x^0
=1x^110 + 1x^110                   + 1x^11 + 1x^10 + 1x^1 + x^0
=1x^111                            + 1x^11 + 1x^10 + 1x^1 + x^0

But mathematicians changed the rules so that it is mod 2. So basically any binary polynomial mod 2 is just addition without carry or XORs. So our original equation looks like:

=( 1x^110 + 1x^101 + 1x^100 + 11x^11 + 1x^10 + 1x^1 + x^0 ) MOD 2
=( 1x^110 + 1x^101 + 1x^100 +  1x^11 + 1x^10 + 1x^1 + x^0 )
= x^6 + x^5 + x^4 + 3*x^3 + x^2 + x^1 + x^0 (or that original number we had)

I know this is a leap of faith but this is beyond my capability as a line-programmer. If you are a hard-core CS-student or engineer I challenge to break this down. Everyone will benefit from this analysis.

So to work out a full example:

   Original message                : 1101011011
   Polynomial of (W)idth 4         :      10011
   Message after appending W zeros : 11010110110000

Now we divide the augmented Message by the Poly using CRC arithmetic. This is the same division as before:

            1100001010 = Quotient (nobody cares about the quotient)
       _______________
10011 ) 11010110110000 = Augmented message (1101011011 + 0000)
=Poly   10011,,.,,....
        -----,,.,,....
         10011,.,,....
         10011,.,,....
         -----,.,,....
          00001.,,....
          00000.,,....
          -----.,,....
           00010,,....
           00000,,....
           -----,,....
            00101,....
            00000,....
            -----,....
             01011....
             00000....
             -----....
              10110...
              10011...
              -----...
               01010..
               00000..
               -----..
                10100.
                10011.
                -----.
                 01110
                 00000
                 -----
                  1110 = Remainder = THE CHECKSUM!!!!

The division yields a quotient, which we throw away, and a remainder, which is the calculated checksum. This ends the calculation. Usually, the checksum is then appended to the message and the result transmitted. In this case the transmission would be: 11010110111110.

Only use a 32-bit number as your divisor and use your entire stream as your dividend. Throw out the quotient and keep the remainder. Tack the remainder on the end of your message and you have a CRC32.

Average guy review:

         QUOTIENT
        ----------
DIVISOR ) DIVIDEND
                 = REMAINDER
  1. Take the first 32 bits.
  2. Shift bits
  3. If 32 bits are less than DIVISOR, go to step 2.
  4. XOR 32 bits by DIVISOR. Go to step 2.

(Note that the stream has to be dividable by 32 bits or it should be padded. For example, an 8-bit ANSI stream would have to be padded. Also at the end of the stream, the division is halted.)

Get GMT Time in Java

Useful Utils methods as below for manage Time in GMT with DST Savings:

public static Date convertToGmt(Date date) {
    TimeZone tz = TimeZone.getDefault();
    Date ret = new Date(date.getTime() - tz.getRawOffset());

    // if we are now in DST, back off by the delta.  Note that we are checking the GMT date, this is the KEY.
    if (tz.inDaylightTime(ret)) {
        Date dstDate = new Date(ret.getTime() - tz.getDSTSavings());

        // check to make sure we have not crossed back into standard time
        // this happens when we are on the cusp of DST (7pm the day before the change for PDT)
        if (tz.inDaylightTime(dstDate)) {
            ret = dstDate;
        }
    }
    return ret;
}

public static Date convertFromGmt(Date date) {
    TimeZone tz = TimeZone.getDefault();
    Date ret = new Date(date.getTime() + tz.getRawOffset());

    // if we are now in DST, back off by the delta.  Note that we are checking the GMT date, this is the KEY.
    if (tz.inDaylightTime(ret)) {
        Date dstDate = new Date(ret.getTime() + tz.getDSTSavings());

        // check to make sure we have not crossed back into standard time
        // this happens when we are on the cusp of DST (7pm the day before the change for PDT)
        if (tz.inDaylightTime(dstDate)) {
            ret = dstDate;
        }
    }
    return ret;
}

Pass a variable to a PHP script running from the command line

You could use what sep16 on php.net recommends:

<?php

parse_str(implode('&', array_slice($argv, 1)), $_GET);

?>

It behaves exactly like you'd expect with cgi-php.

$ php -f myfile.php type=daily a=1 b[]=2 b[]=3

will set $_GET['type'] to 'daily', $_GET['a'] to '1' and $_GET['b'] to array('2', '3').

Javascript - object key->value

Use this syntax:

obj[name]

Note that obj.x is the same as obj["x"] for all valid JS identifiers, but the latter form accepts all string as keys (not just valid identifiers).

obj["Hey, this is ... neat?"] = 42

JavaScript: How do I print a message to the error console?

To answer your question you can use ES6 features,

var var=10;
console.log(`var=${var}`);

Start new Activity and finish current one in Android?

You can use finish() method or you can use:

android:noHistory="true"

And then there is no need to call finish() anymore.

<activity android:name=".ClassName" android:noHistory="true" ... />

Get time difference between two dates in seconds

Define two dates using new Date(). Calculate the time difference of two dates using date2. getTime() – date1. getTime(); Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (10006060*24)

Calculate the execution time of a method

From personal experience, the System.Diagnostics.Stopwatch class can be used to measure the execution time of a method, however, BEWARE: It is not entirely accurate!

Consider the following example:

Stopwatch sw;

for(int index = 0; index < 10; index++)
{
    sw = Stopwatch.StartNew();
    DoSomething();
    Console.WriteLine(sw.ElapsedMilliseconds);
}

sw.Stop();

Example results

132ms
4ms
3ms
3ms
2ms
3ms
34ms
2ms
1ms
1ms

Now you're wondering; "well why did it take 132ms the first time, and significantly less the rest of the time?"

The answer is that Stopwatch does not compensate for "background noise" activity in .NET, such as JITing. Therefore the first time you run your method, .NET JIT's it first. The time it takes to do this is added to the time of the execution. Equally, other factors will also cause the execution time to vary.

What you should really be looking for absolute accuracy is Performance Profiling!

Take a look at the following:

RedGate ANTS Performance Profiler is a commercial product, but produces very accurate results. - Boost the performance of your applications with .NET profiling

Here is a StackOverflow article on profiling: - What Are Some Good .NET Profilers?

I have also written an article on Performance Profiling using Stopwatch that you may want to look at - Performance profiling in .NET

Could not create work tree dir 'example.com'.: Permission denied

I think you don't have your permissions set up correctly for /var/www Change the ownership of the folder.

sudo chown -R **yourusername** /var/www

Writing a VLOOKUP function in vba

        Public Function VLOOKUP1(ByVal lookup_value As String, ByVal table_array As Range, ByVal col_index_num As Integer) As String
        Dim i As Long

        For i = 1 To table_array.Rows.Count
            If lookup_value = table_array.Cells(table_array.Row + i - 1, 1) Then
                VLOOKUP1 = table_array.Cells(table_array.Row + i - 1, col_index_num)
                Exit For
            End If
        Next i

        End Function

IE9 jQuery AJAX with CORS returns "Access is denied"

Note -- Note

do not use "http://www.domain.xxx" or "http://localhost/" or "IP >> 127.0.0.1" for URL in ajax. only use path(directory) and page name without address.

false state:

var AJAXobj = createAjax();
AJAXobj.onreadystatechange = handlesAJAXcheck;
AJAXobj.open('POST', 'http://www.example.com/dir/getSecurityCode.php', true);
AJAXobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
AJAXobj.send(pack);

true state:

var AJAXobj = createAjax();
AJAXobj.onreadystatechange = handlesAJAXcheck;
AJAXobj.open('POST', 'dir/getSecurityCode.php', true);   // <<--- note
AJAXobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
AJAXobj.send(pack);

What is the difference between a var and val definition in Scala?

Though many have already answered the difference between Val and var. But one point to notice is that val is not exactly like final keyword.

We can change the value of val using recursion but we can never change value of final. Final is more constant than Val.

def factorial(num: Int): Int = {
 if(num == 0) 1
 else factorial(num - 1) * num
}

Method parameters are by default val and at every call value is being changed.

jQuery animate margin top

You had MarginTop instead of marginTop

http://jsfiddle.net/kX7b6/1/

It is also very buggy if you leave mid animation, here is update:

http://jsfiddle.net/kX7b6/3/

Note I changed it to mouseenter and mouseleave because I don't think the intention was to cancel the animation when you hover over the red or green area.

Python: Writing to and Reading from serial port

ser.read(64) should be ser.read(size=64); ser.read uses keyword arguments, not positional.

Also, you're reading from the port twice; what you probably want to do is this:

i=0
for modem in PortList:
    for port in modem:
        try:
            ser = serial.Serial(port, 9600, timeout=1)
            ser.close()
            ser.open()
            ser.write("ati")
            time.sleep(3)
            read_val = ser.read(size=64)
            print read_val
            if read_val is not '':
                print port
        except serial.SerialException:
            continue
        i+=1

Delete all Duplicate Rows except for One in MySQL?

If you want to keep the row with the lowest id value:

DELETE FROM NAMES
 WHERE id NOT IN (SELECT * 
                    FROM (SELECT MIN(n.id)
                            FROM NAMES n
                        GROUP BY n.name) x)

If you want the id value that is the highest:

DELETE FROM NAMES
 WHERE id NOT IN (SELECT * 
                    FROM (SELECT MAX(n.id)
                            FROM NAMES n
                        GROUP BY n.name) x)

The subquery in a subquery is necessary for MySQL, or you'll get a 1093 error.

Pythonic way of checking if a condition holds for any element of a list

Python has a built in any() function for exactly this purpose.

WPF ListView - detect when selected item is clicked

You can handle click on list view item like this:

<ListView.ItemTemplate>
  <DataTemplate>
     <Button BorderBrush="Transparent" Background="Transparent" Focusable="False">
        <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <i:InvokeCommandAction Command="{Binding DataContext.MyCommand, ElementName=ListViewName}" CommandParameter="{Binding}"/>
                </i:EventTrigger>
        </i:Interaction.Triggers>
      <Button.Template>
      <ControlTemplate>
         <Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
    ...

accessing a docker container from another container

Using docker-compose, services are exposed to each other by name by default. Docs.
You could also specify an alias like;

version: '2.1'
services:
  mongo:
    image: mongo:3.2.11
  redis:
    image: redis:3.2.10
  api:
    image: some-image
    depends_on:
      - mongo
      - solr
    links:
      - "mongo:mongo.openconceptlab.org"
      - "solr:solr.openconceptlab.org"
      - "some-service:some-alias"

And then access the service using the specified alias as a host name, e.g mongo.openconceptlab.org for mongo in this case.

In Visual Studio Code How do I merge between two local branches?

Update June 2017 (from VSCode 1.14)

The ability to merge local branches has been added through PR 25731 and commit 89cd05f: accessible through the "Git: merge branch" command.
And PR 27405 added handling the diff3-style merge correctly.

Vahid's answer mention 1.17, but that September release actually added nothing regarding merge.
Only the 1.18 October one added Git conflict markers

https://code.visualstudio.com/assets/updates/1_18/merge.png

From 1.18, with the combination of merge command (1.14) and merge markers (1.18), you truly can do local merges between branches.


Original answer 2016:

The Version Control doc does not mention merge commands, only merge status and conflict support.

Even the latest 1.3 June release does not bring anything new to the VCS front.

This is supported by issue 5770 which confirms you cannot use VS Code as a git mergetool, because:

Is this feature being included in the next iteration, by any chance?

Probably not, this is a big endeavour, since a merge UI needs to be implemented.

That leaves the actual merge to be initiated from command line only.

How big can a MySQL database get before performance starts to degrade

Query performance mainly depends on the number of records it needs to scan, indexes plays a high role in it and index data size is proportional to number of rows and number of indexes.

Queries with indexed field conditions along with full value would be returned in 1ms generally, but starts_with, IN, Between, obviously contains conditions might take more time with more records to scan.

Also you will face lot of maintenance issues with DDL, like ALTER, DROP will be slow and difficult with more live traffic even for adding a index or new columns.

Generally its advisable to cluster the Database into as many clusters as required (500GB would be a general benchmark, as said by others it depends on many factors and can vary based on use cases) that way it gives better isolation and gives independence to scale specific clusters (more suited in case of B2B)

Move to next item using Java 8 foreach loop in stream

The lambda you are passing to forEach() is evaluated for each element received from the stream. The iteration itself is not visible from within the scope of the lambda, so you cannot continue it as if forEach() were a C preprocessor macro. Instead, you can conditionally skip the rest of the statements in it.

How can I send an HTTP POST request to a server from Excel using VBA?

To complete the response of the other users:

For this I have created an "WinHttp.WinHttpRequest.5.1" object.

Send a post request with some data from Excel using VBA:

Dim LoginRequest As Object
Set LoginRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
LoginRequest.Open "POST", "http://...", False
LoginRequest.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
LoginRequest.send ("key1=value1&key2=value2")

Send a get request with token authentication from Excel using VBA:

Dim TCRequestItem As Object
Set TCRequestItem = CreateObject("WinHttp.WinHttpRequest.5.1")
TCRequestItem.Open "GET", "http://...", False
TCRequestItem.setRequestHeader "Content-Type", "application/xml"
TCRequestItem.setRequestHeader "Accept", "application/xml"
TCRequestItem.setRequestHeader "Authorization", "Bearer " & token
TCRequestItem.send

Python Script to convert Image into Byte array

with BytesIO() as output:
    from PIL import Image
    with Image.open(filename) as img:
        img.convert('RGB').save(output, 'BMP')                
    data = output.getvalue()[14:]

I just use this for add a image to clipboard in windows.

"unexpected token import" in Nodejs5 and babel?

if you use the preset for react-native it accepts the import

npm i babel-preset-react-native --save-dev

and put it inside your .babelrc file

{
  "presets": ["react-native"]
}

in your project root directory

https://www.npmjs.com/package/babel-preset-react-native

Use and meaning of "in" in an if statement?

Using a in b is simply translates to b.__contains__(a), which should return if b includes a or not.

But, your example looks a little weird, it takes an input from user and assigns its integer value to how_much variable if the input contains "0" or "1".

Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

It is possible to set environment variables on Mac OS X 10.10 Yosemite with 3 files + 2 commands.

Main file with environment variables definition:

$ ls -la /etc/environment 
-r-xr-xr-x  1 root  wheel  369 Oct 21 04:42 /etc/environment
$ cat /etc/environment
#!/bin/sh

set -e

syslog -s -l warn "Set environment variables with /etc/environment $(whoami) - start"

launchctl setenv JAVA_HOME      /usr/local/jdk1.7
launchctl setenv MAVEN_HOME     /opt/local/share/java/maven3

if [ -x /usr/libexec/path_helper ]; then
    export PATH=""
    eval `/usr/libexec/path_helper -s`
    launchctl setenv PATH $PATH
fi

osascript -e 'tell app "Dock" to quit'

syslog -s -l warn "Set environment variables with /etc/environment $(whoami) - complete"

Service definition to load environment variables for user applications (terminal, IDE, ...):

$ ls -la /Library/LaunchAgents/environment.user.plist
-rw-------  1 root  wheel  504 Oct 21 04:37 /Library/LaunchAgents/environment.user.plist
$ sudo cat /Library/LaunchAgents/environment.user.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>environment.user</string>
    <key>ProgramArguments</key>
    <array>
            <string>/etc/environment</string>
    </array>
    <key>KeepAlive</key>
    <false/>
    <key>RunAtLoad</key>
    <true/>
    <key>WatchPaths</key>
    <array>
        <string>/etc/environment</string>
    </array>
</dict>
</plist>

The same service definition for root user applications:

$ ls -la /Library/LaunchDaemons/environment.plist
-rw-------  1 root  wheel  499 Oct 21 04:38 /Library/LaunchDaemons/environment.plist
$ sudo cat /Library/LaunchDaemons/environment.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>environment</string>
    <key>ProgramArguments</key>
    <array>
            <string>/etc/environment</string>
    </array>
    <key>KeepAlive</key>
    <false/>
    <key>RunAtLoad</key>
    <true/>
    <key>WatchPaths</key>
    <array>
        <string>/etc/environment</string>
    </array>
</dict>
</plist>

And finally we should register these services:

$ launchctl load -w /Library/LaunchAgents/environment.user.plist
$ sudo launchctl load -w /Library/LaunchDaemons/environment.plist

What we get:

  1. The only place to declare system environment variables: /etc/environment
  2. Instant auto-update of environment variables after modification of /etc/environment file - just relaunch your application

Issues / problems:

In order your env variables were correctly taken by applications after system reboot you will need:

  • either login twice: login => logout => login
  • or close & re-open applications manually, where env variables should be taken
  • or do NOT use feature "Reopen windows when logging back".

This happens due to Apple denies explicit ordering of loaded services, so env variables are registered in parallel with processing of the "reopen queue".

But actually, I reboot my system only several times per year (on big updates), so it is not a big deal.

Loop in Jade (currently known as "Pug") template engine

Here is a very simple jade file that have a loop in it. Jade is very sensitive about white space. After loop definition line (for) you should give an indent(tab) to stuff that want to go inside the loop. You can do this without {}:

- var arr=['one', 'two', 'three'];
- var s = 'string';
doctype html
html
    head
    body
        section= s
        - for (var i=0; i<3; i++)
            div= arr[i]

How do I vertically align text in a div?

These days (we don't need Internet Explorer 6-7-8 any more) I would just use CSS display: table for this issue (or display: flex).


For older browsers:

Table:

_x000D_
_x000D_
.vcenter {_x000D_
    display: table;_x000D_
    background: #eee; /* optional */_x000D_
    width: 150px;_x000D_
    height: 150px;_x000D_
    text-align: center; /* optional */_x000D_
}_x000D_
_x000D_
.vcenter > :first-child {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<div class="vcenter">_x000D_
  <p>This is my Text</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Flex:

_x000D_
_x000D_
.vcenter {_x000D_
    display: flex; /* <-- Here */_x000D_
    align-items: center; /* <-- Here */_x000D_
    justify-content: center; /* optional */_x000D_
    height: 150px; /* <-- Here */_x000D_
    background: #eee;  /* optional */_x000D_
    width: 150px;_x000D_
}
_x000D_
<div class="vcenter">_x000D_
  <p>This is my text</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_


This is (actually, was) my favorite solution for this issue (simple and very well browser supported):

_x000D_
_x000D_
div {_x000D_
    margin: 5px;_x000D_
    text-align: center;_x000D_
    display: inline-block;_x000D_
}_x000D_
_x000D_
.vcenter {_x000D_
    background: #eee;  /* optional */_x000D_
    width: 150px;_x000D_
    height: 150px;_x000D_
}_x000D_
.vcenter:before {_x000D_
    content: " ";_x000D_
    display: inline-block;_x000D_
    height: 100%;_x000D_
    vertical-align: middle;_x000D_
    max-width: 0.001%; /* Just in case the text wrapps, you shouldn't notice it */_x000D_
}_x000D_
_x000D_
.vcenter > :first-child {_x000D_
    display: inline-block;_x000D_
    vertical-align: middle;_x000D_
    max-width: 99.999%;_x000D_
}
_x000D_
<div class="vcenter">_x000D_
  <p>This is my text</p>_x000D_
</div>_x000D_
<div class="vcenter">_x000D_
  <h4>This is my Text<br/>Text<br/>Text</h4>_x000D_
</div>_x000D_
<div class="vcenter">_x000D_
  <div>_x000D_
   <p>This is my</p>_x000D_
   <p>Text</p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I create a ListView with rounded corners in Android?

to make border u have to make another xml file with property of solid and corners in the drawable folder and calls it in background

Display Records From MySQL Database using JTable in Java

Below is a class which will accomplish the very basics of what you want to do when reading data from a MySQL database into a JTable in Java.

import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

public class TableFromMySqlDatabase extends JFrame
{
    public TableFromMySqlDatabase()
    {
        ArrayList columnNames = new ArrayList();
        ArrayList data = new ArrayList();

        //  Connect to an MySQL Database, run query, get result set
        String url = "jdbc:mysql://localhost:3306/yourdb";
        String userid = "root";
        String password = "sesame";
        String sql = "SELECT * FROM animals";

        // Java SE 7 has try-with-resources
        // This will ensure that the sql objects are closed when the program 
        // is finished with them
        try (Connection connection = DriverManager.getConnection( url, userid, password );
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery( sql ))
        {
            ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();

            //  Get column names
            for (int i = 1; i <= columns; i++)
            {
                columnNames.add( md.getColumnName(i) );
            }

            //  Get row data
            while (rs.next())
            {
                ArrayList row = new ArrayList(columns);

                for (int i = 1; i <= columns; i++)
                {
                    row.add( rs.getObject(i) );
                }

                data.add( row );
            }
        }
        catch (SQLException e)
        {
            System.out.println( e.getMessage() );
        }

        // Create Vectors and copy over elements from ArrayLists to them
        // Vector is deprecated but I am using them in this example to keep 
        // things simple - the best practice would be to create a custom defined
        // class which inherits from the AbstractTableModel class
        Vector columnNamesVector = new Vector();
        Vector dataVector = new Vector();

        for (int i = 0; i < data.size(); i++)
        {
            ArrayList subArray = (ArrayList)data.get(i);
            Vector subVector = new Vector();
            for (int j = 0; j < subArray.size(); j++)
            {
                subVector.add(subArray.get(j));
            }
            dataVector.add(subVector);
        }

        for (int i = 0; i < columnNames.size(); i++ )
            columnNamesVector.add(columnNames.get(i));

        //  Create table with database data    
        JTable table = new JTable(dataVector, columnNamesVector)
        {
            public Class getColumnClass(int column)
            {
                for (int row = 0; row < getRowCount(); row++)
                {
                    Object o = getValueAt(row, column);

                    if (o != null)
                    {
                        return o.getClass();
                    }
                }

                return Object.class;
            }
        };

        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );

        JPanel buttonPanel = new JPanel();
        getContentPane().add( buttonPanel, BorderLayout.SOUTH );
    }

    public static void main(String[] args)
    {
        TableFromMySqlDatabase frame = new TableFromMySqlDatabase();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible(true);
    }
}

In the NetBeans IDE which you are using - you will need to add the MySQL JDBC Driver in Project Properties as I display here:

enter image description here

Otherwise the code will throw an SQLException stating that the driver cannot be found.

Now in my example, yourdb is the name of the database and animals is the name of the table that I am performing a query against.

Here is what will be output:

enter image description here

Parting note:

You stated that you were a novice and needed some help understanding some of the basic classes and concepts of Java. I will list a few here, but remember you can always browse the docs on Oracle's site.

How to show all shared libraries used by executables in Linux?

readelf -d recursion

redelf -d produces similar output to objdump -p which was mentioned at: https://stackoverflow.com/a/15520982/895245

But beware that dynamic libraries can depend on other dynamic libraries, to you have to recurse.

Example:

readelf -d /bin/ls | grep 'NEEDED'

Sample ouptut:

 0x0000000000000001 (NEEDED)             Shared library: [libselinux.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [libacl.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]

Then:

$ locate libselinux.so.1
/lib/i386-linux-gnu/libselinux.so.1
/lib/x86_64-linux-gnu/libselinux.so.1
/mnt/debootstrap/lib/x86_64-linux-gnu/libselinux.so.1

Choose one, and repeat:

readelf -d /lib/x86_64-linux-gnu/libselinux.so.1 | grep 'NEEDED'

Sample output:

0x0000000000000001 (NEEDED)             Shared library: [libpcre.so.3]
0x0000000000000001 (NEEDED)             Shared library: [libdl.so.2]
0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]
0x0000000000000001 (NEEDED)             Shared library: [ld-linux-x86-64.so.2]

And so on.

/proc/<pid>/maps for running processes

This is useful to find all the libraries currently being used by running executables. E.g.:

sudo awk '/\.so/{print $6}' /proc/1/maps | sort -u

shows all currently loaded dynamic dependencies of init (PID 1):

/lib/x86_64-linux-gnu/ld-2.23.so
/lib/x86_64-linux-gnu/libapparmor.so.1.4.0
/lib/x86_64-linux-gnu/libaudit.so.1.0.0
/lib/x86_64-linux-gnu/libblkid.so.1.1.0
/lib/x86_64-linux-gnu/libc-2.23.so
/lib/x86_64-linux-gnu/libcap.so.2.24
/lib/x86_64-linux-gnu/libdl-2.23.so
/lib/x86_64-linux-gnu/libkmod.so.2.3.0
/lib/x86_64-linux-gnu/libmount.so.1.1.0
/lib/x86_64-linux-gnu/libpam.so.0.83.1
/lib/x86_64-linux-gnu/libpcre.so.3.13.2
/lib/x86_64-linux-gnu/libpthread-2.23.so
/lib/x86_64-linux-gnu/librt-2.23.so
/lib/x86_64-linux-gnu/libseccomp.so.2.2.3
/lib/x86_64-linux-gnu/libselinux.so.1
/lib/x86_64-linux-gnu/libuuid.so.1.3.0

This method also shows libraries opened with dlopen, tested with this minimal setup hacked up with a sleep(1000) on Ubuntu 18.04.

See also: https://superuser.com/questions/310199/see-currently-loaded-shared-objects-in-linux/1243089

How can I generate Unix timestamps?

In Perl:

>> time
=> 1335552733

How to push to History in React Router v4?

You can use the history methods outside of your components. Try by the following way.

First, create a history object used the history package:

// src/history.js

import { createBrowserHistory } from 'history';

export default createBrowserHistory();

Then wrap it in <Router> (please note, you should use import { Router } instead of import { BrowserRouter as Router }):

// src/index.jsx

// ...
import { Router, Route, Link } from 'react-router-dom';
import history from './history';

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/login">Login</Link></li>
        </ul>
        <Route exact path="/" component={HomePage} />
        <Route path="/login" component={LoginPage} />
      </div>
    </Router>
  </Provider>,
  document.getElementById('root'),
);

Change your current location from any place, for example:

// src/actions/userActionCreators.js

// ...
import history from '../history';

export function login(credentials) {
  return function (dispatch) {
    return loginRemotely(credentials)
      .then((response) => {
        // ...
        history.push('/');
      });
  };
}

UPD: You can also see a slightly different example in React Router FAQ.

Get position/offset of element relative to a parent container?

I did it like this in Internet Explorer.

function getWindowRelativeOffset(parentWindow, elem) {
    var offset = {
        left : 0,
        top : 0
    };
    // relative to the target field's document
    offset.left = elem.getBoundingClientRect().left;
    offset.top = elem.getBoundingClientRect().top;
    // now we will calculate according to the current document, this current
    // document might be same as the document of target field or it may be
    // parent of the document of the target field
    var childWindow = elem.document.frames.window;
    while (childWindow != parentWindow) {
        offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
        offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
        childWindow = childWindow.parent;
    }

    return offset;
};

=================== you can call it like this

getWindowRelativeOffset(top, inputElement);

I focus on IE only as per my focus but similar things can be done for other browsers.

How to check if a variable exists in a FreeMarker template?

To check if the value exists:

[#if userName??]
   Hi ${userName}, How are you?
[/#if]

Or with the standard freemarker syntax:

<#if userName??>
   Hi ${userName}, How are you?
</#if>

To check if the value exists and is not empty:

<#if userName?has_content>
    Hi ${userName}, How are you?
</#if>

Using "word-wrap: break-word" within a table

You can try this:

td p {word-break:break-all;}

This, however, makes it appear like this when there's enough space, unless you add a <br> tag:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

So, I would then suggest adding <br> tags where there are newlines, if possible.

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

http://jsfiddle.net/LLyH3/3/

Also, if this doesn't solve your problem, there's a similar thread here.

How to create a custom string representation for a class object?

If you have to choose between __repr__ or __str__ go for the first one, as by default implementation __str__ calls __repr__ when it wasn't defined.

Custom Vector3 example:

class Vector3(object):
    def __init__(self, args):
        self.x = args[0]
        self.y = args[1]
        self.z = args[2]

    def __repr__(self):
        return "Vector3([{0},{1},{2}])".format(self.x, self.y, self.z)

    def __str__(self):
        return "x: {0}, y: {1}, z: {2}".format(self.x, self.y, self.z)

In this example, repr returns again a string that can be directly consumed/executed, whereas str is more useful as a debug output.

v = Vector3([1,2,3])
print repr(v)    #Vector3([1,2,3])
print str(v)     #x:1, y:2, z:3

jQuery click event on radio button doesn't get fired

Seems like you're #inline_content isn't there! Remove the jQuery-Selector or check the parent elements, maybe you have a typo or forgot to add the id.

(made you a jsfiddle, works after adding a parent <div id="inline_content">: http://jsfiddle.net/J5HdN/)

Android getResources().getDrawable() deprecated API 22

Now you need to implement like this

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //>= API 21
        //
    } else {
        //
    }

Following single line of code is enough, everything will take care by ContextCompat.getDrawable

ContextCompat.getDrawable(this, R.drawable.your_drawable_file)

TypeLoadException says 'no implementation', but it is implemented

I encountered this error in a context where I was using Autofac and a lot of dynamic assembly loading.

While performing an Autofac resolution operation, the runtime would fail to load one of the assemblies. The error message complained that Method 'MyMethod' in type 'MyType' from assembly 'ImplementationAssembly' does not have an implementation. The symptoms occurred when running on a Windows Server 2012 R2 VM, but did not occur on Windows 10 or Windows Server 2016 VMs.

ImplementationAssembly referenced System.Collections.Immutable 1.1.37, and contained implementations of a IMyInterface<T1,T2> interface, which was defined in a separate DefinitionAssembly. DefinitionAssembly referenced System.Collections.Immutable 1.1.36.

The methods from IMyInterface<T1,T2> which were "not implemented" had parameters of type IImmutableDictionary<TKey, TRow>, which is defined in System.Collections.Immutable.

The actual copy of System.Collections.Immutable found in the program directory was version 1.1.37. On my Windows Server 2012 R2 VM, the GAC contained a copy of System.Collections.Immutable 1.1.36. On Windows 10 and Windows Server 2016, the GAC contained a copy of System.Collections.Immutable 1.1.37. The loading error only occurred when the GAC contained the older version of the DLL.

So, the root cause of the assembly load failure was the mismatching references to System.Collections.Immutable. The interface definition and implementation had identical-looking method signatures, but actually depended on different versions of System.Collections.Immutable, which meant that the runtime did not consider the implementation class to match the interface definition.

Adding the following binding redirect to my application config file fixed the issue:

<dependentAssembly>
        <assemblyIdentity name="System.Collections.Immutable" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.1.37.0" newVersion="1.1.37.0" />
</dependentAssembly>

Chrome hangs after certain amount of data transfered - waiting for available socket

Our first thought is that the site is down or the like, but the truth is that this is not the problem or disability. Nor is it a problem because a simple connection when tested under Firefox, Opera or services Explorer open as normal.

The error in Chrome displays a sign that says "This site is not available" and clarification with the legend "Error 15 (net :: ERR_SOCKET_NOT_CONNECTED): Unknown error". The error is quite usual in Google Chrome, more precisely in its updates, and its workaround is to restart the computer.

As partial solutions are not much we offer a tutorial for you solve the fault in less than a minute. To avoid this problem and ensure that services are normally open in Google Chrome should insert the following into the address bar: chrome: // net-internals (then give "Enter"). They then have to go to the "Socket" in the left menu and choose "Flush Socket Pools" (look at the following screenshots to guide http://www.fixotip.com/how-to-fix-error-waiting-for-available-sockets-in-google-chrome/) This has the problem solved and no longer will experience problems accessing Gmail, Google or any of the services of the Mountain View giant. I hope you found it useful and share the tutorial with whom they need or social networks: Facebook, Twitter or Google+.

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

How can I detect the touch event of an UIImageView?

Instead of making a touchable UIImageView then placing it on the navbar, you should just create a UIBarButtonItem, which you make out of a UIImageView.

First make the image view:

UIImageView *yourImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"nameOfYourImage.png"]];

Then make the barbutton item out of your image view:

UIBarButtonItem *yourBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:yourImageView];

Then add the bar button item to your navigation bar:

self.navigationItem.rightBarButtonItem = yourBarButtonItem;

Remember that this code goes into the view controller which is inside a navigation controller viewcontroller array. So basically, this "touchable image-looking bar button item" will only appear in the navigation bar when this view controller when it's being shown. When you push another view controller, this navigation bar button item will disappear.

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

It fails "when trying to execute the function manually" because you have a different 'this'. This will refer not to the thing you have in mind when invoking the method manually, but something else, probably the window object, or whatever context object you have when invoking manually.

XPath: How to select elements based on their value?

//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]

The reason why I add this answer is that I want to explain the relationship of . and text() .

The first thing is when using [], there are only two types of data:

  1. [number] to select a node from node-set
  2. [bool] to filter a node-set from node-set

In this case, the value is evaluated to boolean by function boolean(), and there is a rule:

Filters are always evaluated with respect to a context.

When you need to compare text() or . with a string "Data", it first uses string() function to transform those to string type, than gets a boolean result.

There are two important rule about string():

  1. The string() function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results.

    text() is relative path that return a node-set contains all the text node of current node(context node), like ["Data"]. When it is evaluated by string(["Data"]), it will return the first node of node-set, so you get "Data" only when there is only one text node in the node-set.

  2. If you want the string() function to concatenate all child text, you must then pass a single node instead of a node-set.

    For example, we get a node-set ['a', 'b'], you can pass there parent node to string(parent), this will return 'ab', and of cause string(.) in you case will return an concatenated string "Data".

Both way will get same result only when there is a text node.

Stopping Excel Macro executution when pressing Esc won't work

I also like to use MsgBox for debugging, and I've run into this same issue more than once. Now I always add a Cancel button to the popup, and exit the macro if Cancel is pressed. Example code:

    If MsgBox("Debug message", vbOKCancel, "Debugging") = vbCancel Then Exit Sub

Unbound classpath container in Eclipse

This is pretty old question and I recently came across this. Also answers says make sure that you have the correct JDK registered in Installed JRE section of Eclipse properties, and that is it. I had the correct JDK registered and that was marked as default, but still I got this error. There is one more missing piece.

Make sure the in the Installed JREs section the name of your target runtime environment is exactly as it is mentioned in your imported project. For example if the error you get is - Unbound classpath container: 'JRE System Library [JavaSE-1.8]'. Then in Installed JREs you need to have JDK 1.8 registered and its name should be the exact value mentioned in square brackets, which in this case is JavaSE-1.8.

Efficient way to apply multiple filters to pandas DataFrame or Series

e can also select rows based on values of a column that are not in a list or any iterable. We will create boolean variable just like before, but now we will negate the boolean variable by placing ~ in the front.

For example

list = [1, 0]
df[df.col1.isin(list)]

How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?

Download Microsoft Drivers for PHP for SQL Server. Extract the files and use one of:

File                             Thread Safe         VC Bulid
php_sqlsrv_53_nts_vc6.dll           No                  VC6
php_sqlsrv_53_nts_vc9.dll           No                  VC9
php_sqlsrv_53_ts_vc6.dll            Yes                 VC6
php_sqlsrv_53_ts_vc9.dll            Yes                 VC9

You can see the Thread Safety status in phpinfo().

Add the correct file to your ext directory and the following line to your php.ini:

extension=php_sqlsrv_53_*_vc*.dll

Use the filename of the file you used.

As Gordon already posted this is the new Extension from Microsoft and uses the sqlsrv_* API instead of mssql_*

Update:
On Linux you do not have the requisite drivers and neither the SQLSERV Extension.
Look at Connect to MS SQL Server from PHP on Linux? for a discussion on this.

In short you need to install FreeTDS and YES you need to use mssql_* functions on linux. see update 2

To simplify things in the long run I would recommend creating a wrapper class with requisite functions which use the appropriate API (sqlsrv_* or mssql_*) based on which extension is loaded.

Update 2: You do not need to use mssql_* functions on linux. You can connect to an ms sql server using PDO + ODBC + FreeTDS. On windows, the best performing method to connect is via PDO + ODBC + SQL Native Client since the PDO + SQLSRV driver can be incredibly slow.

Undefined reference to pthread_create in Linux

In Visual Studio 2019 specify -pthread in the property pages for the project under:

Linker -> Command Line -> Additional Options

Type in -pthread in the textbox.

How to define a connection string to a SQL Server 2008 database?

Standard Security
Data Source=serverName\instanceName;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

Trusted Connection
Data Source=serverName\instanceName;Initial Catalog=myDataBase;Integrated Security=SSPI;

Here's a good reference on connection strings that I keep handy: ConnectionStrings.com

How to use jquery $.post() method to submit form values

Get the value of your textboxes using val() and store them in a variable. Pass those values through $.post. In using the $.Post Submit button you can actually remove the form.

<script>

    username = $("#username").val(); 
    password = $("#password").val();

    $("#post-btn").click(function(){        
        $.post("process.php", { username:username, password:password } ,function(data){
            alert(data);
        });
    });
</script>

PHP GuzzleHttp. How to make a post request with params?

Note in Guzzle V6.0+, another source of getting the following error may be incorrect use of JSON as an array:

Passing in the "body" request option as an array to send a POST request has been deprecated. Please use the "form_params" request option to send a application/x-www-form-urlencoded request, or a the "multipart" request option to send a multipart/form-data request.

Incorrect:

$response = $client->post('http://example.com/api', [
    'body' => [
        'name' => 'Example name',
    ]
])

Correct:

$response = $client->post('http://example.com/api', [
    'json' => [
        'name' => 'Example name',
    ]
])

Correct:

$response = $client->post('http://example.com/api', [
    'headers' => ['Content-Type' => 'application/json'],
    'body' => json_encode([
        'name' => 'Example name',
    ])
])

How can I change the thickness of my <hr> tag

I suggest to use construction like

<style>
  .hr { height:0; border-top:1px solid _anycolor_; }
  .hr hr { display:none }
</style>

<div class="hr"><hr /></div>

How to check if a std::string is set or not?

The default constructor for std::string always returns an object that is set to a null string.

differences in application/json and application/x-www-form-urlencoded

The first case is telling the web server that you are posting JSON data as in:

{ Name : 'John Smith', Age: 23}

The second option is telling the web server that you will be encoding the parameters in the URL as in:

Name=John+Smith&Age=23

Format XML string to print friendly XML string

Use XmlTextWriter...

public static string PrintXML(string xml)
{
    string result = "";

    MemoryStream mStream = new MemoryStream();
    XmlTextWriter writer = new XmlTextWriter(mStream, Encoding.Unicode);
    XmlDocument document = new XmlDocument();

    try
    {
        // Load the XmlDocument with the XML.
        document.LoadXml(xml);

        writer.Formatting = Formatting.Indented;

        // Write the XML into a formatting XmlTextWriter
        document.WriteContentTo(writer);
        writer.Flush();
        mStream.Flush();

        // Have to rewind the MemoryStream in order to read
        // its contents.
        mStream.Position = 0;

        // Read MemoryStream contents into a StreamReader.
        StreamReader sReader = new StreamReader(mStream);

        // Extract the text from the StreamReader.
        string formattedXml = sReader.ReadToEnd();

        result = formattedXml;
    }
    catch (XmlException)
    {
        // Handle the exception
    }

    mStream.Close();
    writer.Close();

    return result;
}

How to do SQL Like % in Linq?

Contains is used in Linq ,Just like Like is used in SQL .

string _search="/12/";

. . .

.Where(s => s.Hierarchy.Contains(_search))

You can write your SQL script in Linq as Following :

 var result= Organizations.Join(OrganizationsHierarchy.Where(s=>s.Hierarchy.Contains("/12/")),s=>s.Id,s=>s.OrganizationsId,(org,orgH)=>new {org,orgH});

Update using LINQ to SQL

AdventureWorksDataContext db = new AdventureWorksDataContext();
db.Log = Console.Out;

// Get hte first customer record
Customer c = from cust in db.Customers select cust where id = 5;
Console.WriteLine(c.CustomerType);
c.CustomerType = 'I';
db.SubmitChanges(); // Save the changes away

Best XML Parser for PHP

I would have to say SimpleXML takes the cake because it is firstly an extension, written in C, and is very fast. But second, the parsed document takes the form of a PHP object. So you can "query" like $root->myElement.

How to install pip in CentOS 7?

Below are the steps I followed to install python34 and pip

yum update -y
yum -y install yum-utils
yum -y groupinstall development
yum -y install https://centos7.iuscommunity.org/ius-release.rpm
yum makecache
yum -y install python34u  python34u-pip
python3.6 -v
echo "alias python=/usr/bin/python3.4" >> ~/.bash_profile
source ~/.bash_profile
pip3 install --upgrade pip

# if yum install python34u-pip doesnt work, try 

curl https://bootstrap.pypa.io/get-pip.py | python