Programs & Examples On #Codebase

The term codebase, or code base, is used in software development to mean the whole collection of source code used to build a particular application or component.

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

To get this working for Calabash automated tests

There is a pull request up to fix the issue of xcode 12 not working with calabash https://github.com/calabash/run_loop/pull/757

A temporary solution is to use this WIP branch, although it is not great to have to use this as it is a draft PR. Xcode 12 support for Calabash will hopefully come in the future.

Change in your Gemfile

gem "run_loop"

to

gem 'run_loop', git: 'https://github.com/calabash/run_loop.git', branch: 'xcode_14_support'

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

Following worked on M1

ProductName:    macOS
ProductVersion: 11.2.1
BuildVersion:   20D74

% xcode-select --install

Agree the Terms and Conditions prompt, it will return following message on success.

% xcode-select: note: install requested for command line developer tools

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

It was fixed this kind of error after migrate to AndroidX

  • Go to Refactor ---> Migrate to AndroidX

How to solve npm install throwing fsevents warning on non-MAC OS?

I found the same problem and i tried all the solution mentioned above and in github. Some works only in local repository, when i push my PR in remote repositories with travic-CI or Pipelines give me the same error back. Finally i fixed it by using the npm command below.

npm audit fix --force

tsc throws `TS2307: Cannot find module` for a local file

In VS2019, the project property page, TypeScript Build tab has a setting (dropdown) for "Module System". When I changed that from "ES2015" to CommonJS, then VS2019 IDE stopped complaining that it could find neither axios nor redux-thunk (TS2307).

tsconfig.json:

{
  "compilerOptions": {
    "allowJs": true,
    "baseUrl": "src",
    "forceConsistentCasingInFileNames": true,
    "jsx": "react",
    "lib": [
      "es6",
      "dom",
      "es2015.promise"
    ],
    "module": "esnext",
    "moduleResolution": "node",
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "outDir": "build/dist",
    "rootDir": "src",
    "sourceMap": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "target": "es5",
    "skipLibCheck": true,
    "strict": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true
  },
  "exclude": [
    "build",
    "scripts",
    "acceptance-tests",
    "webpack",
    "jest",
    "src/setupTests.ts",
    "node_modules",
    "obj",
    "**/*.spec.ts"
  ],
  "include": [
    "src",
    "src/**/*.ts",
    "@types/**/*.d.ts",
    "node_modules/axios",
    "node_modules/redux-thunk"
  ]
}

How to convert an Image to base64 string in java?

this did it for me. you can vary the options for the output format to Base64.Default whatsoever.

// encode base64 from image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
encodedString = Base64.encodeToString(b, Base64.URL_SAFE | Base64.NO_WRAP);

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

jus do this import { shallow, mount } from "enzyme";

const store = mockStore({
  startup: { complete: false }
});

describe("==== Testing App ======", () => {
  const setUpFn = props => {
    return mount(
      <Provider store={store}>
        <App />
      </Provider>
    );
  };

  let wrapper;
  beforeEach(() => {
    wrapper = setUpFn();
  });

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

@Eddie Loeffen's answer seems to be the most popular answer to this question, but it has some bad long term effects. If you review the documentation page for System.Net.ServicePointManager.SecurityProtocol here the remarks section implies that the negotiation phase should just address this (and forcing the protocol is bad practice because in the future, TLS 1.2 will be compromised as well). However, we wouldn't be looking for this answer if it did.

Researching, it appears that the ALPN negotiation protocol is required to get to TLS1.2 in the negotiation phase. We took that as our starting point and tried newer versions of the .Net framework to see where support starts. We found that .Net 4.5.2 does not support negotiation to TLS 1.2, but .Net 4.6 does.

So, even though forcing TLS1.2 will get the job done now, I recommend that you upgrade to .Net 4.6 instead. Since this is a PCI DSS issue for June 2016, the window is short, but the new framework is a better answer.

UPDATE: Working from the comments, I built this:

ServicePointManager.SecurityProtocol = 0;    
foreach (SecurityProtocolType protocol in SecurityProtocolType.GetValues(typeof(SecurityProtocolType)))
    {
        switch (protocol)
        {
            case SecurityProtocolType.Ssl3:
            case SecurityProtocolType.Tls:
            case SecurityProtocolType.Tls11:
                break;
            default:
                ServicePointManager.SecurityProtocol |= protocol;
            break;
        }
    }

In order to validate the concept, I or'd together SSL3 and TLS1.2 and ran the code targeting a server that supports only TLS 1.0 and TLS 1.2 (1.1 is disabled). With the or'd protocols, it seems to connect fine. If I change to SSL3 and TLS 1.1, that failed to connect. My validation uses HttpWebRequest from System.Net and just calls GetResponse(). For instance, I tried this and failed:

        HttpWebRequest request = WebRequest.Create("https://www.contoso.com/my/web/resource") as HttpWebRequest;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11;
        request.GetResponse();

while this worked:

        HttpWebRequest request = WebRequest.Create("https://www.contoso.com/my/web/resource") as HttpWebRequest;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
        request.GetResponse();

This has an advantage over forcing TLS 1.2 in that, if the .Net framework is upgraded so that there are more entries in the Enum, they will be supported by the code as is. It has a disadvantage over just using .Net 4.6 in that 4.6 uses ALPN and should support new protocols if no restriction is specified.

Edit 4/29/2019 - Microsoft published this article last October. It has a pretty good synopsis of their recommendation of how this should be done in the various versions of .net framework.

Importing CommonCrypto in a Swift framework

I found a GitHub project that successfully uses CommonCrypto in a Swift framework: SHA256-Swift. Also, this article about the same problem with sqlite3 was useful.

Based on the above, the steps are:

1) Create a CommonCrypto directory inside the project directory. Within, create a module.map file. The module map will allow us to use the CommonCrypto library as a module within Swift. Its contents are:

module CommonCrypto [system] {
    header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.0.sdk/usr/include/CommonCrypto/CommonCrypto.h"
    link "CommonCrypto"
    export *
}

2) In Build Settings, within Swift Compiler - Search Paths, add the CommonCrypto directory to Import Paths (SWIFT_INCLUDE_PATHS).

Build Settings

3) Finally, import CommonCrypto inside your Swift files as any other modules. For example:

import CommonCrypto

extension String {

    func hnk_MD5String() -> String {
        if let data = self.dataUsingEncoding(NSUTF8StringEncoding)
        {
            let result = NSMutableData(length: Int(CC_MD5_DIGEST_LENGTH))
            let resultBytes = UnsafeMutablePointer<CUnsignedChar>(result.mutableBytes)
            CC_MD5(data.bytes, CC_LONG(data.length), resultBytes)
            let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, length: result.length)
            let MD5 = NSMutableString()
            for c in resultEnumerator {
                MD5.appendFormat("%02x", c)
            }
            return MD5
        }
        return ""
    }
}

Limitations

Using the custom framework in another project fails at compile time with the error missing required module 'CommonCrypto'. This is because the CommonCrypto module does not appear to be included with the custom framework. A workaround is to repeat step 2 (setting Import Paths) in the project that uses the framework.

The module map is not platform independent (it currently points to a specific platform, the iOS 8 Simulator). I don't know how to make the header path relative to the current platform.

Updates for iOS 8 <= We should remove the line link "CommonCrypto", to get the successful compilation.

UPDATE / EDIT

I kept getting the following build error:

ld: library not found for -lCommonCrypto for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

Unless I removed the line link "CommonCrypto" from the module.map file I created. Once I removed this line it built ok.

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

I am using Newtonsoft.Json v6.0.3, but this is what I had to do in my Web.config file:

<dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.5.0.0" newVersion="6.0.0.0" />
</dependentAssembly>

Note that even though I am using 6.0.3, I had to put in newVersion="6.0.0.0"

In my packages.config file I have:

<package id="Newtonsoft.Json" version="6.0.3" targetFramework="net45" />

Undo git stash pop that results in merge conflict

Instructions here are a little complicated so I'm going to offer something more straightforward:

  1. git reset HEAD --hard Abandon all changes to the current branch

  2. ... Perform intermediary work as necessary

  3. git stash pop Re-pop the stash again at a later date when you're ready

How to playback MKV video in web browser?

You can use this following code. work just on chrome browser.

_x000D_
_x000D_
 function failed(e) {_x000D_
   // video playback failed - show a message saying why_x000D_
   switch (e.target.error.code) {_x000D_
     case e.target.error.MEDIA_ERR_ABORTED:_x000D_
       alert('You aborted the video playback.');_x000D_
       break;_x000D_
     case e.target.error.MEDIA_ERR_NETWORK:_x000D_
       alert('A network error caused the video download to fail part-way.');_x000D_
       break;_x000D_
     case e.target.error.MEDIA_ERR_DECODE:_x000D_
       alert('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');_x000D_
       break;_x000D_
     case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:_x000D_
       alert('The video could not be loaded, either because the server or network failed or because the format is not supported.');_x000D_
       break;_x000D_
     default:_x000D_
       alert('An unknown error occurred.');_x000D_
       break;_x000D_
   }_x000D_
 }
_x000D_
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">_x000D_
_x000D_
<head>_x000D_
 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />_x000D_
 <meta name="author" content="Amin Developer!" />_x000D_
_x000D_
 <title>Untitled 1</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<p><video src="http://jell.yfish.us/media/Jellyfish-3-Mbps.mkv" type='video/x-matroska; codecs="theora, vorbis"' autoplay controls onerror="failed(event)" ></video></p>_x000D_
<p><a href="YOU mkv FILE LINK GOES HERE TO DOWNLOAD">Download the video file</a>.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Write Base64-encoded image to file

No need to use BufferedImage, as you already have the image file in a byte array

    byte dearr[] = Base64.decodeBase64(crntImage);
    FileOutputStream fos = new FileOutputStream(new File("c:/decode/abc.bmp")); 
    fos.write(dearr); 
    fos.close();

How do I integrate Ajax with Django applications?

When we use Django:

Server ===> Client(Browser)   
      Send a page

When you click button and send the form,
----------------------------
Server <=== Client(Browser)  
      Give data back. (data in form will be lost)
Server ===> Client(Browser)  
      Send a page after doing sth with these data
----------------------------

If you want to keep old data, you can do it without Ajax. (Page will be refreshed)

Server ===> Client(Browser)   
      Send a page
Server <=== Client(Browser)  
      Give data back. (data in form will be lost)
Server ===> Client(Browser)  
      1. Send a page after doing sth with data
      2. Insert data into form and make it like before. 
      After these thing, server will send a html page to client. It means that server do more work, however, the way to work is same.

Or you can do with Ajax (Page will be not refreshed)

--------------------------
<Initialization> 
Server ===> Client(Browser) [from URL1]    
      Give a page                      
--------------------------  
<Communication>
Server <=== Client(Browser)     
      Give data struct back but not to refresh the page.
Server ===> Client(Browser) [from URL2] 
      Give a data struct(such as JSON)
---------------------------------

If you use Ajax, you must do these:

  1. Initial a HTML page using URL1 (we usually initial page by Django template). And then server send client a html page.
  2. Use Ajax to communicate with server using URL2. And then server send client a data struct.

Django is different from Ajax. The reason for this is as follows:

  • The thing return to client is different. The case of Django is HTML page. The case of Ajax is data struct.
  • Django is good at creating something, but it only can create once, it cannot change anything. Django is like anime, consist of many picture. By contrast, Ajax is not good at creating sth but good at change sth in exist html page.

In my opinion, if you would like to use ajax everywhere. when you need to initial a page with data at first, you can use Django with Ajax. But in some case, you just need a static page without anything from server, you need not use Django template.

If you don't think Ajax is the best practice. you can use Django template to do everything, like anime.

(My English is not good)

Dynamic Web Module 3.0 -- 3.1

1) Go to your project and find ".settings" directory this one
2) Open file xml named:
org.eclipse.wst.common.project.facet.core.xml
3)

<?xml version="1.0" encoding="UTF-8"?>
    <faceted-project>
    <fixed facet="wst.jsdt.web"/>
    <installed facet="java" version="1.5"/>
    <installed facet="jst.web" version="2.3"/>
    <installed facet="wst.jsdt.web" version="1.0"/>
 </faceted-project>

Change jst.web version to 3.0 and java version to 1.7 or 1.8 (base on your current using jdk version)

4) Change your web.xml file under WEB-INF directory , please refer to this article:
https://www.mkyong.com/web-development/the-web-xml-deployment-descriptor-examples/
5) Go to pom.xml file and paste these lines:

<build>
    <finalName>YOUR_PROJECT_NAME</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <source>1.8</source> THIS IS YOUR USING JDK's VERSION
                <target>1.8</target> SAME AS ABOVE
            </configuration>
        </plugin>
    </plugins>
</build>  

Exception of type 'System.OutOfMemoryException' was thrown.

Another thing to try is

Tools -> Options -> search for IIS -> tick Use the 64 bit version of IIS Express for web sites and projects.

Use the 64 bit version of IIS Express for web sites and projects screenshot

PHP parse/syntax errors; and how to solve them

Unexpected T_STRING

T_STRING is a bit of a misnomer. It does not refer to a quoted "string". It means a raw identifier was encountered. This can range from bare words to leftover CONSTANT or function names, forgotten unquoted strings, or any plain text.

  1. Misquoted strings

    This syntax error is most common for misquoted string values however. Any unescaped and stray " or ' quote will form an invalid expression:

                   ?                  ?
     echo "<a href="http://example.com">click here</a>";
    

    Syntax highlighting will make such mistakes super obvious. It's important to remember to use backslashes for escaping \" double quotes, or \' single quotes - depending on which was used as string enclosure.

    • For convenience you should prefer outer single quotes when outputting plain HTML with double quotes within.
    • Use double quoted strings if you want to interpolate variables, but then watch out for escaping literal " double quotes.
    • For lengthier output, prefer multiple echo/print lines instead of escaping in and out. Better yet consider a HEREDOC section.


    Another example is using PHP entry inside HTML code generated with PHP:

    $text = '<div>some text with <?php echo 'some php entry' ?></div>'
    

    This happens if $text is large with many lines and developer does not see the whole PHP variable value and focus on the piece of code forgetting about its source. Example is here

    See also What is the difference between single-quoted and double-quoted strings in PHP?.

  2. Unclosed strings

    If you miss a closing " then a syntax error typically materializes later. An unterminated string will often consume a bit of code until the next intended string value:

                                                           ?
    echo "Some text", $a_variable, "and some runaway string ;
    success("finished");
             ?
    

    It's not just literal T_STRINGs which the parser may protest then. Another frequent variation is an Unexpected '>' for unquoted literal HTML.

  3. Non-programming string quotes

    If you copy and paste code from a blog or website, you sometimes end up with invalid code. Typographic quotes aren't what PHP expects:

    $text = ’Something something..’ + ”these ain't quotes”;
    

    Typographic/smart quotes are Unicode symbols. PHP treats them as part of adjoining alphanumeric text. For example ”these is interpreted as a constant identifier. But any following text literal is then seen as a bareword/T_STRING by the parser.

  4. The missing semicolon; again

    If you have an unterminated expression in previous lines, then any following statement or language construct gets seen as raw identifier:

           ?
    func1()
    function2();
    

    PHP just can't know if you meant to run two functions after another, or if you meant to multiply their results, add them, compare them, or only run one || or the other.

  5. Short open tags and <?xml headers in PHP scripts

    This is rather uncommon. But if short_open_tags are enabled, then you can't begin your PHP scripts with an XML declaration:

          ?
    <?xml version="1.0"?>
    

    PHP will see the <? and reclaim it for itself. It won't understand what the stray xml was meant for. It'll get interpreted as constant. But the version will be seen as another literal/constant. And since the parser can't make sense of two subsequent literals/values without an expression operator in between, that'll be a parser failure.

  6. Invisible Unicode characters

    A most hideous cause for syntax errors are Unicode symbols, such as the non-breaking space. PHP allows Unicode characters as identifier names. If you get a T_STRING parser complaint for wholly unsuspicious code like:

    <?php
        print 123;
    

    You need to break out another text editor. Or an hexeditor even. What looks like plain spaces and newlines here, may contain invisible constants. Java-based IDEs are sometimes oblivious to an UTF-8 BOM mangled within, zero-width spaces, paragraph separators, etc. Try to reedit everything, remove whitespace and add normal spaces back in.

    You can narrow it down with with adding redundant ; statement separators at each line start:

    <?php
        ;print 123;
    

    The extra ; semicolon here will convert the preceding invisible character into an undefined constant reference (expression as statement). Which in return makes PHP produce a helpful notice.

  7. The `$` sign missing in front of variable names

    Variables in PHP are represented by a dollar sign followed by the name of the variable.

    The dollar sign ($) is a sigil that marks the identifier as a name of a variable. Without this sigil, the identifier could be a language keyword or a constant.

    This is a common error when the PHP code was "translated" from code written in another language (C, Java, JavaScript, etc.). In such cases, a declaration of the variable type (when the original code was written in a language that uses typed variables) could also sneak out and produce this error.

  8. Escaped Quotation marks

    If you use \ in a string, it has a special meaning. This is called an "Escape Character" and normally tells the parser to take the next character literally.

    Example: echo 'Jim said \'Hello\''; will print Jim said 'hello'

    If you escape the closing quote of a string, the closing quote will be taken literally and not as intended, i.e. as a printable quote as part of the string and not close the string. This will show as a parse error commonly after you open the next string or at the end of the script.

    Very common error when specifiying paths in Windows: "C:\xampp\htdocs\" is wrong. You need "C:\\xampp\\htdocs\\".

  9. Typed properties

    You need PHP =7.4 to use property typing such as:

    public stdClass $obj;
    

Is it possible to run a .NET 4.5 app on XP?

Try mono:

http://www.go-mono.com/mono-downloads/download.html

This download works on all versions of Windows XP, 2003, Vista and Windows 7.

Can I delete a git commit but keep the changes?

I think you are looking for this

git reset --soft HEAD~1

It undoes the most recent commit whilst keeping the changes made in that commit to staging.

Running Python on Windows for Node.js dependencies

Why not downloading the python installer here ? It make the work for you when you check the path installation

What is two way binding?

Actually emberjs supports two-way binding, which is one of the most powerful feature for a javascript MVC framework. You can check it out where it mentioning binding in its user guide.

for emberjs, to create two way binding is by creating a new property with the string Binding at the end, then specifying a path from the global scope:

App.wife = Ember.Object.create({
  householdIncome: 80000
});

App.husband = Ember.Object.create({
  householdIncomeBinding: 'App.wife.householdIncome'
});

App.husband.get('householdIncome'); // 80000

// Someone gets raise.
App.husband.set('householdIncome', 90000);
App.wife.get('householdIncome'); // 90000

Note that bindings don't update immediately. Ember waits until all of your application code has finished running before synchronizing changes, so you can change a bound property as many times as you'd like without worrying about the overhead of syncing bindings when values are transient.

Hope it helps in extend of original answer selected.

The module was expected to contain an assembly manifest

First try to open the file with a decompiler such as ILSpy, your dll might be corrupt. I had this error on an online web site, when I downloaded the dll and tried to open it, it was corrupt, probably some error occurred while uploading it via ftp.

Load RSA public key from file

This program is doing almost everything with Public and private keys. The der format can be obtained but saving raw data ( without encoding base64). I hope this helps programmers.

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import sun.security.pkcs.PKCS8Key;
import sun.security.pkcs10.PKCS10;
import sun.security.x509.X500Name;

import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;



/**
 * @author Desphilboy
 * DorOd bar shomA barobach
 *
 */
public class csrgenerator {

    private static PublicKey publickey= null;
    private static PrivateKey privateKey=null;
    //private static PKCS8Key privateKey=null;
    private static KeyPairGenerator kpg= null;
    private static ByteArrayOutputStream bs =null;
    private static csrgenerator thisinstance;
    private KeyPair keypair;
    private static PKCS10 pkcs10;
    private String signaturealgorithm= "MD5WithRSA";

    public String getSignaturealgorithm() {
        return signaturealgorithm;
    }



    public void setSignaturealgorithm(String signaturealgorithm) {
        this.signaturealgorithm = signaturealgorithm;
    }



    private csrgenerator() {
        try {
           kpg = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            System.out.print("No such algorithm RSA in constructor csrgenerator\n");
        }
        kpg.initialize(2048);
        keypair = kpg.generateKeyPair();
        publickey = keypair.getPublic();
        privateKey = keypair.getPrivate();
    }



    /** Generates a new key pair 
    *
    * @param int bits 
    *   this is the number of bits in modulus must be 512, 1024, 2048  or so on 
    */
    public KeyPair generateRSAkys(int bits)
    {
          kpg.initialize(bits);
            keypair = kpg.generateKeyPair();
            publickey = keypair.getPublic();
            privateKey = keypair.getPrivate();
            KeyPair dup= keypair;
     return dup;
    }

     public static csrgenerator getInstance() {
            if (thisinstance == null)
                thisinstance = new csrgenerator();
            return thisinstance;
        }


     /**
      *  Returns a CSR as string  
      * @param cn  Common Name
      * @param OU  Organizational Unit 
      * @param Org  Organization
      * @param LocName Location name
      * @param Statename  State/Territory/Province/Region
      * @param Country    Country
      * @return     returns  csr as string.
      * @throws Exception
      */
     public String getCSR(String commonname, String organizationunit, String organization,String localname, String statename, String country ) throws Exception {
            byte[] csr = generatePKCS10(commonname, organizationunit, organization, localname, statename, country,signaturealgorithm);
            return new String(csr);
        }

     /** This function generates a new Certificate 
      * Signing Request. 
     *
     * @param CN
     *            Common Name, is X.509 speak for the name that distinguishes
     *            the Certificate best, and ties it to your Organization
     * @param OU
     *            Organizational unit
     * @param O
     *            Organization NAME
     * @param L
     *            Location
     * @param S
     *            State
     * @param C
     *            Country
     * @return    byte stream of generated request
     * @throws Exception
     */
    private static byte[] generatePKCS10(String CN, String OU, String O,String L, String S, String C,String sigAlg) throws Exception {
        // generate PKCS10 certificate request

        pkcs10 = new PKCS10(publickey);
       Signature   signature = Signature.getInstance(sigAlg);
        signature.initSign(privateKey);
        // common, orgUnit, org, locality, state, country
        //X500Name(String commonName, String organizationUnit,String organizationName,Local,State, String country)
        X500Name x500Name = new X500Name(CN, OU, O, L, S, C);
        pkcs10.encodeAndSign(x500Name,signature);
        bs = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bs);
        pkcs10.print(ps);
        byte[] c = bs.toByteArray();
        try {
            if (ps != null)
                ps.close();
            if (bs != null)
                bs.close();
        } catch (Throwable th) {
        }
        return c;
    }

    public  PublicKey getPublicKey() {
        return publickey;
    }




    /**
     * @return
     */
    public PrivateKey getPrivateKey() {
        return privateKey;
    }

    /**
     * saves private key to a file
     * @param filename
     */
    public  void SavePrivateKey(String filename)
    {
        PKCS8EncodedKeySpec pemcontents=null;
        pemcontents= new PKCS8EncodedKeySpec( privateKey.getEncoded());
        PKCS8Key pemprivatekey= new  PKCS8Key( );
        try {
            pemprivatekey.decode(pemcontents.getEncoded());
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        File file=new File(filename);
        try {

            file.createNewFile();
            FileOutputStream fos=new FileOutputStream(file);
            fos.write(pemprivatekey.getEncoded());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



    }



    /**
     * Saves Certificate Signing Request to a file;
     * @param filename  is a String containing full path to the file which will be created containing the CSR.
     */
    public void SaveCSR(String filename)
    {
        FileOutputStream fos=null;
        PrintStream ps=null;
        File file;
        try {

            file = new File(filename);
            file.createNewFile();
            fos = new FileOutputStream(file);
            ps= new PrintStream(fos);
        }catch (IOException e)
        {
            System.out.print("\n could not open the file "+ filename);
        }

        try {
            try {
                pkcs10.print(ps);
            } catch (SignatureException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            ps.flush();
            ps.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.print("\n cannot write to the file "+ filename);
            e.printStackTrace();

        }

        }


    /**
     * Saves both public key and private  key to file names specified
     * @param fnpub  file name of public key
     * @param fnpri  file name of private key
     * @throws IOException
     */
    public static void SaveKeyPair(String fnpub,String fnpri) throws IOException { 

// Store Public Key.
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
publickey.getEncoded());
FileOutputStream fos = new FileOutputStream(fnpub);
fos.write(x509EncodedKeySpec.getEncoded());
fos.close();

// Store Private Key.
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
fos = new FileOutputStream(fnpri);
fos.write(pkcs8EncodedKeySpec.getEncoded());
fos.close();
}


    /**
     * Reads a Private Key from a pem base64 encoded file.
     * @param filename name of the file to read.
     * @param algorithm Algorithm is usually "RSA"
     * @return returns the privatekey which is read from the file;
     * @throws Exception
     */
    public  PrivateKey getPemPrivateKey(String filename, String algorithm) throws Exception {
          File f = new File(filename);
          FileInputStream fis = new FileInputStream(f);
          DataInputStream dis = new DataInputStream(fis);
          byte[] keyBytes = new byte[(int) f.length()];
          dis.readFully(keyBytes);
          dis.close();

          String temp = new String(keyBytes);
          String privKeyPEM = temp.replace("-----BEGIN PRIVATE KEY-----", "");
          privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", "");
          //System.out.println("Private key\n"+privKeyPEM);

          BASE64Decoder b64=new BASE64Decoder();
          byte[] decoded = b64.decodeBuffer(privKeyPEM);

          PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
          KeyFactory kf = KeyFactory.getInstance(algorithm);
          return kf.generatePrivate(spec);
          }



    /**
     * Saves the private key to a pem file.
     * @param filename  name of the file to write the key into 
     * @param key the Private key to save.
     * @return  String representation of the pkcs8 object.
     * @throws Exception
     */
    public  String  SavePemPrivateKey(String filename) throws Exception {
        PrivateKey key=this.privateKey;
          File f = new File(filename);
          FileOutputStream fos = new FileOutputStream(f);
          DataOutputStream dos = new DataOutputStream(fos);


          byte[] keyBytes = key.getEncoded();
          PKCS8Key pkcs8= new PKCS8Key();
          pkcs8.decode(keyBytes);
          byte[] b=pkcs8.encode();

          BASE64Encoder b64=new BASE64Encoder();
          String  encoded = b64.encodeBuffer(b);

          encoded= "-----BEGIN PRIVATE KEY-----\r\n" + encoded + "-----END PRIVATE KEY-----";

         dos.writeBytes(encoded);
         dos.flush();
         dos.close();

          //System.out.println("Private key\n"+privKeyPEM);
        return pkcs8.toString();

          }


    /**
     * Saves a public key to a base64 encoded pem file
     * @param filename  name of the file 
     * @param key public key to be saved 
     * @return string representation of the pkcs8 object.
     * @throws Exception
     */
    public  String  SavePemPublicKey(String filename) throws Exception {
        PublicKey key=this.publickey;  
        File f = new File(filename);
          FileOutputStream fos = new FileOutputStream(f);
          DataOutputStream dos = new DataOutputStream(fos);


          byte[] keyBytes = key.getEncoded();
          BASE64Encoder b64=new BASE64Encoder();
          String  encoded = b64.encodeBuffer(keyBytes);

          encoded= "-----BEGIN PUBLIC KEY-----\r\n" + encoded + "-----END PUBLIC KEY-----";

         dos.writeBytes(encoded);
         dos.flush();
         dos.close();

          //System.out.println("Private key\n"+privKeyPEM);
      return  encoded.toString();

          }





       /**
     * reads a public key from a file
     * @param filename name of the file to read
     * @param algorithm is usually RSA
     * @return the read public key
     * @throws Exception
     */
    public  PublicKey getPemPublicKey(String filename, String algorithm) throws Exception {
          File f = new File(filename);
          FileInputStream fis = new FileInputStream(f);
          DataInputStream dis = new DataInputStream(fis);
          byte[] keyBytes = new byte[(int) f.length()];
          dis.readFully(keyBytes);
          dis.close();

          String temp = new String(keyBytes);
          String publicKeyPEM = temp.replace("-----BEGIN PUBLIC KEY-----\n", "");
          publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");


          BASE64Decoder b64=new BASE64Decoder();
          byte[] decoded = b64.decodeBuffer(publicKeyPEM);

          X509EncodedKeySpec spec =
                new X509EncodedKeySpec(decoded);
          KeyFactory kf = KeyFactory.getInstance(algorithm);
          return kf.generatePublic(spec);
          }




    public static void main(String[] args) throws Exception {
        csrgenerator gcsr = csrgenerator.getInstance();
        gcsr.setSignaturealgorithm("SHA512WithRSA");
        System.out.println("Public Key:\n"+gcsr.getPublicKey().toString());

        System.out.println("Private Key:\nAlgorithm: "+gcsr.getPrivateKey().getAlgorithm().toString());
        System.out.println("Format:"+gcsr.getPrivateKey().getFormat().toString());
        System.out.println("To String :"+gcsr.getPrivateKey().toString());
        System.out.println("GetEncoded :"+gcsr.getPrivateKey().getEncoded().toString());
        BASE64Encoder encoder= new BASE64Encoder();
        String s=encoder.encodeBuffer(gcsr.getPrivateKey().getEncoded());
        System.out.println("Base64:"+s+"\n");

        String csr = gcsr.getCSR( "[email protected]","baxshi az xodam", "Xodam","PointCook","VIC" ,"AU");
        System.out.println("CSR Request Generated!!");
        System.out.println(csr);
        gcsr.SaveCSR("c:\\testdir\\javacsr.csr");
        String p=gcsr.SavePemPrivateKey("c:\\testdir\\java_private.pem");
        System.out.print(p);
        p=gcsr.SavePemPublicKey("c:\\testdir\\java_public.pem");
        privateKey= gcsr.getPemPrivateKey("c:\\testdir\\java_private.pem", "RSA");
        BASE64Encoder encoder1= new BASE64Encoder();
        String s1=encoder1.encodeBuffer(gcsr.getPrivateKey().getEncoded());
        System.out.println("Private Key in Base64:"+s1+"\n");
        System.out.print(p);


    }

    }

Convert between UIImage and Base64 string

See my class -  AppExtension.swift


// MARK: - UIImage (Base64 Encoding)

public enum ImageFormat {
    case PNG
    case JPEG(CGFloat)
}

extension UIImage {

    public func base64(format: ImageFormat) -> String {
        var imageData: NSData
        switch format {
        case .PNG: imageData = UIImagePNGRepresentation(self)
        case .JPEG(let compression): imageData = UIImageJPEGRepresentation(self, compression)
        }
        return imageData.base64EncodedStringWithOptions(.allZeros)
    }
}

Backporting Python 3 open(encoding="utf-8") to Python 2

This may do the trick:

import sys
if sys.version_info[0] > 2:
    # py3k
    pass
else:
    # py2
    import codecs
    import warnings
    def open(file, mode='r', buffering=-1, encoding=None,
             errors=None, newline=None, closefd=True, opener=None):
        if newline is not None:
            warnings.warn('newline is not supported in py2')
        if not closefd:
            warnings.warn('closefd is not supported in py2')
        if opener is not None:
            warnings.warn('opener is not supported in py2')
        return codecs.open(filename=file, mode=mode, encoding=encoding,
                    errors=errors, buffering=buffering)

Then you can keep you code in the python3 way.

Note that some APIs like newline, closefd, opener do not work

What is a C++ delegate?

An option for delegates in C++ that is not otherwise mentioned here is to do it C style using a function ptr and a context argument. This is probably the same pattern that many asking this question are trying to avoid. But, the pattern is portable, efficient, and is usable in embedded and kernel code.

class SomeClass
{
    in someMember;
    int SomeFunc( int);

    static void EventFunc( void* this__, int a, int b, int c)
    {
        SomeClass* this_ = static_cast< SomeClass*>( this__);

        this_->SomeFunc( a );
        this_->someMember = b + c;
    }
};

void ScheduleEvent( void (*delegateFunc)( void*, int, int, int), void* delegateContext);

    ...
    SomeClass* someObject = new SomeObject();
    ...
    ScheduleEvent( SomeClass::EventFunc, someObject);
    ...

Call An Asynchronous Javascript Function Synchronously

You can also convert it into callbacks.

function thirdPartyFoo(callback) {    
  callback("Hello World");    
}

function foo() {    
  var fooVariable;

  thirdPartyFoo(function(data) {
    fooVariable = data;
  });

  return fooVariable;
}

var temp = foo();  
console.log(temp);

How to purge tomcat's cache when deploying a new .war file? Is there a config setting?

You can delete the "work" directory.

Are you sure it's not a browser caching issue?

Copy to Clipboard for all Browsers using javascript

For security reasons most browsers do not allow to modify the clipboard (except IE, of course...).

The only way to make a copy-to-clipboard function cross-browser compatible is to use Flash.

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

That method was introduced in Commons Codec 1.4. This exception indicates that you've an older version of Commons Codec somewhere else in the webapp's runtime classpath which got precedence in classloading. Check all paths covered by the webapp's runtime classpath. This includes among others the Webapp/WEB-INF/lib, YourAppServer/lib, JRE/lib and JRE/lib/ext. Finally remove or upgrade the offending older version.


Update: as per the comments, you can't seem to locate it. I can only suggest to outcomment the code using that newer method and then put the following line in place:

System.out.println(Base64.class.getProtectionDomain().getCodeSource().getLocation());

That should print the absolute path to the JAR file where it was been loaded from during runtime.


Update 2: this did seem to point to the right file. Sorry, I can't explain your problem anymore right now. All I can suggest is to use a different Base64 method like encodeBase64(byte[]) and then just construct a new String(bytes) yourself. Or you could drop that library and use a different Base64 encoder, for example this one.

Undoing accidental git stash pop

Try using How to recover a dropped stash in Git? to find the stash you popped. I think there are always two commits for a stash, since it preserves the index and the working copy (so often the index commit will be empty). Then git show them to see the diff and use patch -R to unapply them.

Best way to get application folder path

  1. Application.StartupPathand 7. System.IO.Path.GetDirectoryName(Application.ExecutablePath) - Is only going to work for Windows Forms application

  2. System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location)

    Is going to give you something like: "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\Temporary ASP.NET Files\\legal-services\\e84f415e\\96c98009\\assembly\\dl3\\42aaba80\\bcf9fd83_4b63d101" which is where the page that you are running is.

  3. AppDomain.CurrentDomain.BaseDirectory for web application could be useful and will return something like "C:\\hg\\Services\\Services\\Services.Website\\" which is base directory and is quite useful.

  4. System.IO.Directory.GetCurrentDirectory() and 5. Environment.CurrentDirectory

will get you location of where the process got fired from - so for web app running in debug mode from Visual Studio something like "C:\\Program Files (x86)\\IIS Express"

  1. System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)

will get you location where .dll that is running the code is, for web app that could be "file:\\C:\\hg\\Services\\Services\\Services.Website\\bin"

Now in case of for example console app points 2-6 will be directory where .exe file is.

Hope this saves you some time.

Could not load file or assembly '***.dll' or one of its dependencies

I recently hit this issue, the app would run fine on the developer machines and select others machines but not on recently installed machines. It turned out that the machines it did work on had the Visual C++ 11 Runtime installed while the freshly installed machines didn't. Adding the Visual C++ 11 Runtime redistributable to the app installer fixed the issue...

'AND' vs '&&' as operator

Since and has lower precedence than = you can use it in condition assignment:

if ($var = true && false) // Compare true with false and assign to $var
if ($var = true and false) // Assign true to $var and compare $var to false

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

Asked and answered before...

Books on line says "COUNT ( { [ [ ALL | DISTINCT ] expression ] | * } )"

"1" is a non-null expression so it's the same as COUNT(*). The optimiser recognises it as trivial so gives the same plan. A PK is unique and non-null (in SQL Server at least) so COUNT(PK) = COUNT(*)

This is a similar myth to EXISTS (SELECT * ... or EXISTS (SELECT 1 ...

And see the ANSI 92 spec, section 6.5, General Rules, case 1

        a) If COUNT(*) is specified, then the result is the cardinality
          of T.

        b) Otherwise, let TX be the single-column table that is the
          result of applying the <value expression> to each row of T
          and eliminating null values. If one or more null values are
          eliminated, then a completion condition is raised: warning-
          null value eliminated in set function.

Java web start - Unable to load resource

Try using Janela or github to diagnose the problem.

What are the recommendations for html <base> tag?

I have found a way to use <base> and anchor based links. You can use JavaScript to keep links like #contact working as they have to. I used it in some parallax pages and it works for me.

<base href="http://www.mywebsite.com/templates/"><!--[if lte IE 6]></base><![endif]-->

...content...

<script>
var link='',pathname = window.location.href;
$('a').each(function(){
    link = $(this).attr('href');
    if(link[0]=="#"){
        $(this).attr('href', pathname + link);
    }
});
</script>

You should use at the end of the page

Why would you use String.Equals over ==?

There is practical difference between string.Equals and ==

bool result = false;

object obj = "String";    
string str2 = "String";
string str3 = typeof(string).Name;
string str4 = "String";
object obj2 = str3;

// Comparision between object obj and string str2 -- Com 1
result = string.Equals(obj, str2);// true
result = String.ReferenceEquals(obj, str2); // true
result = (obj == str2);// true

// Comparision between object obj and string str3 -- Com 2
result = string.Equals(obj, str3);// true
result = String.ReferenceEquals(obj, str3); // false
result = (obj == str3);// false

// Comparision between object obj and string str4 -- Com 3
result = string.Equals(obj, str4);// true
result = String.ReferenceEquals(obj, str4); // true
result = (obj == str4);// true

// Comparision between string str2 and string str3 -- Com 4
result = string.Equals(str2, str3);// true
result = String.ReferenceEquals(str2, str3); // false
result = (str2 == str3);// true

// Comparision between string str2 and string str4 -- Com 5
result = string.Equals(str2, str4);// true
result = String.ReferenceEquals(str2, str4); // true
result = (str2 == str4);// true

// Comparision between string str3 and string str4 -- Com 6
result = string.Equals(str3, str4);// true
result = String.ReferenceEquals(str3, str4); // false
result = (str3 == str4);// true

// Comparision between object obj and object obj2 -- Com 7
result = String.Equals(obj, obj2);// true
result = String.ReferenceEquals(obj, obj2); // false
result = (obj == obj2);// false

Adding Watch

obj     "String" {1#}   object {string}
str2    "String" {1#}   string
str3    "String" {5#}   string
str4    "String" {1#}   string
obj2    "String" {5#}   object {string}

Now look at {1#} and {5#}

obj, str2, str4 and obj2 references are same.

obj and obj2 are object type and others are string type

Conclusion:

  1. com1: result = (obj == str2);// true
    • compares object and string so performs a reference equality check
    • obj and str2 point to the same reference so the result is true
  2. com2: result = (obj == str3);// false
    • compares object and string so performs a reference equality check
    • obj and str3 point to the different references so the result is false
  3. com3: result = (obj == str4);// true
    • compares object and string so performs a reference equality check
    • obj and str4 point to the same reference so the result is true
  4. com4: result = (str2 == str3);// true
    • compares string and string so performs a string value check
    • str2 and str3 are both "String" so the result is true
  5. com5: result = (str2 == str4);// true
    • compares string and string so performs a string value check
    • str2 and str4 are both "String" so the result is true
  6. com6: result = (str3 == str4);// true
    • compares string and string so performs a string value check
    • str3 and str4 are both "String" so the result is true
  7. com7: result = (obj == obj2);// false  - compares object and object so performs a reference equality check      - obj and obj2 point to the different references so the result is false

Disable all gcc warnings

-w is the GCC-wide option to disable warning messages.

How to grep Git commit diffs or contents for a certain word?

If you want search for sensitive data in order to remove it from your git history (which is the reason why I landed here), there are tools for that. Github as a dedicated help page for that issue.

Here is the gist of the article:

The BFG Repo-Cleaner is a faster, simpler alternative to git filter-branch for removing unwanted data. For example, to remove your file with sensitive data and leave your latest commit untouched), run:

bfg --delete-files YOUR-FILE-WITH-SENSITIVE-DATA

To replace all text listed in passwords.txt wherever it can be found in your repository's history, run:

bfg --replace-text passwords.txt

See the BFG Repo-Cleaner's documentation for full usage and download instructions.

How do you discover model attributes in Rails?

For Schema related stuff

Model.column_names         
Model.columns_hash         
Model.columns 

For instance variables/attributes in an AR object

object.attribute_names                    
object.attribute_present?          
object.attributes

For instance methods without inheritance from super class

Model.instance_methods(false)

Could not load file or assembly 'System.Data.SQLite'

In our case didn't work because our production server has missing

Microsoft Visual C++ 2010 SP1 Redistributable Package (x86)

We installed it and all work fine. The Application Pool must have Enable 32-bit Applications set to true and you must the x86 version of the library

#pragma once vs include guards?

I don't think it will make a significant difference in compile time but #pragma once is very well supported across compilers but not actually part of the standard. The preprocessor may be a little faster with it as it is more simple to understand your exact intent.

#pragma once is less prone to making mistakes and it is less code to type.

To speed up compile time more just forward declare instead of including in .h files when you can.

I prefer to use #pragma once.

See this wikipedia article about the possibility of using both.

XmlSerializer giving FileNotFoundException at constructor

I had the same problem until I used a 3rd Party tool to generate the Class from the XSD and it worked! I discovered that the tool was adding some extra code at the top of my class. When I added this same code to the top of my original class it worked. Here's what I added...

#pragma warning disable
namespace MyNamespace
{
  using System;
  using System.Diagnostics;
  using System.Xml.Serialization;
  using System.Collections;
  using System.Xml.Schema;
  using System.ComponentModel;
  using System.Xml;
  using System.Collections.Generic;

  [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.1064.2")]
  [System.SerializableAttribute()]
  [System.Diagnostics.DebuggerStepThroughAttribute()]
  [System.ComponentModel.DesignerCategoryAttribute("code")]
  [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
  [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
  public partial class MyClassName
  {
  ...

What does void mean in C, C++, and C#?

If you're explaining the concept to a beginner, it might be helpful to use an analogy. The use of void in all these cases is analogous in meaning to a page in a book which has the following words, "This page left intentionally blank." It is to differentiate to the compiler between something which should be flagged as an error, versus a type which is intentionally to be left blank because that is the behavior you want.

It always appears in code where normally you would expect to see a type appear, such as a return type or a pointer type. This is why in C#, void maps to an actual CLR type, System.Void because it is a type in itself.

Some programming languages never developed the concept of void, just like some human cultures never invented the concept of the number zero. Void represents the same advancement in a programming language as the concept of zero represents to human language.

How do I solve this error, "error while trying to deserialize parameter"

I have a solution for this but not sure on the reason why this would be different from one environment to the other - although one big difference between the two environments is WSS svc pack 1 was installed on the environment where the error was occurring.

To fix this issue I got a good clue from this link - http://silverlight.net/forums/t/22787.aspx ie to "please check the Xml Schema of your service" and "the sequence in the schema is sorted alphabetically"

Looking at the wsdl generated I noticed that for the serialized class that was causing the error, the properties of this class were not visible in the wsdl.

The Definition of the class had private setters for most of the properties, but not for CustomFields property ie..

[Serializable]
public class FileMetaDataDto
{
    .
    . a constructor...   etc and several other properties edited for brevity
    . 

    public int Id { get; private set; }
    public string Version { get; private set; }
    public List<MetaDataValueDto> CustomFields { get; set; }

}

On removing private from the setter and redeploying the service then looking at the wsdl again, these properties were now visible, and the original error was fixed.

So the wsdl before update was

- <s:complexType name="ArrayOfFileMetaDataDto">
- <s:sequence>
  <s:element minOccurs="0" maxOccurs="unbounded" name="FileMetaDataDto" nillable="true" type="tns:FileMetaDataDto" /> 
  </s:sequence>
  </s:complexType>
- <s:complexType name="FileMetaDataDto">
- <s:sequence>
  <s:element minOccurs="0" maxOccurs="1" name="CustomFields" type="tns:ArrayOfMetaDataValueDto" /> 
  </s:sequence>
  </s:complexType>

The wsdl after update was

- <s:complexType name="ArrayOfFileMetaDataDto">
- <s:sequence>
  <s:element minOccurs="0" maxOccurs="unbounded" name="FileMetaDataDto" nillable="true" type="tns:FileMetaDataDto" /> 
  </s:sequence>
  </s:complexType>
- <s:complexType name="FileMetaDataDto">
- <s:sequence>
  <s:element minOccurs="1" maxOccurs="1" name="Id" type="s:int" /> 
  <s:element minOccurs="0" maxOccurs="1" name="Name" type="s:string" /> 
  <s:element minOccurs="0" maxOccurs="1" name="Title" type="s:string" /> 
  <s:element minOccurs="0" maxOccurs="1" name="ContentType" type="s:string" /> 
  <s:element minOccurs="0" maxOccurs="1" name="Icon" type="s:string" /> 
  <s:element minOccurs="0" maxOccurs="1" name="ModifiedBy" type="s:string" /> 
  <s:element minOccurs="1" maxOccurs="1" name="ModifiedDateTime" type="s:dateTime" /> 
  <s:element minOccurs="1" maxOccurs="1" name="FileSizeBytes" type="s:int" /> 
  <s:element minOccurs="0" maxOccurs="1" name="Url" type="s:string" /> 
  <s:element minOccurs="0" maxOccurs="1" name="RelativeFolderPath" type="s:string" /> 
  <s:element minOccurs="0" maxOccurs="1" name="DisplayVersion" type="s:string" /> 
  <s:element minOccurs="0" maxOccurs="1" name="Version" type="s:string" /> 
  <s:element minOccurs="0" maxOccurs="1" name="CustomFields" type="tns:ArrayOfMetaDataValueDto" /> 
  <s:element minOccurs="0" maxOccurs="1" name="CheckoutBy" type="s:string" /> 
  </s:sequence>
  </s:complexType>

Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

There second method will be many times more effective (mostly because of compilers inlining and boxing but still numbers are very expressive):

public static bool CheckObjectImpl(object o)
{
    return o != null;
}

public static bool CheckNullableImpl<T>(T? o) where T: struct
{
    return o.HasValue;
}

Benchmark test:

BenchmarkDotNet=v0.10.5, OS=Windows 10.0.14393
Processor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4
Frequency=3233539 Hz, Resolution=309.2587 ns, Timer=TSC
  [Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0
  Clr    : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0
  Core   : .NET Core 4.6.25009.03, 64bit RyuJIT


        Method |  Job | Runtime |       Mean |     Error |    StdDev |        Min |        Max |     Median | Rank |  Gen 0 | Allocated |
-------------- |----- |-------- |-----------:|----------:|----------:|-----------:|-----------:|-----------:|-----:|-------:|----------:|
   CheckObject |  Clr |     Clr | 80.6416 ns | 1.1983 ns | 1.0622 ns | 79.5528 ns | 83.0417 ns | 80.1797 ns |    3 | 0.0060 |      24 B |
 CheckNullable |  Clr |     Clr |  0.0029 ns | 0.0088 ns | 0.0082 ns |  0.0000 ns |  0.0315 ns |  0.0000 ns |    1 |      - |       0 B |
   CheckObject | Core |    Core | 77.2614 ns | 0.5703 ns | 0.4763 ns | 76.4205 ns | 77.9400 ns | 77.3586 ns |    2 | 0.0060 |      24 B |
 CheckNullable | Core |    Core |  0.0007 ns | 0.0021 ns | 0.0016 ns |  0.0000 ns |  0.0054 ns |  0.0000 ns |    1 |      - |       0 B |

Benchmark code:

public class BenchmarkNullableCheck
{
    static int? x = (new Random()).Next();

    public static bool CheckObjectImpl(object o)
    {
        return o != null;
    }

    public static bool CheckNullableImpl<T>(T? o) where T: struct
    {
        return o.HasValue;
    }

    [Benchmark]
    public bool CheckObject()
    {
        return CheckObjectImpl(x);
    }

    [Benchmark]
    public bool CheckNullable()
    {
        return CheckNullableImpl(x);
    }
}

https://github.com/dotnet/BenchmarkDotNet was used

So if you have an option (e.g. writing custom serializers) to process Nullable in different pipeline than object - and use their specific properties - do it and use Nullable specific properties. So from consistent thinking point of view HasValue should be preferred. Consistent thinking can help you to write better code do not spending too much time in details.

PS. People say that advice "prefer HasValue because of consistent thinking" is not related and useless. Can you predict the performance of this?

public static bool CheckNullableGenericImpl<T>(T? t) where T: struct
{
    return t != null; // or t.HasValue?
}

PPS People continue minus, seems nobody tries to predict performance of CheckNullableGenericImpl. I will tell you: there compiler will not help you replacing !=null with HasValue. HasValue should be used directly if you are interested in performance.

Protect .NET code from reverse engineering?

In my experience, making your application or library more difficult to crack hurts your honest customers whilst only slightly delaying the dishonest ones. Concentrate on making a great, low friction product instead of putting a lot of effort into delaying the inevitable.

How can I selectively merge or pick changes from another branch in Git?

I had the exact same problem as mentioned by you above. But I found this Git blog clearer in explaining the answer.

Command from the above link:

# You are in the branch you want to merge to
git checkout <branch_you_want_to_merge_from> <file_paths...>

Git for beginners: The definitive practical guide

Why yet another howto? There are really good ones on the net, like the git guide which is perfect to begin. It has good links including the git book to which one can contribute (hosted on git hub) and which is perfect for this collective task.

On stackoverflow, I would really prefer to see your favorite tricks !

Mine, which I discovered only lately, is git stash, explained here, which enables you to save your current job and go to another branch

EDIT: as the previous post, if you really prefer stackoverlow format with posts as a wiki I will delete this answer

Default string initialization: NULL or Empty?

+1 for distinguishing between "empty" and NULL. I agree that "empty" should mean "valid, but blank" and "NULL" should mean "invalid."

So I'd answer your question like this:

empty when I want a valid default value that may or may not be changed, for example, a user's middle name.

NULL when it is an error if the ensuing code does not set the value explicitly.

How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC?

Any functions into which you pass string literals "I am a string literal" should use char const * as the type instead of char*.

If you're going to fix something, fix it right.

Explanation:

You can not use string literals to initialise strings that will be modified, because they are of type const char*. Casting away the constness to later modify them is undefined behaviour, so you have to copy your const char* strings char by char into dynamically allocated char* strings in order to modify them.

Example:

#include <iostream>

void print(char* ch);

void print(const char* ch) {
    std::cout<<ch;
}

int main() {
    print("Hello");
    return 0;
}

Find in Files: Search all code in Team Foundation Server

In my case, writing a small utility in C# helped. Links that helped me - http://pascallaurin42.blogspot.com/2012/05/tfs-queries-searching-in-all-files-of.html

How to list files of a team project using tfs api?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.Framework.Client;
using System.IO;

namespace TFSSearch
{
class Program
{
    static string[] textPatterns = new[] { "void main(", "exception", "RegisterScript" };  //Text to search
    static string[] filePatterns = new[] { "*.cs", "*.xml", "*.config", "*.asp", "*.aspx", "*.js", "*.htm", "*.html", 
                                           "*.vb", "*.asax", "*.ashx", "*.asmx", "*.ascx", "*.master", "*.svc"}; //file extensions

    static void Main(string[] args)
    {
        try
        {
            var tfs = TfsTeamProjectCollectionFactory
             .GetTeamProjectCollection(new Uri("http://{tfsserver}:8080/tfs/}")); // one some servers you also need to add collection path (if it not the default collection)

            tfs.EnsureAuthenticated();

            var versionControl = tfs.GetService<VersionControlServer>();


            StreamWriter outputFile = new StreamWriter(@"C:\Find.txt");
            var allProjs = versionControl.GetAllTeamProjects(true);
            foreach (var teamProj in allProjs)
            {
                foreach (var filePattern in filePatterns)
                {
                    var items = versionControl.GetItems(teamProj.ServerItem + "/" + filePattern, RecursionType.Full).Items
                                .Where(i => !i.ServerItem.Contains("_ReSharper"));  //skipping resharper stuff
                    foreach (var item in items)
                    {
                        List<string> lines = SearchInFile(item);
                        if (lines.Count > 0)
                        {
                            outputFile.WriteLine("FILE:" + item.ServerItem);
                            outputFile.WriteLine(lines.Count.ToString() + " occurence(s) found.");
                            outputFile.WriteLine();
                        }
                        foreach (string line in lines)
                        {
                            outputFile.WriteLine(line);
                        }
                        if (lines.Count > 0)
                        {
                            outputFile.WriteLine();
                        }
                    }
                }
                outputFile.Flush();
            }
        }
        catch (Exception e)
        {
            string ex = e.Message;
            Console.WriteLine("!!EXCEPTION: " + e.Message);
            Console.WriteLine("Continuing... ");
        }
        Console.WriteLine("========");
        Console.Read();
    }

    // Define other methods and classes here
    private static List<string> SearchInFile(Item file)
    {
        var result = new List<string>();

        try
        {
            var stream = new StreamReader(file.DownloadFile(), Encoding.Default);

            var line = stream.ReadLine();
            var lineIndex = 0;

            while (!stream.EndOfStream)
            {
                if (textPatterns.Any(p => line.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0))
                    result.Add("=== Line " + lineIndex + ": " + line.Trim());

                line = stream.ReadLine();
                lineIndex++;
            }
        }
        catch (Exception e)
        {
            string ex = e.Message;
            Console.WriteLine("!!EXCEPTION: " + e.Message);
            Console.WriteLine("Continuing... ");
        }

        return result;
    }
}
}

What Vim command(s) can be used to quote/unquote words?

Here's some mapping that could help:

:nnoremap <Leader>q" ciw""<Esc>P
:nnoremap <Leader>q' ciw''<Esc>P
:nnoremap <Leader>qd daW"=substitute(@@,"'\\\|\"","","g")<CR>P

If you haven't changed the mapleader variable, then activate the mapping with \q" \q' or \qd. They add double quote around the word under the cursor, single quote around the word under the cursor, delete any quotes around the word under the cursor respectively.

How can I write to the console in PHP?

function phpconsole($label='var', $x) {
    ?>
    <script type="text/javascript">
        console.log('<?php echo ($label)?>');
        console.log('<?php echo json_encode($x)?>');
    </script>
    <?php
}

How do I uniquely identify computers visiting my web site?

Introduction

I don't know if there is or ever will be a way to uniquely identify machines using a browser alone. The main reasons are:

  • You will need to save data on the users computer. This data can be deleted by the user any time. Unless you have a way to recreate this data which is unique for each and every machine then your stuck.
  • Validation. You need to guard against spoofing, session hijacking, etc.

Even if there are ways to track a computer without using cookies there will always be a way to bypass it and software that will do this automatically. If you really need to track something based on a computer you will have to write a native application (Apple Store / Android Store / Windows Program / etc).

I might not be able to give you an answer to the question you asked but I can show you how to implement session tracking. With session tracking you try to track the browsing session instead of the computer visiting your site. By tracking the session, your database schema will look like this:

sesssion:
  sessionID: string
  // Global session data goes here

  computers: [{
     BrowserID: string
     ComputerID: string
     FingerprintID: string
     userID: string
     authToken: string
     ipAddresses: ["203.525....", "203.525...", ...]
     // Computer session data goes here
  }, ...]

Advantages of session based tracking:

  1. For logged in users, you can always generate the same session id from the users username / password / email.
  2. You can still track guest users using sessionID.
  3. Even if several people use the same computer (ie cybercafe) you can track them separately if they log in.

Disadvantages of session based tracking:

  1. Sessions are browser based and not computer based. If a user uses 2 different browsers it will result in 2 different sessions. If this is a problem you can stop reading here.
  2. Sessions expire if user is not logged in. If a user is not logged in, then they will use a guest session which will be invalidated if user deletes cookies and browser cache.

Implementation

There are many ways of implementing this. I don't think I can cover them all I'll just list my favorite which would make this an opinionated answer. Bear that in mind.

Basics

I will track the session by using what is known as a forever cookie. This is data which will automagically recreate itself even if the user deletes his cookies or updates his browser. It will not however survive the user deleting both their cookies and their browsing cache.

To implement this I will use the browsers caching mechanism (RFC), WebStorage API (MDN) and browser cookies (RFC, Google Analytics).

Legal

In order to utilize tracking ids you need to add them to both your privacy policy and your terms of use preferably under the sub-heading Tracking. We will use the following keys on both document.cookie and window.localStorage:

  • _ga: Google Analytics data
  • __utma: Google Analytics tracking cookie
  • sid: SessionID

Make sure you include links to your Privacy policy and terms of use on all pages that use tracking.

Where do I store my session data?

You can either store your session data in your website database or on the users computer. Since I normally work on smaller sites (let than 10 thousand continuous connections) that use 3rd party applications (Google Analytics / Clicky / etc) it's best for me to store data on clients computer. This has the following advantages:

  1. No database lookup / overhead / load / latency / space / etc.
  2. User can delete their data whenever they want without the need to write me annoying emails.

and disadvantages:

  1. Data has to be encrypted / decrypted and signed / verified which creates cpu overhead on client (not so bad) and server (bah!).
  2. Data is deleted when user deletes their cookies and cache. (this is what I want really)
  3. Data is unavailable for analytics when users go off-line. (analytics for currently browsing users only)

UUIDS

  • BrowserID: Unique id generated from the browsers user agent string. Browser|BrowserVersion|OS|OSVersion|Processor|MozzilaMajorVersion|GeckoMajorVersion
  • ComputerID: Generated from users IP Address and HTTPS session key. getISP(requestIP)|getHTTPSClientKey()
  • FingerPrintID: JavaScript based fingerprinting based on a modified fingerprint.js. FingerPrint.get()
  • SessionID: Random key generated when user 1st visits site. BrowserID|ComputerID|randombytes(256)
  • GoogleID: Generated from __utma cookie. getCookie(__utma).uniqueid

Mechanism

The other day I was watching the wendy williams show with my girlfriend and was completely horrified when the host advised her viewers to delete their browser history at least once a month. Deleting browser history normally has the following effects:

  1. Deletes history of visited websites.
  2. Deletes cookies and window.localStorage (aww man).

Most modern browsers make this option readily available but fear not friends. For there is a solution. The browser has a caching mechanism to store scripts / images and other things. Usually even if we delete our history, this browser cache still remains. All we need is a way to store our data here. There are 2 methods of doing this. The better one is to use a SVG image and store our data inside its tags. This way data can still be extracted even if JavaScript is disabled using flash. However since that is a bit complicated I will demonstrate the other approach which uses JSONP (Wikipedia)

example.com/assets/js/tracking.js (actually tracking.php)

var now = new Date();
var window.__sid = "SessionID"; // Server generated

setCookie("sid", window.__sid, now.setFullYear(now.getFullYear() + 1, now.getMonth(), now.getDate() - 1));

if( "localStorage" in window ) {
  window.localStorage.setItem("sid", window.__sid);
}

Now we can get our session key any time:

window.__sid || window.localStorage.getItem("sid") || getCookie("sid") || ""

How do I make tracking.js stick in browser?

We can achieve this using Cache-Control, Last-Modified and ETag HTTP headers. We can use the SessionID as value for etag header:

setHeaders({
  "ETag": SessionID,
  "Last-Modified": new Date(0).toUTCString(),
  "Cache-Control": "private, max-age=31536000, s-max-age=31536000, must-revalidate"
})

Last-Modified header tells the browser that this file is basically never modified. Cache-Control tells proxies and gateways not to cache the document but tells the browser to cache it for 1 year.

The next time the browser requests the document, it will send If-Modified-Since and If-None-Match headers. We can use these to return a 304 Not Modified response.

example.com/assets/js/tracking.php

$sid = getHeader("If-None-Match") ?: getHeader("if-none-match") ?: getHeader("IF-NONE-MATCH") ?: ""; 
$ifModifiedSince = hasHeader("If-Modified-Since") ?: hasHeader("if-modified-since") ?: hasHeader("IF-MODIFIED-SINCE");

if( validateSession($sid) ) {
  if( sessionExists($sid) ) {
    continueSession($sid);
    send304();
  } else {
    startSession($sid);
    send304();
  }
} else if( $ifModifiedSince ) {
  send304();
} else {
  startSession();
  send200();
}

Now every time the browser requests tracking.js our server will respond with a 304 Not Modified result and force an execute of the local copy of tracking.js.

I still don't understand. Explain it to me

Lets suppose the user clears their browsing history and refreshes the page. The only thing left on the users computer is a copy of tracking.js in browser cache. When the browser requests tracking.js it recieves a 304 Not Modified response which causes it to execute the 1st version of tracking.js it recieved. tracking.js executes and restores the SessionID that was deleted.

Validation

Suppose Haxor X steals our customers cookies while they are still logged in. How do we protect them? Cryptography and Browser fingerprinting to the rescue. Remember our original definition for SessionID was:

BrowserID|ComputerID|randomBytes(256)

We can change this to:

Timestamp|BrowserID|ComputerID|encrypt(randomBytes(256), hk)|sign(Timestamp|BrowserID|ComputerID|randomBytes(256), hk)

Where hk = sign(Timestamp|BrowserID|ComputerID, serverKey).

Now we can validate our SessionID using the following algorithm:

if( getTimestamp($sid) is older than 1 year ) return false;
if( getBrowserID($sid) !== createBrowserID($_Request, $_Server) ) return false;
if( getComputerID($sid) !== createComputerID($_Request, $_Server) return false;

$hk = sign(getTimestamp($sid) + getBrowserID($sid) + getComputerID($sid), $SERVER["key"]);

if( !verify(getTimestamp($sid) + getBrowserID($sid) + getComputerID($sid) + decrypt(getRandomBytes($sid), hk), getSignature($sid), $hk) ) return false;

return true; 

Now in order for Haxor's attack to work they must:

  1. Have same ComputerID. That means they have to have the same ISP provider as victim (Tricky). This will give our victim the opportunity to take legal action in their own country. Haxor must also obtain HTTPS session key from victim (Hard).
  2. Have same BrowserID. Anyone can spoof User-Agent string (Annoying).
  3. Be able to create their own fake SessionID (Very Hard). Volume atacks won't work because we use a time-stamp to generate encryption / signing key so basically its like generating a new key for each session. On top of that we encrypt random bytes so a simple dictionary attack is also out of the question.

We can improve validation by forwarding GoogleID and FingerprintID (via ajax or hidden fields) and matching against those.

if( GoogleID != getStoredGoodleID($sid) ) return false;
if( byte_difference(FingerPrintID, getStoredFingerprint($sid) > 10%) return false;

How do I select last 5 rows in a table without sorting?

Without an order, this is impossible. What defines the "bottom"? The following will select 5 rows according to how they are stored in the database.

SELECT TOP 5 * FROM [TableName]

The Definitive C Book Guide and List

Beginner

Introductory, no previous programming experience

  • C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]

    * Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.

  • Programming: Principles and Practice Using C++ (Bjarne Stroustrup, 2nd Edition - May 25, 2014) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.

Introductory, with previous programming experience

  • A Tour of C++ (Bjarne Stroustrup) (2nd edition for C++17) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.

  • Accelerated C++ (Andrew Koenig and Barbara Moo, 1st Edition - August 24, 2000) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction to the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach to teaching the language.) Despite this, the C++ it teaches is purely C++98. [Review]

Best practices

  • Effective C++ (Scott Meyers, 3rd Edition - May 22, 2005) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]

  • Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.

  • Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]


Intermediate

  • More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.

  • Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]

  • More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object-oriented programming in C++ and correct use of the STL. [Review]

  • Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using non-member functions and the single responsibility principle. [Review]

  • C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]

  • C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition covering C++11, C++14 and C++17 has been already published. [Review]

  • C++ 17 - The Complete Guide (Nicolai M. Josuttis) This book describes all the new features introduced in the C++17 Standard covering everything from the simple ones like 'Inline Variables', 'constexpr if' all the way up to 'Polymorphic Memory Resources' and 'New and Delete with overaligned Data'. [Review]

  • C++ in Action (Bartosz Milewski). This book explains C++ and its features by building an application from ground up. [Review]

  • Functional Programming in C++ (Ivan Cukic). This book introduces functional programming techniques to modern C++ (C++11 and later). A very nice read for those who want to apply functional programming paradigms to C++.

  • Professional C++ (Marc Gregoire, 5th Edition - Feb 2021) Provides a comprehensive and detailed tour of the C++ language implementation replete with professional tips and concise but informative in-text examples, emphasizing C++20 features. Uses C++20 features, such as modules and std::format throughout all examples.


Advanced

  • Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multi-methods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]

  • C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)

  • C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications. A second edition covering C++14 and C++17 has been already published. [Review]

  • Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by type traits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.


Reference Style - All Levels

  • The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much like it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review] Note: All releases of the C++ standard are tracked in the question "Where do I find the current C or C++ standard documents?".

  • C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]

  • The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]

C++11/14/17/… References:

  • The C++11/14/17 Standard (INCITS/ISO/IEC 14882:2011/2014/2017) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. The C++17 standard is released in electronic form for 198 Swiss Francs.

  • The C++17 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++20.

  • Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.

  • The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.

  • The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.

  • cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.


Classics / Older

Note: Some information contained within these books may not be up-to-date or no longer considered best practice.

  • The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.

  • Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]

  • Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.

  • Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly, a good read, if it only was up to date. It was written long before C++ 98 and misses on many features (e.g. namespaces) important for large-scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is released in 2019.

  • Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.

  • The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however, this book goes through the entire C++ standard of the time explaining the rationale, the possible implementations, and features of the language. This is not a book to learn programming principles and patterns on C++, but to understand every aspect of the C++ language.

  • Thinking in C++ (Bruce Eckel, 2nd Edition, 2000). Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they're marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const), with no official errata list. A partial 3rd party errata list is available at http://www.computersciencelab.com/Eckel.htm, but it is apparently not maintained.

  • Scientific and Engineering C++: An Introduction to Advanced Techniques and Examples (John Barton and Lee Nackman) It is a comprehensive and very detailed book that tried to explain and make use of all the features available in C++, in the context of numerical methods. It introduced at the time several new techniques, such as the Curiously Recurring Template Pattern (CRTP, also called Barton-Nackman trick). It pioneered several techniques such as dimensional analysis and automatic differentiation. It came with a lot of compilable and useful code, ranging from an expression parser to a Lapack wrapper. The code is still available online. Unfortunately, the books have become somewhat outdated in the style and C++ features, however, it was an incredible tour-de-force at the time (1994, pre-STL). The chapters on dynamics inheritance are a bit complicated to understand and not very useful. An updated version of this classic book that includes move semantics and the lessons learned from the STL would be very nice.

VBA array sort function?

Take a look here:
Edit: The referenced source (allexperts.com) has since closed, but here are the relevant author comments:

There are many algorithms available on the web for sorting. The most versatile and usually the quickest is the Quicksort algorithm. Below is a function for it.

Call it simply by passing an array of values (string or numeric; it doesn't matter) with the Lower Array Boundary (usually 0) and the Upper Array Boundary (i.e. UBound(myArray).)

Example: Call QuickSort(myArray, 0, UBound(myArray))

When it's done, myArray will be sorted and you can do what you want with it.
(Source: archive.org)

Public Sub QuickSort(vArray As Variant, inLow As Long, inHi As Long)
  Dim pivot   As Variant
  Dim tmpSwap As Variant
  Dim tmpLow  As Long
  Dim tmpHi   As Long

  tmpLow = inLow
  tmpHi = inHi

  pivot = vArray((inLow + inHi) \ 2)

  While (tmpLow <= tmpHi)
     While (vArray(tmpLow) < pivot And tmpLow < inHi)
        tmpLow = tmpLow + 1
     Wend

     While (pivot < vArray(tmpHi) And tmpHi > inLow)
        tmpHi = tmpHi - 1
     Wend

     If (tmpLow <= tmpHi) Then
        tmpSwap = vArray(tmpLow)
        vArray(tmpLow) = vArray(tmpHi)
        vArray(tmpHi) = tmpSwap
        tmpLow = tmpLow + 1
        tmpHi = tmpHi - 1
     End If
  Wend

  If (inLow < tmpHi) Then QuickSort vArray, inLow, tmpHi
  If (tmpLow < inHi) Then QuickSort vArray, tmpLow, inHi
End Sub

Note that this only works with single-dimensional (aka "normal"?) arrays. (There's a working multi-dimensional array QuickSort here.)

Empty an array in Java / processing

array = new String[array.length];

How to put text over images in html?

The <img> element is empty — it doesn't have an end tag.

If the image is a background image, use CSS. If it is a content image, then set position: relative on a container, then absolutely position the image and/or text within it.

preferredStatusBarStyle isn't called

UIStatusBarStyle in iOS 7

The status bar in iOS 7 is transparent, the view behind it shows through.

The style of the status bar refers to the appearances of its content. In iOS 7, the status bar content is either dark (UIStatusBarStyleDefault) or light (UIStatusBarStyleLightContent). Both UIStatusBarStyleBlackTranslucent and UIStatusBarStyleBlackOpaque are deprecated in iOS 7.0. Use UIStatusBarStyleLightContent instead.

How to change UIStatusBarStyle

If below the status bar is a navigation bar, the status bar style will be adjusted to match the navigation bar style (UINavigationBar.barStyle):

Specifically, if the navigation bar style is UIBarStyleDefault, the status bar style will be UIStatusBarStyleDefault; if the navigation bar style is UIBarStyleBlack, the status bar style will be UIStatusBarStyleLightContent.

If there is no navigation bar below the status bar, the status bar style can be controlled and changed by an individual view controller while the app runs.

-[UIViewController preferredStatusBarStyle] is a new method added in iOS 7. It can be overridden to return the preferred status bar style:

- (UIStatusBarStyle)preferredStatusBarStyle
  {
      return UIStatusBarStyleLightContent;
  }

If the status bar style should be controlled by a child view controller instead of self, override -[UIViewController childViewControllerForStatusBarStyle] to return that child view controller.

If you prefer to opt out of this behavior and set the status bar style by using the -[UIApplication statusBarStyle] method, add the UIViewControllerBasedStatusBarAppearance key to an app’s Info.plist file and give it the value NO.

setting an environment variable in virtualenv

Locally within an virtualenv there are two methods you could use to test this. The first is a tool which is installed via the Heroku toolbelt (https://toolbelt.heroku.com/). The tool is foreman. It will export all of your environment variables that are stored in a .env file locally and then run app processes within your Procfile.

The second way if you're looking for a lighter approach is to have a .env file locally then run:

export $(cat .env)

How can I make Jenkins CI with Git trigger on pushes to master?

Instead of triggering builds remotely, change your Jenkins project configuration to trigger builds by polling.

Jenkins can poll based on a fixed internal, or by a URL. The latter is what you want to skip builds if there are not changes for that branch. The exact details are in the documentation. Essentially you just need to check the "Poll SCM" option, leave the schedule section blank, and set a remote URL to hit JENKINS_URL/job/name/polling.

One gotcha if you have a secured Jenkins environment is unlike /build, the /polling URL requires authentication. The instructions here have details. For example, I have a GitHub Post-Receive hook going to username:apiToken@JENKIS_URL/job/name/polling.

"pip install unroll": "python setup.py egg_info" failed with error code 1

I faced the same problem with the same error message but on Ubuntu 16.04 LTS (Xenial Xerus) instead:

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-w71uo1rg/poster/

I tested all the solutions provided above and none of them worked for me. I read the full TraceBack and found out I had to create the virtual environment with Python version 2.7 instead (the default one uses Python 3.5 instead):

virtualenv --python=/usr/bin/python2.7 my_venv

Once I activated it, I run pip install unirest successfully.

How to display errors for my MySQLi query?

mysqli_error()

As in:

$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);

Trigger error is better than die because you can use it for development AND production, it's the permanent solution.

How can I find out what version of git I'm running?

Or even just

git version

Results in something like

git version 1.8.3.msysgit.0

Javascript ES6 export const vs export let

I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).

The only difference would be if you try to reassign it before the end of this very file.

How to switch databases in psql?

You can connect using

\c dbname

If you would like to see all possible commands for POSTGRESQL or SQL follow this steps :

  1. rails dbconsole (You will redericted to your current ENV database)

  2. \? (For POSTGRESQL commands)

or

  1. \h (For SQL commands)

  2. Press Q to Exit

Mockito: Trying to spy on method is calling the original method

One more possible scenario which may causing issues with spies is when you're testing spring beans (with spring test framework) or some other framework that is proxing your objects during test.

Example

@Autowired
private MonitoringDocumentsRepository repository

void test(){
    repository = Mockito.spy(repository)
    Mockito.doReturn(docs1, docs2)
            .when(repository).findMonitoringDocuments(Mockito.nullable(MonitoringDocumentSearchRequest.class));
}

In above code both Spring and Mockito will try to proxy your MonitoringDocumentsRepository object, but Spring will be first, which will cause real call of findMonitoringDocuments method. If we debug our code just after putting a spy on repository object it will look like this inside debugger:

repository = MonitoringDocumentsRepository$$EnhancerBySpringCGLIB$$MockitoMock$

@SpyBean to the rescue

If instead @Autowired annotation we use @SpyBean annotation, we will solve above problem, the SpyBean annotation will also inject repository object but it will be firstly proxied by Mockito and will look like this inside debugger

repository = MonitoringDocumentsRepository$$MockitoMock$$EnhancerBySpringCGLIB$

and here is the code:

@SpyBean
private MonitoringDocumentsRepository repository

void test(){
    Mockito.doReturn(docs1, docs2)
            .when(repository).findMonitoringDocuments(Mockito.nullable(MonitoringDocumentSearchRequest.class));
}

How should I validate an e-mail address?

Try this code.. Its really works..

            if (!email
                    .matches("^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$"))
            {
                Toast.makeText(getApplicationContext(), "Email is invalid",
                        Toast.LENGTH_LONG).show();
                return;
            }

How do I get into a Docker container's shell?

To connect to cmd in a Windows container, use

docker exec -it d8c25fde2769 cmd

Where d8c25fde2769 is the container id.

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

The best solution would be to do these steps :

  1. Delete the file called - V2__create_shipwreck.sql, clean and build the project again.
  2. Run the project again, login into h2 and delete the table called "schema_version".

    drop table schema_version;

  3. Now make V2__create_shipwreck.sql file with ddl and rerun the project again.

  4. Do remember this, add version 4.1.2 for flyway-core in pom.xml like

    <dependency>
        <groupId>org.flywaydb</groupId>
        <artifactId>flyway-core</artifactId>
        <version>4.1.2</version>
    </dependency>
    

It should work now. Hope this will help.

Blur effect on a div element

I think this is what you are looking for? If you are looking to add a blur effect to a div element, you can do this directly through CSS Filters-- See fiddle: http://jsfiddle.net/ayhj9vb0/

 div {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
  width: 100px;
  height: 100px;
  background-color: #ccc;

}

Where to find free public Web Services?

https://www.programmableweb.com/ -- Great collection of all category API's across web. It not only show cases the API's , but also Developers who use those API's in their applications and code samples, rating of the API and much more. They have more than apis they also have sdk and libraries too.

How to solve “Microsoft Visual Studio (VS)” error “Unable to connect to the configured development Web server”

I solved the error by changing the port for the project.

I did the following steps:

  1. Right click on the project.
  2. Go to properties.
  3. Go to Server tab.
  4. On tab section, change the project URL for other port, like 8080 or 3000.

Good luck!

WRONGTYPE Operation against a key holding the wrong kind of value php

Redis supports 5 data types. You need to know what type of value that a key maps to, as for each data type, the command to retrieve it is different.

Here are the commands to retrieve key value:

  • if value is of type string -> GET <key>
  • if value is of type hash -> HGETALL <key>
  • if value is of type lists -> lrange <key> <start> <end>
  • if value is of type sets -> smembers <key>
  • if value is of type sorted sets -> ZRANGEBYSCORE <key> <min> <max>

Use the TYPE command to check the type of value a key is mapping to:

  • type <key>

How do I change data-type of pandas data frame to string with a defined format?

I'm unable to reproduce your problem but have you tried converting it to an integer first?

image_name_data['id'] = image_name_data['id'].astype(int).astype('str')

Then, regarding your more general question you could use map (as in this answer). In your case:

image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)

Bootstrap 3: Scroll bars

You need to use the overflow option, but with the following parameters:

.nav {
    max-height:300px;
    overflow-y:auto;  
}

Use overflow-y:auto; so the scrollbar only appears when the content exceeds the maximum height.

If you use overflow-y:scroll, the scrollbar will always be visible - on all .nav - regardless if the content exceeds the maximum heigh or not.

Presumably you want something that adapts itself to the content rather then the the opposite.

Hope it may helpful

Checking if jquery is loaded using Javascript

As per this link:

if (typeof jQuery == 'undefined') {
    // jQuery IS NOT loaded, do stuff here.
}


there are a few more in comments of the link as well like,

if (typeof jQuery == 'function') {...}

//or

if (typeof $== 'function') {...}

// or

if (jQuery) {
    alert("jquery is loaded");
} else {
    alert("Not loaded");
}


Hope this covers most of the good ways to get this thing done!!

Assembly code vs Machine code vs Object code?

Assembly code is a human readable representation of machine code:

mov eax, 77
jmp anywhere

Machine code is pure hexadecimal code:

5F 3A E3 F1

I assume you mean object code as in an object file. This is a variant of machine code, with a difference that the jumps are sort of parameterized such that a linker can fill them in.

An assembler is used to convert assembly code into machine code (object code) A linker links several object (and library) files to generate an executable.

I have once written an assembler program in pure hex (no assembler available) luckily this was way back on the good old (ancient) 6502. But I'm glad there are assemblers for the pentium opcodes.

How do I correct this Illegal String Offset?

if(isset($rule["type"]) && ($rule["type"] == "radio") || ($rule["type"] == "checkbox") )
{
    if(!isset($data[$field]))
        $data[$field]="";
}

How is a JavaScript hash map implemented?

Here is an easy and convenient way of using something similar to the Java map:

var map= {
    'map_name_1': map_value_1,
    'map_name_2': map_value_2,
    'map_name_3': map_value_3,
    'map_name_4': map_value_4
    }

And to get the value:

alert( map['map_name_1'] );    // fives the value of map_value_1

......  etc  .....

How do I make an image smaller with CSS?

CSS 3 introduces the background-size property, but support is not universal.

Having the browser resize the image is inefficient though, the large image still has to be downloaded. You should resize it server side (caching the result) and use that instead. It will use less bandwidth and work in more browsers.

How to put/get multiple JSONObjects to JSONArray?

I found very good link for JSON: http://code.google.com/p/json-simple/wiki/EncodingExamples#Example_1-1_-_Encode_a_JSON_object

Here's code to add multiple JSONObjects to JSONArray.

JSONArray Obj = new JSONArray();
try {
    for(int i = 0; i < 3; i++) {
        // 1st object
        JSONObject list1 = new JSONObject();
        list1.put("val1",i+1);
        list1.put("val2",i+2);
        list1.put("val3",i+3);
        obj.put(list1);
    }

} catch (JSONException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}             
Toast.makeText(MainActivity.this, ""+obj, Toast.LENGTH_LONG).show();

How to get detailed list of connections to database in sql server 2005?

There is also who is active?:

Who is Active? is a comprehensive server activity stored procedure based on the SQL Server 2005 and 2008 dynamic management views (DMVs). Think of it as sp_who2 on a hefty dose of anabolic steroids

How to declare an ArrayList with values?

You can do like this :

List<String> temp = new ArrayList<String>(Arrays.asList("1", "12"));

Show or hide element in React

with the newest version react 0.11 you can also just return null to have no content rendered.

Rendering to null

SQL Server Operating system error 5: "5(Access is denied.)"

An old post, but here is a step by step that worked for SQL Server 2014 running under windows 7:

  • Control Panel ->
  • System and Security ->
  • Administrative Tools ->
  • Services ->
  • Double Click SQL Server (SQLEXPRESS) -> right click, Properties
  • Select Log On Tab
  • Select "Local System Account" (the default was some obtuse Windows System account)
  • -> OK
  • right click, Stop
  • right click, Start

Voilá !

I think setting the logon account may have been an option in the installation, but if so it was not the default, and was easy to miss if you were not already aware of this issue.

Python error when trying to access list by index - "List indices must be integers, not str"

A list is a chain of spaces that can be indexed by (0, 1, 2 .... etc). So if players was a list, players[0] or players[1] would have worked. If players is a dictionary, players["name"] would have worked.

Making a WinForms TextBox behave like your browser's address bar

just use selectall() on enter and click events

private void textBox1_Enter(object sender, EventArgs e)
        {

            textBox1.SelectAll();
        }
        private void textBox1_Click(object sender, EventArgs e)
        {
            textBox1.SelectAll();
        }

How do I install TensorFlow's tensorboard?

It may be helpful to make an alias for it.

Install and find your tensorboard location:

pip install tensorboard
pip show tensorboard

Add the following alias in .bashrc:

alias tensorboard='python pathShownByPip/tensorboard/main.py'

Open another terminal or run exec bash.

For Windows users, cd into pathShownByPip\tensorboard and run python main.py from there.

For Python 3.x, use pip3 instead of pip, and don't forget to use python3 in the alias.

HTML / CSS Popup div on text click

DEMO

In the content area you can provide whatever you want to display in it.

_x000D_
_x000D_
.black_overlay {_x000D_
  display: none;_x000D_
  position: absolute;_x000D_
  top: 0%;_x000D_
  left: 0%;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background-color: black;_x000D_
  z-index: 1001;_x000D_
  -moz-opacity: 0.8;_x000D_
  opacity: .80;_x000D_
  filter: alpha(opacity=80);_x000D_
}_x000D_
.white_content {_x000D_
  display: none;_x000D_
  position: absolute;_x000D_
  top: 25%;_x000D_
  left: 25%;_x000D_
  width: 50%;_x000D_
  height: 50%;_x000D_
  padding: 16px;_x000D_
  border: 16px solid orange;_x000D_
  background-color: white;_x000D_
  z-index: 1002;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>LIGHTBOX EXAMPLE</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <p>This is the main content. To display a lightbox click <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a>_x000D_
  </p>_x000D_
  <div id="light" class="white_content">This is the lightbox content. <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>_x000D_
  </div>_x000D_
  <div id="fade" class="black_overlay"></div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to set host_key_checking=false in ansible inventory file?

Due to the fact that I answered this in 2014, I have updated my answer to account for more recent versions of ansible.

Yes, you can do it at the host/inventory level (Which became possible on newer ansible versions) or global level:

inventory:

Add the following.

ansible_ssh_common_args='-o StrictHostKeyChecking=no'

host:

Add the following.

ansible_ssh_extra_args='-o StrictHostKeyChecking=no'

hosts/inventory options will work with connection type ssh and not paramiko. Some people may strongly argue that inventory and hosts is more secure because the scope is more limited.

global:

Ansible User Guide - Host Key Checking

  • You can do it either in the /etc/ansible/ansible.cfg or ~/.ansible.cfg file:

    [defaults]
    host_key_checking = False
    
  • Or you can setup and env variable (this might not work on newer ansible versions):

    export ANSIBLE_HOST_KEY_CHECKING=False
    

Cocoa Autolayout: content hugging vs content compression resistance priority

Let's say you have a button with the text, "Click Me". What width should that button be?

First, you definitely don't want the button to be smaller than the text. Otherwise, the text would be clipped. This is the horizontal compression resistance priority.

Second, you don't want the button to be bigger than it needs to be. A button that looked like this, [          Click Me          ], is obviously too big. You want the button to "hug" its contents without too much padding. This is the horizontal content hugging priority. For a button, it isn't as strong as the horizontal compression resistance priority.

sklearn: Found arrays with inconsistent numbers of samples when calling LinearRegression.fit()

I think the "X" argument of regr.fit needs to be a matrix, so the following should work.

regr = LinearRegression()
regr.fit(df2.iloc[1:1000, [5]].values, df2.iloc[1:1000, 2].values)

REST API Best practice: How to accept list of parameter values as input

A Step Back

First and foremost, REST describes a URI as a universally unique ID. Far too many people get caught up on the structure of URIs and which URIs are more "restful" than others. This argument is as ludicrous as saying naming someone "Bob" is better than naming him "Joe" – both names get the job of "identifying a person" done. A URI is nothing more than a universally unique name.

So in REST's eyes arguing about whether ?id=["101404","7267261"] is more restful than ?id=101404,7267261 or \Product\101404,7267261 is somewhat futile.

Now, having said that, many times how URIs are constructed can usually serve as a good indicator for other issues in a RESTful service. There are a couple of red flags in your URIs and question in general.

Suggestions

  1. Multiple URIs for the same resource and Content-Location

    We may want to accept both styles but does that flexibility actually cause more confusion and head aches (maintainability, documentation, etc.)?

    URIs identify resources. Each resource should have one canonical URI. This does not mean that you can't have two URIs point to the same resource but there are well defined ways to go about doing it. If you do decide to use both the JSON and list based formats (or any other format) you need to decide which of these formats is the main canonical URI. All responses to other URIs that point to the same "resource" should include the Content-Location header.

    Sticking with the name analogy, having multiple URIs is like having nicknames for people. It is perfectly acceptable and often times quite handy, however if I'm using a nickname I still probably want to know their full name – the "official" way to refer to that person. This way when someone mentions someone by their full name, "Nichloas Telsa", I know they are talking about the same person I refer to as "Nick".

  2. "Search" in your URI

    A more complex case is when we want to offer more complex inputs. For example, if we want to allow multiple filters on search...

    A general rule of thumb of mine is, if your URI contains a verb, it may be an indication that something is off. URI's identify a resource, however they should not indicate what we're doing to that resource. That's the job of HTTP or in restful terms, our "uniform interface".

    To beat the name analogy dead, using a verb in a URI is like changing someone's name when you want to interact with them. If I'm interacting with Bob, Bob's name doesn't become "BobHi" when I want to say Hi to him. Similarly, when we want to "search" Products, our URI structure shouldn't change from "/Product/..." to "/Search/...".

Answering Your Initial Question

  1. Regarding ["101404","7267261"] vs 101404,7267261: My suggestion here is to avoid the JSON syntax for simplicity's sake (i.e. don't require your users do URL encoding when you don't really have to). It will make your API a tad more usable. Better yet, as others have recommended, go with the standard application/x-www-form-urlencoded format as it will probably be most familiar to your end users (e.g. ?id[]=101404&id[]=7267261). It may not be "pretty", but Pretty URIs does not necessary mean Usable URIs. However, to reiterate my initial point though, ultimately when speaking about REST, it doesn't matter. Don't dwell too heavily on it.

  2. Your complex search URI example can be solved in very much the same way as your product example. I would recommend going the application/x-www-form-urlencoded format again as it is already a standard that many are familiar with. Also, I would recommend merging the two.

Your URI...

/Search?term=pumas&filters={"productType":["Clothing","Bags"],"color":["Black","Red"]}    

Your URI after being URI encoded...

/Search?term=pumas&filters=%7B%22productType%22%3A%5B%22Clothing%22%2C%22Bags%22%5D%2C%22color%22%3A%5B%22Black%22%2C%22Red%22%5D%7D

Can be transformed to...

/Product?term=pumas&productType[]=Clothing&productType[]=Bags&color[]=Black&color[]=Red

Aside from avoiding the requirement of URL encoding and making things look a bit more standard, it now homogenizes the API a bit. The user knows that if they want to retrieve a Product or List of Products (both are considered a single "resource" in RESTful terms), they are interested in /Product/... URIs.

How to debug a referenced dll (having pdb)

If you have a project reference, it should work immediately.

If it is a file (dll) reference, you need the debugging symbols (the "pdb" file) to be in the same folder as the dll. Check that your projects are generating debug symbols (project properties => Build => Advanced => Output / Debug Info = full); and if you have copied the dll, put the pdb with it.

You can also load symbols directly in the IDE if you don't want to copy any files, but it is more work.

The easiest option is to use project references!

How to execute .sql script file using JDBC

Just read it and then use the preparedstatement with the full sql-file in it.

(If I remember good)

ADD: You can also read and split on ";" and than execute them all in a loop. Do not forget the comments and add again the ";"

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.

How do I use an image as a submit button?

Just remove the border and add a background image in css

Example:

_x000D_
_x000D_
$("#form").on('submit', function() {_x000D_
   alert($("#submit-icon").val());_x000D_
});
_x000D_
#submit-icon {_x000D_
  background-image: url("https://pixabay.com/static/uploads/photo/2016/10/18/21/22/california-1751455__340.jpg"); /* Change url to wanted image */_x000D_
  background-size: cover;_x000D_
  border: none;_x000D_
  width: 32px;_x000D_
  height: 32px;_x000D_
  cursor: pointer;_x000D_
  color: transparent;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form id="form">_x000D_
  <input type="submit" id="submit-icon" value="test">_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to disable clicking inside div

How to disable clicking another div click until first one popup div close

Image of the example

 <p class="btn1">One</p>
 <div id="box1" class="popup">
 Test Popup Box One
 <span class="close">X</span>
 </div>

 <!-- Two -->
 <p class="btn2">Two</p>
 <div id="box2" class="popup">
 Test Popup Box Two
 <span class="close">X</span>
  </div>

<style>
.disabledbutton {
 pointer-events: none;
 }

.close {
cursor: pointer;
}

</style>
<script>
$(document).ready(function(){
//One
$(".btn1").click(function(){
  $("#box1").css('display','block');
  $(".btn2,.btn3").addClass("disabledbutton");

});
$(".close").click(function(){
  $("#box1").css('display','none');
  $(".btn2,.btn3").removeClass("disabledbutton");
});
</script>

String.equals versus ==

The == operator checks if the two references point to the same object or not.
.equals() checks for the actual string content (value).

Note that the .equals() method belongs to class Object (super class of all classes). You need to override it as per you class requirement, but for String it is already implemented and it checks whether two strings have the same value or not.

Case1)
String s1 = "Stack Overflow";
String s2 = "Stack Overflow";
s1 == s1;      // true
s1.equals(s2); // true
Reason: String literals created without null are stored in the string pool in the permgen area of the heap. So both s1 and s2 point to the same object in the pool.
Case2)
String s1 = new String("Stack Overflow");
String s2 = new String("Stack Overflow");
s1 == s2;      // false
s1.equals(s2); // true
Reason: If you create a String object using the `new` keyword a separate space is allocated to it on the heap.

Formatting DataBinder.Eval data

After some searching on the Internet I found that it is in fact very much possible to call a custom method passing the DataBinder.Eval value.

The custom method can be written in the code behind file, but has to be declared public or protected. In my question above, I had mentioned that I tried to write the custom method in the code behind but was getting a run time error. The reason for this was that I had declared the method to be private.

So, in summary the following is a good way to use DataBinder.Eval value to get your desired output:

default.aspx

<asp:Label ID="lblNewsDate" runat="server" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, "publishedDate")) )%>'></asp:Label>

default.aspx.cs code:

public partial class _Default : System.Web.UI.Page
{

    protected string GetDateInHomepageFormat(DateTime d)
    {

        string retValue = "";

        // Do all processing required and return value

        return retValue;
    }
}

Hope this helps others as well.

When to use cla(), clf() or close() for clearing a plot in matplotlib?

There is just a caveat that I discovered today. If you have a function that is calling a plot a lot of times you better use plt.close(fig) instead of fig.clf() somehow the first does not accumulate in memory. In short if memory is a concern use plt.close(fig) (Although it seems that there are better ways, go to the end of this comment for relevant links).

So the the following script will produce an empty list:

for i in range(5):
    fig = plot_figure()
    plt.close(fig)
# This returns a list with all figure numbers available
print(plt.get_fignums())

Whereas this one will produce a list with five figures on it.

for i in range(5):
    fig = plot_figure()
    fig.clf()
# This returns a list with all figure numbers available
print(plt.get_fignums())

From the documentation above is not clear to me what is the difference between closing a figure and closing a window. Maybe that will clarify.

If you want to try a complete script there you have:

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1000)
y = np.sin(x)

for i in range(5):
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(x, y)
    plt.close(fig)

print(plt.get_fignums())

for i in range(5):
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(x, y)
    fig.clf()

print(plt.get_fignums())

If memory is a concern somebody already posted a work-around in SO see: Create a figure that is reference counted

Windows Scheduled task succeeds but returns result 0x1

Windows Task scheduler (Windows server 2008r2)

Same error for me (last run result: 0x1)

Tabs

  1. Action: remove quotes/double-quotes in

program/script

and

start in

even if there is spaces in the path name...

  1. General:

Run with highest privileges

and

configure for your OS...

Now it work!

last run result: The operation completed successfully

Filter data.frame rows by a logical condition

You could use the dplyr package:

library(dplyr)
filter(expr, cell_type == "hesc")
filter(expr, cell_type == "hesc" | cell_type == "bj fibroblast")

How to Maximize window in chrome using webDriver (python)

Nothing worked for me except:

driver.set_window_size(1024, 600)
driver.maximize_window()

I found this by inspecting selenium/webdriver/remote/webdriver.py. I've never found any useful documentation, but reading the code has been marginally effective.

Calculating Covariance with Python and Numpy

When a and b are 1-dimensional sequences, numpy.cov(a,b)[0][1] is equivalent to your cov(a,b).

The 2x2 array returned by np.cov(a,b) has elements equal to

cov(a,a)  cov(a,b)

cov(a,b)  cov(b,b)

(where, again, cov is the function you defined above.)

Code to loop through all records in MS Access

You should be able to do this with a pretty standard DAO recordset loop. You can see some examples at the following links:
http://msdn.microsoft.com/en-us/library/bb243789%28v=office.12%29.aspx
http://www.granite.ab.ca/access/email/recordsetloop.htm

My own standard loop looks something like this:

Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT * FROM Contacts")

'Check to see if the recordset actually contains rows
If Not (rs.EOF And rs.BOF) Then
    rs.MoveFirst 'Unnecessary in this case, but still a good habit
    Do Until rs.EOF = True
        'Perform an edit
        rs.Edit
        rs!VendorYN = True
        rs("VendorYN") = True 'The other way to refer to a field
        rs.Update

        'Save contact name into a variable
        sContactName = rs!FirstName & " " & rs!LastName

        'Move to the next record. Don't ever forget to do this.
        rs.MoveNext
    Loop
Else
    MsgBox "There are no records in the recordset."
End If

MsgBox "Finished looping through records."

rs.Close 'Close the recordset
Set rs = Nothing 'Clean up

How to convert an array of strings to an array of floats in numpy?

You can use this as well

import numpy as np
x=np.array(['1.1', '2.2', '3.3'])
x=np.asfarray(x,float)

How to generate .angular-cli.json file in Angular Cli?

I couldn't see .angular-cli.json too. Because my Angular version is 6. ng version -> Angular CLI : 6.0.7. Check your Angular version.

MySQL foreach alternative for procedure

Here's the mysql reference for cursors. So I'm guessing it's something like this:

  DECLARE done INT DEFAULT 0;
  DECLARE products_id INT;
  DECLARE result varchar(4000);
  DECLARE cur1 CURSOR FOR SELECT products_id FROM sets_products WHERE set_id = 1;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

  OPEN cur1;

  REPEAT
    FETCH cur1 INTO products_id;
    IF NOT done THEN
      CALL generate_parameter_list(@product_id, @result);
      SET param = param + "," + result; -- not sure on this syntax
    END IF;
  UNTIL done END REPEAT;

  CLOSE cur1;

  -- now trim off the trailing , if desired

There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key

Foreign keys work by joining a column to a unique key in another table, and that unique key must be defined as some form of unique index, be it the primary key, or some other unique index.

At the moment, the only unique index you have is a compound one on ISBN, Title which is your primary key.

There are a number of options open to you, depending on exactly what BookTitle holds and the relationship of the data within it.

I would hazard a guess that the ISBN is unique for each row in BookTitle. ON the assumption this is the case, then change your primary key to be only on ISBN, and change BookCopy so that instead of Title you have ISBN and join on that.

If you need to keep your primary key as ISBN, Title then you either need to store the ISBN in BookCopy as well as the Title, and foreign key on both columns, OR you need to create a unique index on BookTitle(Title) as a distinct index.

More generally, you need to make sure that the column or columns you have in your REFERENCES clause match exactly a unique index in the parent table: in your case it fails because you do not have a single unique index on Title alone.

TSQL: How to convert local time to UTC? (SQL Server 2008)

SQL Server 2008 has a type called datetimeoffset. It's really useful for this type of stuff.

http://msdn.microsoft.com/en-us/library/bb630289.aspx

Then you can use the function SWITCHOFFSET to move it from one timezone to another, but still keeping the same UTC value.

http://msdn.microsoft.com/en-us/library/bb677244.aspx

Rob

process.env.NODE_ENV is undefined

It is due to OS

In your package.json, make sure to have your scripts(Where app.js is your main js file to be executed & NODE_ENV is declared in a .env file).Eg:

"scripts": {
    "start": "node app.js",
    "dev": "nodemon server.js",
    "prod": "NODE_ENV=production & nodemon app.js"
  }

For windows

Also set up your .env file variable having NODE_ENV=development

If your .env file is in a folder for eg.config folder make sure to specify in app.js(your main js file)

const dotenv = require('dotenv'); dotenv.config({ path: './config/config.env' });

Oracle JDBC intermittent Connection Issue

The root cause of this problem has to do with user authentication versions. For each database user, multiple password verifiers are kept in the database. Typically when you upgrade your database, a new password verifier will be added to the list, a stronger one. The following query shows the password verifier versions that are available for each user. For example:

SQL> SELECT PASSWORD_VERSIONS FROM DBA_USERS WHERE USERNAME='SCOTT';

PASSWORD_VERSIONS
-----------------
11G 12C

When upgrading to a newer driver you can use a newer version of the verifier because the driver and server negotiate the strongest possible verifier to to be used. This newer version of the verifier will be more secure and will involve generating larger random numbers or using more complex hashing functions which can explain why you see issues while establishing JDBC connections. As mentioned by other responses using /dev/urandom normally resolves these issues. You can also decide to downgrade your password verifier and make the newer driver use the same older password verifier that your previous driver was using. For example if you want to use the 10G password verifier (for testing purposes only), first you need to make sure it's available for your user. Set SQLNET.ALLOWED_LOGON_VERSION_SERVER=8 in sqlnet.ora on the server. Then:

SQL> alter user scott identified by "tiger";

User altered.

SQL> SELECT PASSWORD_VERSIONS FROM DBA_USERS WHERE USERNAME='SCOTT';
PASSWORD_VERSIONS
-----------------
10G 11G 12C

Then you can force the JDBC thin driver to use the 10G verifier by setting this JDBC property oracle.jdbc.thinLogonCapability="o3". If you run into the error "ORA-28040: No matching authentication protocol" then that means your server is not allowing the 10G verifier to be used. If that's the case then you need to check your configuration again.

How to add minutes to my Date

The issue for you is that you are using mm. You should use MM. MM is for month and mm is for minutes. Try with yyyy-MM-dd HH:mm

Other approach:

It can be as simple as this (other option is to use joda-time)

static final long ONE_MINUTE_IN_MILLIS=60000;//millisecs

Calendar date = Calendar.getInstance();
long t= date.getTimeInMillis();
Date afterAddingTenMins=new Date(t + (10 * ONE_MINUTE_IN_MILLIS));

Why is it string.join(list) instead of list.join(string)?

Because the join() method is in the string class, instead of the list class?

I agree it looks funny.

See http://www.faqs.org/docs/diveintopython/odbchelper_join.html:

Historical note. When I first learned Python, I expected join to be a method of a list, which would take the delimiter as an argument. Lots of people feel the same way, and there’s a story behind the join method. Prior to Python 1.6, strings didn’t have all these useful methods. There was a separate string module which contained all the string functions; each function took a string as its first argument. The functions were deemed important enough to put onto the strings themselves, which made sense for functions like lower, upper, and split. But many hard-core Python programmers objected to the new join method, arguing that it should be a method of the list instead, or that it shouldn’t move at all but simply stay a part of the old string module (which still has lots of useful stuff in it). I use the new join method exclusively, but you will see code written either way, and if it really bothers you, you can use the old string.join function instead.

--- Mark Pilgrim, Dive into Python

If...Then...Else with multiple statements after Then

Multiple statements are to be separated by a new line:

If SkyIsBlue Then
  StartEngines
  Pollute
ElseIf SkyIsRed Then
  StopAttack
  Vent
ElseIf SkyIsYellow Then
  If Sunset Then
    Sleep
  ElseIf Sunrise or IsMorning Then
    Smoke
    GetCoffee
  Else
    Error
  End If
Else
  Joke
  Laugh
End If

How to modify values of JsonObject / JsonArray directly?

Since 2.3 version of Gson library the JsonArray class have a 'set' method.

Here's an simple example:

JsonArray array = new JsonArray();
array.add(new JsonPrimitive("Red"));
array.add(new JsonPrimitive("Green"));
array.add(new JsonPrimitive("Blue"));

array.remove(2);
array.set(0, new JsonPrimitive("Yelow"));

How to increase Java heap space for a tomcat app

Easiest way of doing is: (In Linux/Ububuntu e.t.c)

Go to tomcat bin directory:

cd /opt/tomcat8.5/bin

create new file under bin directory "setenv.sh" and save below mention entries in it.

export CATALINA_OPTS="$CATALINA_OPTS -Xms512m"
export CATALINA_OPTS="$CATALINA_OPTS -Xmx2048m"
export CATALINA_OPTS="$CATALINA_OPTS -XX:MaxPermSize=256m"

and issue command:

./catalina.sh run

In your catalina log file you can see entry like this:

INFO [main] VersionLoggerListener.log Command line argument: -Xms512m
INFO [main] VersionLoggerListener.log Command line argument: -Xmx2048m
INFO [main] VersionLoggerListener.log Command line argument: -XX:MaxPermSize=256m

Which confirms that above changes took place.

Also, the value of "Xms512m" and "-Xmx2048m" can be modified accordingly in the setenv.sh file.

Startup of tomcat could be done in two steps as well. cd /opt/tomcat8.5/bin

Step #1
run ./setenv.sh 
Step #2
./startup.sh

If you're using systemd edit:

/usr/lib/systemd/system/tomcat8.service

and set

Environment=CATALINA_OPTS="-Xms512M -Xmx2048M -XX:MaxPermSize=256m"

Tool to generate JSON schema from JSON data

After several months, the best answer I have is my simple tool. It is raw but functional.

What I want is something similar to this. The JSON data can provide a skeleton for the JSON schema. I have not implemented it yet, but it should be possible to give an existing JSON schema as basis, so that the existing JSON schema plus JSON data can generate an updated JSON schema. If no such schema is given as input, completely default values are taken.

This would be very useful in iterative development: the first time the tool is run, the JSON schema is dummy, but it can be refined automatically according to the evolution of the data.

Joining 2 SQL SELECT result sets into one

Use JOIN to join the subqueries and use ON to say where the rows from each subquery must match:

SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a

If there are some values of col_a that are in T1 but not in T2, you can use a LEFT OUTER JOIN instead.

How to prevent colliders from passing through each other?

Collision with fast-moving objects is always a problem. A good way to ensure that you detect all collision is to use Raycasting instead of relying on the physics simulation. This works well for bullets or small objects, but will not produce good results for large objects. http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html

Pseudo-codeish (I don't have code-completion here and a poor memory):

void FixedUpdate()
{
    Vector3 direction = new Vector3(transform.position - lastPosition);
    Ray ray = new Ray(lastPosition, direction);
    RaycastHit hit;
    if (Physics.Raycast(ray, hit, direction.magnitude))
    {
        // Do something if hit
    }

    this.lastPosition = transform.position;
}

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

It is a conflict (bug) between Themes inside style.xml file in android versions 7 (Api levels 24,25) & 8 (api levels 26,27), when you have

android:screenOrientation="portrait" :inside specific activity (that crashes) in AndroidManifest.xml

&

<item name="android:windowIsTranslucent">true</item> 

in the theme that applied to that activity inside style.xml

It can be solve by these ways according to your need :

1- Remove on of the above mentioned properties that make conflict

2- Change Activity orientation to one of these values as you need : unspecified or behind and so on that can be found here : Google reference for android:screenOrientation `

3- Set the orientation programmatically in run time

PHP move_uploaded_file() error?

How can I know that what is the problem

Easy. Refer to the error log of the webserver.

how can I get the actual problem to display to the user ?

NEVER do it.
An average user will unerstand nothing of this error.
A malicious user should get no feedback, especially in a form of very informative error message.

Just show a page with excuses.

If you don't have access to the server's error log, your task become more complicated.
There are several ways to get in touch with error messages.

To display error messages on screen you can add these lines to the code

ini_set('display_errors',1);
error_reporting(E_ALL);

or to make custom error logfile

ini_set('log_errors',1);
ini_set('error_log','/absolute/path/tp/log_file');

and there are some other ways.
but you must understand that without actual error message you can't move. It's hard to be blind in the dark

Format the date using Ruby on Rails

Since the timestamps are seconds since the UNIX epoch, you can use DateTime.strptime ("string parse time") with the correct specifier:

Date.strptime('1100897479', '%s')
#=> #<Date: 2004-11-19 ((2453329j,0s,0n),+0s,2299161j)>
Date.strptime('1100897479', '%s').to_s
#=> "2004-11-19"
DateTime.strptime('1100897479', '%s')
#=> #<DateTime: 2004-11-19T20:51:19+00:00 ((2453329j,75079s,0n),+0s,2299161j)>
DateTime.strptime('1100897479', '%s').to_s
#=> "2004-11-19T20:51:19+00:00"

Note that you have to require 'date' for that to work, then you can call it either as Date.strptime (if you only care about the date) or DateTime.strptime (if you want date and time). If you need different formatting, you can call DateTime#strftime (look at strftime.net if you have a hard time with the format strings) on it or use one of the built-in methods like rfc822.

Service has zero application (non-infrastructure) endpoints

I got a more detailed exception when I added it programmatically - AddServiceEndpoint:

string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));  

host.AddServiceEndpoint(typeof(MyNamespace.IService),
                        new BasicHttpBinding(), baseAddress);
host.Open();

Display current time in 12 hour format with AM/PM

Easiest way to get it by using date pattern - h:mm a, where

  • h - Hour in am/pm (1-12)
  • m - Minute in hour
  • a - Am/pm marker

Code snippet :

DateFormat dateFormat = new SimpleDateFormat("hh:mm a");

Read more on documentation - SimpleDateFormat java 7

The I/O operation has been aborted because of either a thread exit or an application request

I had this problem. I think that it was caused by the socket getting opened and no data arriving within a short time after the open. I was reading from a serial to ethernet box called a Devicemaster. I changed the Devicemaster port setting from "connect always" to "connect on data" and the problem disappeared. I have great respect for Hans Passant but I do not agree that this is an error code that you can easily solve by scrutinizing code.

How to Parse a JSON Object In Android

In the end I solved it by using JSONObject.get rather than JSONObject.getString and then cast test to a String.

private void saveData(String result) {
    try {
        JSONObject json= (JSONObject) new JSONTokener(result).nextValue();
        JSONObject json2 = json.getJSONObject("results");
        test = (String) json2.get("name");
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

PostgreSQL Error: Relation already exists

In my case, I had a sequence with the same name.

What does numpy.random.seed(0) do?

There is a nice explanation in Numpy docs: https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.RandomState.html it refers to Mersenne Twister pseudo-random number generator. More details on the algorithm here: https://en.wikipedia.org/wiki/Mersenne_Twister

Test file upload using HTTP PUT method

curl -X PUT -T "/path/to/file" "http://myputserver.com/puturl.tmp"

What is the "realm" in basic authentication

A realm can be seen as an area (not a particular page, it could be a group of pages) for which the credentials are used; this is also the string that will be shown when the browser pops up the login window, e.g.

Please enter your username and password for <realm name>:

When the realm changes, the browser may show another popup window if it doesn't have credentials for that particular realm.

Alter column, add default constraint

Actually you have to Do Like below Example, which will help to Solve the Issue...

drop table ABC_table

create table ABC_table
(
    names varchar(20),
    age int
)

ALTER TABLE ABC_table
ADD CONSTRAINT MyConstraintName
DEFAULT 'This is not NULL' FOR names

insert into ABC(age) values(10)

select * from ABC

Custom events in jQuery?

I had a similar question, but was actually looking for a different answer; I'm looking to create a custom event. For example instead of always saying this:

$('#myInput').keydown(function(ev) {
    if (ev.which == 13) {
        ev.preventDefault();
        // Do some stuff that handles the enter key
    }
});

I want to abbreviate it to this:

$('#myInput').enterKey(function() {
    // Do some stuff that handles the enter key
});

trigger and bind don't tell the whole story - this is a JQuery plugin. http://docs.jquery.com/Plugins/Authoring

The "enterKey" function gets attached as a property to jQuery.fn - this is the code required:

(function($){
    $('body').on('keydown', 'input', function(ev) {
        if (ev.which == 13) {
            var enterEv = $.extend({}, ev, { type: 'enterKey' });
            return $(ev.target).trigger(enterEv);
        }
    });

    $.fn.enterKey = function(selector, data, fn) {
        return this.on('enterKey', selector, data, fn);
    };
})(jQuery);

http://jsfiddle.net/b9chris/CkvuJ/4/

A nicety of the above is you can handle keyboard input gracefully on link listeners like:

$('a.button').on('click enterKey', function(ev) {
    ev.preventDefault();
    ...
});

Edits: Updated to properly pass the right this context to the handler, and to return any return value back from the handler to jQuery (for example in case you were looking to cancel the event and bubbling). Updated to pass a proper jQuery event object to handlers, including key code and ability to cancel event.

Old jsfiddle: http://jsfiddle.net/b9chris/VwEb9/24/

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...

How to change the port number for Asp.Net core app?

Yes this will be accesible from other machines if you bind on any external IP address. For example binding to http://*:80 . Note that binding to http://localhost:80 will only bind on 127.0.0.1 interface and therefore will not be accesible from other machines.

Visual Studio is overriding your port. You can change VS port editing this file Properties\launchSettings.json or else set it by code:

        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseUrls("http://*:80") // <-----
            .Build();

        host.Run();

A step by step guide using an external config file is available here.

Read/Parse text file line by line in VBA

I find the FileSystemObject with a TxtStream the easiest way to read files

Dim fso As FileSystemObject: Set fso = New FileSystemObject
Set txtStream = fso.OpenTextFile(filePath, ForReading, False)

Then with this txtStream object you have all sorts of tools which intellisense picks up (unlike using the FreeFile() method) so there is less guesswork. Plus you don' have to assign a FreeFile and hope it is actually still free since when you assigned it.

You can read a file like:

Do While Not txtStream.AtEndOfStream
    txtStream.ReadLine
Loop
txtStream.Close

NOTE: This requires a reference to Microsoft Scripting Runtime.

Checking for an empty field with MySQL

An empty field can be either an empty string or a NULL.

To handle both, use:

email > ''

which can benefit from the range access if you have lots of empty email record (both types) in your table.

How to round the corners of a button

Swift 4 Update

I also tried many options still i wasn't able to get my UIButton round cornered. I added the corner radius code inside the viewDidLayoutSubviews() Solved My issue.

func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        anyButton.layer.cornerRadius = anyButton.frame.height / 2
    }

Also we can adjust the cornerRadius as follows

func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        anyButton.layer.cornerRadius = 10 //Any suitable number as you prefer can be applied 
    }

HttpWebRequest using Basic authentication

Try this:

System.Net.CredentialCache credentialCache = new System.Net.CredentialCache(); 
credentialCache.Add(
    new System.Uri("http://www.yoururl.com/"),
    "Basic", 
    new System.Net.NetworkCredential("username", "password")
);

...
...

httpWebRequest.Credentials = credentialCache; 

How can I render inline JavaScript with Jade / Pug?

No use script tag only.

Solution with |:

script
  | if (10 == 10) {
  |   alert("working")
  | }

Or with a .:

script.
  if (10 == 10) {
    alert("working")
  }

iOS: Compare two dates

NSDate actually represents a time interval in seconds since a reference date (1st Jan 2000 UTC I think). Internally, a double precision floating point number is used so two arbitrary dates are highly unlikely to compare equal even if they are on the same day. If you want to see if a particular date falls on a particular day, you probably need to use NSDateComponents. e.g.

NSDateComponents* dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear: 2011];
[dateComponents setMonth: 5];
[dateComponents setDay: 24];
/*
 *  Construct two dates that bracket the day you are checking.  
 *  Use the user's current calendar.  I think this takes care of things like daylight saving time.
 */
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* startOfDate = [calendar dateFromComponents: dateComponents];
NSDateComponents* oneDay = [[NSDateComponents alloc] init];
[oneDay setDay: 1];
NSDate* endOfDate = [calendar dateByAddingComponents: oneDay toDate: startOfDate options: 0];
/*
 *  Compare the date with the start of the day and the end of the day.
 */
NSComparisonResult startCompare = [startOfDate compare: myDate];
NSComparisonResult endCompare = [endOfDate compare: myDate];

if (startCompare != NSOrderedDescending && endCompare == NSOrderedDescending)
{
    // we are on the right date
} 

PHP upload image

Change function file_get_content() in your code to file_get_contents() . You are missing 's' at the end of function name. That is why it is giving undefined function error.

file_get_contents()

Remove last unnecessary comma after $image filed in line

"INSERT INTO content VALUES         ('','','','','','','','','','$image_name','$image',)

Android: How can I validate EditText input?

In main.xml file

You can put the following attrubute to validate only alphabatics character can accept in edittext.

Do this :

  android:entries="abcdefghijklmnopqrstuvwxyz"

How to increase heap size for jBoss server

On wildfly 8 and later, go to /bin/standalone.conf and put your JAVA_OPTS there, with all you need.

WARNING: Setting property 'source' to 'org.eclipse.jst.jee.server:appname' did not find a matching property

You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. Then click to activate "Publish module contents to separate XML files". Finally, restart your server, the message must disappear.

Source: http://www.albeesonline.com/blog/2008/11/29/warning-setpropertiesruleserverserviceenginehostcontext-setting-property/

How to display loading message when an iFrame is loading?

You can use below code .

 iframe {background:url(../images/loader.gif) center center no-repeat; height: 100%;}

Show datalist labels but submit the actual value

Note that datalist is not the same as a select. It allows users to enter a custom value that is not in the list, and it would be impossible to fetch an alternate value for such input without defining it first.

Possible ways to handle user input are to submit the entered value as is, submit a blank value, or prevent submitting. This answer handles only the first two options.

If you want to disallow user input entirely, maybe select would be a better choice.


To show only the text value of the option in the dropdown, we use the inner text for it and leave out the value attribute. The actual value that we want to send along is stored in a custom data-value attribute:

To submit this data-value we have to use an <input type="hidden">. In this case we leave out the name="answer" on the regular input and move it to the hidden copy.

<input list="suggestionList" id="answerInput">
<datalist id="suggestionList">
    <option data-value="42">The answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">

This way, when the text in the original input changes we can use javascript to check if the text also present in the datalist and fetch its data-value. That value is inserted into the hidden input and submitted.

document.querySelector('input[list]').addEventListener('input', function(e) {
    var input = e.target,
        list = input.getAttribute('list'),
        options = document.querySelectorAll('#' + list + ' option'),
        hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden'),
        inputValue = input.value;

    hiddenInput.value = inputValue;

    for(var i = 0; i < options.length; i++) {
        var option = options[i];

        if(option.innerText === inputValue) {
            hiddenInput.value = option.getAttribute('data-value');
            break;
        }
    }
});

The id answer and answer-hidden on the regular and hidden input are needed for the script to know which input belongs to which hidden version. This way it's possible to have multiple inputs on the same page with one or more datalists providing suggestions.

Any user input is submitted as is. To submit an empty value when the user input is not present in the datalist, change hiddenInput.value = inputValue to hiddenInput.value = ""


Working jsFiddle examples: plain javascript and jQuery

String.Format not work in TypeScript

I solved it like this;

1.Created a function

export function FormatString(str: string, ...val: string[]) {
  for (let index = 0; index < val.length; index++) {
    str = str.replace(`{${index}}`, val[index]);
  }
  return str;
}

2.Used it like the following;

FormatString("{0} is {1} {2}", "This", "formatting", "hack");

How to use __DATE__ and __TIME__ predefined macros in as two integers, then stringify?

it is very simple....

[in make file]

==== 1 ===================

OBJS = ....\

version.o <<== add to your obj lists

==== 2 ===================

DATE = $(shell date +'char szVersionStr[20] = "%Y-%m-%d %H:%M:%S";') <<== add

all:version $(ProgramID) <<== version add at first

version: <<== add

echo '$(DATE)' > version.c  <== add ( create version.c file)

[in program]

=====3 =============

extern char szVersionStr[20];

[ using ]

=== 4 ====

printf( "Version: %s\n", szVersionStr );

Android error while retrieving information from server 'RPC:s-5:AEC-0' in Google Play?

I've finally solved this problem. It was driving me nuts. From a PC, go to Google Play. In my case I had conflicting email accounts and had to create a new email account. Then go to your phone settings. Go to accounts and then Google. Remove your existing email there and add the new one.

The phone will then synchronise and then everything works again. You can then update and download apps; which is what I couldn't do before because of this problem.

Use Font Awesome Icons in CSS

Actually even font-awesome CSS has a similar strategy for setting their icon styles. If you want to get a quick hold of the icon code, check the non-minified font-awesome.css file and there they are....each font in its purity.

Font-Awesome CSS File screenshot

Nested lists python

The question title is too wide and the author's need is more specific. In my case, I needed to extract all elements from nested list like in the example below:

Example:

input -> [1,2,[3,4]]
output -> [1,2,3,4]

The code below gives me the result, but I would like to know if anyone can create a simpler answer:

def get_elements_from_nested_list(l, new_l):
    if l is not None:
        e = l[0]
        if isinstance(e, list):
            get_elements_from_nested_list(e, new_l)
        else:
            new_l.append(e)
        if len(l) > 1:
            return get_elements_from_nested_list(l[1:], new_l)
        else:
            return new_l

Call of the method

l = [1,2,[3,4]]
new_l = []

get_elements_from_nested_list(l, new_l)

Reporting Services permissions on SQL Server R2 SSRS

You need to set permissions within SSRS in two places to give yourself initial access. The set-up program only gives access to Builtin\Administrators, to gain access in order to do this you need to right click you browser link and choose Run as administrator.

  1. Run internet explorer as Administrator
  2. Open the report Manager URL, this time you should get in
  3. Go to Site Settings in the top right
  4. Click Security then New Role Assignment
  5. Enter your domain\username and select System Administrator, click ok
  6. Add other users as necessary
  7. Click home, Folder Settings, then New Role Assignment
  8. Enter your domain\username and select Content Manager, click ok
  9. Add other users as necessary
  10. Re-open internet explorer (non-admin) and recheck the url.

How do I programmatically click a link with javascript?

For me, I managed to make it work that way. I deployed the automatic click in 5000 milliseconds and then closed the loop after 1000 milliseconds. Then there was only 1 automatic click.

<script> var myVar = setInterval(function ({document.getElementById("test").click();}, 500)); setInterval(function () {clearInterval(myVar)}, 1000));</script>

Turn off display errors using file "php.ini"

In file php.ini you should try this for all errors:

display_errors = On

Location file is:

  • Ubuntu 16.04:/etc/php/7.0/apache2
  • CentOS 7:/etc/php.ini

How to use Angular4 to set focus by element id

Here is an Angular4+ directive that you can re-use in any component. Based on code given in the answer by Niel T in this question.

import { NgZone, Renderer, Directive, Input } from '@angular/core';

@Directive({
    selector: '[focusDirective]'
})
export class FocusDirective {
    @Input() cssSelector: string

    constructor(
        private ngZone: NgZone,
        private renderer: Renderer
    ) { }

    ngOnInit() {
        console.log(this.cssSelector);
        this.ngZone.runOutsideAngular(() => {
            setTimeout(() => {
                this.renderer.selectRootElement(this.cssSelector).focus();
            }, 0);
        });
    }
}

You can use it in a component template like this:

<input id="new-email" focusDirective cssSelector="#new-email"
  formControlName="email" placeholder="Email" type="email" email>

Give the input an id and pass the id to the cssSelector property of the directive. Or you can pass any cssSelector you like.

Comments from Niel T:

Since the only thing I'm doing is setting the focus on an element, I don't need to concern myself with change detection, so I can actually run the call to renderer.selectRootElement outside of Angular. Because I need to give the new sections time to render, the element section is wrapped in a timeout to allow the rendering threads time to catch up before the element selection is attempted. Once all that is setup, I can simply call the element using basic CSS selectors.

Character Limit in HTML

there's a maxlength attribute

<input type="text" name="textboxname" maxlength="100" />

Upload a file to Amazon S3 with NodeJS

Or Using promises:

const AWS = require('aws-sdk');
AWS.config.update({
    accessKeyId: 'accessKeyId',
    secretAccessKey: 'secretAccessKey',
    region: 'region'
});

let params = {
    Bucket: "yourBucketName",
    Key: 'someUniqueKey',
    Body: 'someFile'
};
try {
    let uploadPromise = await new AWS.S3().putObject(params).promise();
    console.log("Successfully uploaded data to bucket");
} catch (e) {
    console.log("Error uploading data: ", e);
}

how to check the dtype of a column in python pandas

You can access the data-type of a column with dtype:

for y in agg.columns:
    if(agg[y].dtype == np.float64 or agg[y].dtype == np.int64):
          treat_numeric(agg[y])
    else:
          treat_str(agg[y])

How to do IF NOT EXISTS in SQLite

If you want to ignore the insertion of existing value, there must be a Key field in your Table. Just create a table With Primary Key Field Like:

CREATE TABLE IF NOT EXISTS TblUsers (UserId INTEGER PRIMARY KEY, UserName varchar(100), ContactName varchar(100),Password varchar(100));

And Then Insert Or Replace / Insert Or Ignore Query on the Table Like:

INSERT OR REPLACE INTO TblUsers (UserId, UserName, ContactName ,Password) VALUES('1','UserName','ContactName','Password');

It Will Not Let it Re-Enter The Existing Primary key Value... This Is how you can Check Whether a Value exists in the table or not.

Get the current first responder without using a private API

If your ultimate aim is just to resign the first responder, this should work: [self.view endEditing:YES]

how to open a jar file in Eclipse

A project is not exactly the same thing as an executable jar file.

For starters, a project generally contains source code, while an executable jar file generally doesn't. Again, generally speaking, you need to export an Eclipse project to obtain a file suitable for importing.

Why dict.get(key) instead of dict[key]?

One difference, that can be an advantage, is that if we are looking for a key that doesn't exist we will get None, not like when we use the brackets notation, in which case we will get an error thrown:

print(dictionary.get("address")) # None
print(dictionary["address"]) # throws KeyError: 'address'

Last thing that is cool about the get method, is that it receives an additional optional argument for a default value, that is if we tried to get the score value of a student, but the student doesn't have a score key we can get a 0 instead.

So instead of doing this (or something similar):

score = None
try:
    score = dictionary["score"]
except KeyError:
    score = 0

We can do this:

score = dictionary.get("score", 0)
# score = 0

Vim for Windows - What do I type to save and exit from a file?

Use:

:wq!

The exclamation mark is used for overriding read-only mode.

How to add a "confirm delete" option in ASP.Net Gridview?

This code is working fine for me.

jQuery("a").filter(function () {
        return this.innerHTML.indexOf("Delete") == 0;
        }).click(function () { return confirm("Are you sure you want to delete this record?"); 
});

SQL: Alias Column Name for Use in CASE Statement

Nor in MsSql

SELECT col1 AS o, e = CASE WHEN o < GETDATE() THEN o ELSE GETDATE() END 
FROM Table1

Returns:

Msg 207, Level 16, State 3, Line 1
Invalid column name 'o'.
Msg 207, Level 16, State 3, Line 1
Invalid column name 'o'.

However if I change to CASE WHEN col1... THEN col1 it works

jQuery: If this HREF contains

Along with the points made by others, the $= selector is the "ends with" selector. You will want the *= (contains) selector, like so:

$('a').each(function() {
    if ($(this).is('[href*="?"')) {
        alert("Contains questionmark");
    }
});

Here's a live demo ->

As noted by Matt Ball, unless you will need to also manipulate links without a question mark (which may be the case, since you say your example is simplified), it would be less code and much faster to simply select only the links you want to begin with:

$('a[href*="?"]').each(function() {
    alert("Contains questionmark");
});

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

Anti-virus software may interfere with the HAXM installation. After trying to figure out what went wrong for a few hours I found a strange solution - uninstalling my anti-virus software , installing HAXM (which worked) and then re-installing the anti-virus software (Avast in my case but it could happen with other anti-virus programs as well.

The full check I went through to get this running is:

  1. Check the 'Virtualization' and vt-X feature in the BIOS.
  2. Verifying Hyper-V is not installed.
  3. Checking weather vt-X is enabled in windows with the Intel tool and MS tool (mentioned in previous posts in this thread).
  4. Disabling the anti-virus which didn't help.
  5. Uninstalling the anti-virus (which solved the problem for me).

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

In our case, we were using Hibernate and we had many variables referencing the same Hibernate mapped entity. We were creating and saving these references in a loop. Each reference opened a cursor and kept it open.

We discovered this by using a query to check the number of open cursors while running our code, stepping through with a debugger and selectively commenting things out.

As to why each new reference opened another cursor - the entity in question had collections of other entities mapped to it and I think this had something to do with it (perhaps not just this alone but in combination with how we had configured the fetch mode and cache settings). Hibernate itself has had bugs around failing to close open cursors, though it looks like these have been fixed in later versions.

Since we didn't really need to have so many duplicate references to the same entity anyway, the solution was to stop creating and holding onto all those redundant references. Once we did that the problem when away.

PHP: if !empty & empty

if(!empty($youtube) && empty($link)) {

}
else if(empty($youtube) && !empty($link)) {

}
else if(empty($youtube) && empty($link)) {
}

Using Alert in Response.Write Function in ASP.NET

You can simply write

try
 {
    //Your Logic and code
 }
 catch (Exception ex)
 {
    //Error message in  alert box
    Response.Write("<script>alert('Error :" +ex.Message+"');</script>");
 }

it will work fine

MySQL ORDER BY rand(), name ASC

Use a subquery:

SELECT * FROM 
(
    SELECT * FROM users ORDER BY rand() LIMIT 20
) T1
ORDER BY name 

The inner query selects 20 users at random and the outer query orders the selected users by name.

How do I declare a two dimensional array?

And I like this way:

$cars = array
  (
  array("Volvo",22),
  array("BMW",15),
  array("Saab",5),
  array("Land Rover",17)
  );

HTML button calling an MVC Controller and Action method

Of all the suggestions, nobdy used the razor syntax (this is with bootstrap styles as well). This will make a button that redirects to the Login view in the Account controller:

    <form>
        <button class="btn btn-primary" asp-action="Login" asp- 
   controller="Account">@Localizer["Login"]</button>
    </form>

SQL Server Escape an Underscore

Obviously @Lasse solution is right, but there's another way to solve your problem: T-SQL operator LIKE defines the optional ESCAPE clause, that lets you declare a character which will escape the next character into the pattern.

For your case, the following WHERE clauses are equivalent:

WHERE username LIKE '%[_]d';            -- @Lasse solution
WHERE username LIKE '%$_d' ESCAPE '$';
WHERE username LIKE '%^_d' ESCAPE '^';

How can I output a UTF-8 CSV in PHP that Excel will read properly?

How about just outputting for Excel itself? This is an excellent class that allows you to generate XLS files server-side. I use it frequently for clients who can't "figure out" csv's and so far have never had a complaint. It also allows some extra formatting (shading, rowheights, calculations, etc) that csv won't ever do.

Undefined symbols for architecture arm64

Solved after deleting the content of the DerivedData-->Build-->Products-->Debug-iphoneos

Combine hover and click functions (jQuery)?

You could also use bind:

$('#myelement').bind('click hover', function yourCommonHandler (e) {
   // Your handler here
});

ASP MVC in IIS 7 results in: HTTP Error 403.14 - Forbidden

I know you had this problem in an internal host, but I had experienced such an issue before in an external host and in my case it had it's own resolution, maybe it could save somebody's time:

In fact my website was STOPPED by some reason which currently I'm not aware of, to check it out if you have the same problem, in WebsitePanel main page go to Web -> Websites then select the domain name of your website from the list, after that in the right side of the page just opened, check if you see the word STARTED, else if you see the word STOPPED, make it get started again. That's all.

Compare dates in MySQL

That is SQL Server syntax for converting a date to a string. In MySQL you can use the DATE function to extract the date from a datetime:

SELECT *
FROM players
WHERE DATE(us_reg_date) BETWEEN '2000-07-05' AND '2011-11-10'

But if you want to take advantage of an index on the column us_reg_date you might want to try this instead:

SELECT *
FROM players
WHERE us_reg_date >= '2000-07-05'
  AND us_reg_date < '2011-11-10' + interval 1 day

WPF: Grid with column/row margin/padding?

RowDefinition and ColumnDefinition are of type ContentElement, and Margin is strictly a FrameworkElement property. So to your question, "is it easily possible" the answer is a most definite no. And no, I have not seen any layout panels that demonstrate this kind of functionality.

You can add extra rows or columns as you suggested. But you can also set margins on a Grid element itself, or anything that would go inside a Grid, so that's your best workaround for now.

Get OS-level system information

Add OSHI dependency via maven:

<dependency>
    <groupId>com.github.dblock</groupId>
    <artifactId>oshi-core</artifactId>
    <version>2.2</version>
</dependency>

Get a battery capacity left in percentage:

SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
for (PowerSource pSource : hal.getPowerSources()) {
    System.out.println(String.format("%n %s @ %.1f%%", pSource.getName(), pSource.getRemainingCapacity() * 100d));
}

How to provide a mysql database connection in single file in nodejs

try this

var express = require('express');

var mysql     =    require('mysql');

var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
console.log(app);
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "admin123",
  database: "sitepoint"
});

con.connect(function(err){
  if(err){
    console.log('Error connecting to Db');
    return;
  }
  console.log('Connection established');
});



module.exports = app;

CSS Outside Border

Why not simply using background-clip?

-webkit-background-clip: padding;
   -moz-background-clip: padding;
        background-clip: padding-box;

See:
http://caniuse.com/#search=background-clip
https://developer.mozilla.org/en-US/docs/Web/CSS/background-clip
https://css-tricks.com/almanac/properties/b/background-clip

tqdm in Jupyter Notebook prints new progress bars repeatedly

This is an alternative answer for the case where tqdm_notebook doesn't work for you.

Given the following example:

from time import sleep
from tqdm import tqdm

values = range(3)
with tqdm(total=len(values)) as pbar:
    for i in values:
        pbar.write('processed: %d' %i)
        pbar.update(1)
        sleep(1)

The output would look something like this (progress would show up red):

  0%|          | 0/3 [00:00<?, ?it/s]
processed: 1
 67%|¦¦¦¦¦¦?   | 2/3 [00:01<00:00,  1.99it/s]
processed: 2
100%|¦¦¦¦¦¦¦¦¦¦| 3/3 [00:02<00:00,  1.53it/s]
processed: 3

The problem is that the output to stdout and stderr are processed asynchronously and separately in terms of new lines.

If say Jupyter receives on stderr the first line and then the "processed" output on stdout. Then once it receives an output on stderr to update the progress, it wouldn't go back and update the first line as it would only update the last line. Instead it will have to write a new line.

Workaround 1, writing to stdout

One workaround would be to output both to stdout instead:

import sys
from time import sleep
from tqdm import tqdm

values = range(3)
with tqdm(total=len(values), file=sys.stdout) as pbar:
    for i in values:
        pbar.write('processed: %d' % (1 + i))
        pbar.update(1)
        sleep(1)

The output will change to (no more red):

processed: 1   | 0/3 [00:00<?, ?it/s]
processed: 2   | 0/3 [00:00<?, ?it/s]
processed: 3   | 2/3 [00:01<00:00,  1.99it/s]
100%|¦¦¦¦¦¦¦¦¦¦| 3/3 [00:02<00:00,  1.53it/s]

Here we can see that Jupyter doesn't seem to clear until the end of the line. We could add another workaround for that by adding spaces. Such as:

import sys
from time import sleep
from tqdm import tqdm

values = range(3)
with tqdm(total=len(values), file=sys.stdout) as pbar:
    for i in values:
        pbar.write('processed: %d%s' % (1 + i, ' ' * 50))
        pbar.update(1)
        sleep(1)

Which gives us:

processed: 1                                                  
processed: 2                                                  
processed: 3                                                  
100%|¦¦¦¦¦¦¦¦¦¦| 3/3 [00:02<00:00,  1.53it/s]

Workaround 2, set description instead

It might in general be more straight forward not to have two outputs but update the description instead, e.g.:

import sys
from time import sleep
from tqdm import tqdm

values = range(3)
with tqdm(total=len(values), file=sys.stdout) as pbar:
    for i in values:
        pbar.set_description('processed: %d' % (1 + i))
        pbar.update(1)
        sleep(1)

With the output (description updated while it's processing):

processed: 3: 100%|¦¦¦¦¦¦¦¦¦¦| 3/3 [00:02<00:00,  1.53it/s]

Conclusion

You can mostly get it to work fine with plain tqdm. But if tqdm_notebook works for you, just use that (but then you'd probably not read that far).

Using BufferedReader.readLine() in a while loop properly

You're calling br.readLine() a second time inside the loop.
Therefore, you end up reading two lines each time you go around.

What causes HttpHostConnectException?

A "connection refused" error happens when you attempt to open a TCP connection to an IP address / port where there is nothing currently listening for connections. If nothing is listening, the OS on the server side "refuses" the connection.

If this is happening intermittently, then the most likely explanations are (IMO):

  • the server you are talking ("proxy.xyz.com" / port 60) to is going up and down, OR
  • there is something1 between your client and the proxy that is intermittently sending requests to a non-functioning host, or something.

Is this possible that this exception is caused when a search request is made from Android applications as our website don't support a request is being made from android applications.

It seems unlikely. You said that the "connection refused" exception message says that it is the proxy that is refusing the connection, not your server. Besides if a server was going to not handle certain kinds of request, it still has to accept the TCP connection to find out what the request is ... before it can reject it.


1 - For example, it could be a DNS that round-robin resolves the DNS name to different IP addresses. Or it could be an IP-based load balancer.

Creating default object from empty value in PHP?

If you put "@" character begin of the line then PHP doesn't show any warning/notice for this line. For example:

$unknownVar[$someStringVariable]->totalcall = 10; // shows a warning message that contains: Creating default object from empty value

For preventing this warning for this line you must put "@" character begin of the line like this:

@$unknownVar[$someStringVariable]->totalcall += 10; // no problem. created a stdClass object that name is $unknownVar[$someStringVariable] and created a properti that name is totalcall, and it's default value is 0.
$unknownVar[$someStringVariable]->totalcall += 10; // you don't need to @ character anymore.
echo $unknownVar[$someStringVariable]->totalcall; // 20

I'm using this trick when developing. I don't like disable all warning messages becouse if you don't handle warnings correctly then they will become a big error in future.

How to get everything after a certain character?

Another simple way, using strchr() or strstr():

$str = '233718_This_is_a_string';

echo ltrim(strstr($str, '_'), '_'); // This_is_a_string

SQL Server - NOT IN

SELECT [T1].*
FROM [Table1] AS [T1]
WHERE  NOT EXISTS (SELECT 
    1 AS [C1]
    FROM [Table2] AS [T2]
    WHERE ([T2].[MAKE] = [T1].[MAKE]) AND
        ([T2].[MODEL] = [T1].[MODEL]) AND
        ([T2].[Serial Number] = [T1].[Serial Number])
);

Linux command to list all available commands and aliases

There is the

type -a mycommand

command which lists all aliases and commands in $PATH where mycommand is used. Can be used to check if the command exists in several variants. Other than that... There's probably some script around that parses $PATH and all aliases, but don't know about any such script.

PHP cURL custom headers

$subscription_key  ='';
    $host = '';    
    $request_headers = array(
                    "X-Mashape-Key:" . $subscription_key,
                    "X-Mashape-Host:" . $host
                );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);

    $season_data = curl_exec($ch);

    if (curl_errno($ch)) {
        print "Error: " . curl_error($ch);
        exit();
    }

    // Show me the result
    curl_close($ch);
    $json= json_decode($season_data, true);

Python string.join(list) on object array rather than string array

another solution is to override the join operator of the str class.

Let us define a new class my_string as follows

class my_string(str):
    def join(self, l):
        l_tmp = [str(x) for x in l]
        return super(my_string, self).join(l_tmp)

Then you can do

class Obj:
    def __str__(self):
        return 'name'

list = [Obj(), Obj(), Obj()]
comma = my_string(',')

print comma.join(list)

and you get

name,name,name

BTW, by using list as variable name you are redefining the list class (keyword) ! Preferably use another identifier name.

Hope you'll find my answer useful.

bootstrap 3 tabs not working properly

When I moved the following lines from the head section to the end of the body section it worked.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

How to get datetime in JavaScript?

@Shadow Wizard's code should return 02:45 PM instead of 14:45 PM. So I modified his code a bit:

function getNowDateTimeStr(){
 var now = new Date();
 var hour = now.getHours() - (now.getHours() >= 12 ? 12 : 0);
return [[AddZero(now.getDate()), AddZero(now.getMonth() + 1), now.getFullYear()].join("/"), [AddZero(hour), AddZero(now.getMinutes())].join(":"), now.getHours() >= 12 ? "PM" : "AM"].join(" ");
}

//Pad given value to the left with "0"
function AddZero(num) {
    return (num >= 0 && num < 10) ? "0" + num : num + "";
}

Copying an array of objects into another array in javascript

If you want to keep reference:

Array.prototype.push.apply(destinationArray, sourceArray);

Bootstrap 3 Flush footer to bottom. not fixed

UPDATE: This does not directly answer the question in its entirety, but others may find this useful.

This is the HTML for your responsive footer

<footer class="footer navbar-fixed-bottom">
     <div class="container">
     </div>
</footer>

For the CSS

footer{
    width:100%;
    min-height:100px;    
    background-color: #222; /* This color gets inverted color or you can add navbar inverse class in html */
}

NOTE: At the time of the posting for this question the above lines of code does not push the footer below the page content; but it will keep your footer from crawling midway up the page when there is little content on the page. For an example that does push the footer below the page content take a look here http://getbootstrap.com/examples/sticky-footer/

How to get < span > value?

Try this

var div = document.getElementById("test");
var spans = div.getElementsByTagName("span");

for(i=0;i<spans.length;i++)
{
  alert(spans[i].innerHTML);
}

Twitter Bootstrap Button Text Word Wrap

You can simply add this class.

.btn {
    white-space:normal !important;
    word-wrap: break-word; 
}

How to make a launcher

They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.

File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish

But if you do not have samples loaded, then download it using the below steps

Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install

Regular expression: zero or more occurrences of optional character /

/*

If your delimiters are slash-based, escape it:

\/*

* means "0 or more of the previous repeatable pattern", which can be a single character, a character class or a group.

Why doesn't the height of a container element increase if it contains floated elements?

you can use overflow property to the container div if you don't have any div to show over the container eg:

<div class="cointainer">
    <div class="one">Content One</div>
    <div class="two">Content Two</div>
</div>

Here is the following css:

.container{
    width:100%;/* As per your requirment */
    height:auto;
    float:left;
    overflow:hidden;
}
.one{
    width:200px;/* As per your requirment */
    height:auto;
    float:left;
}

.two{
    width:200px;/* As per your requirment */
    height:auto;
    float:left;
}

-----------------------OR------------------------------

    <div class="cointainer">
        <div class="one">Content One</div>
        <div class="two">Content Two</div>
        <div class="clearfix"></div>
    </div>

Here is the following css:

    .container{
        width:100%;/* As per your requirment */
        height:auto;
        float:left;
        overflow:hidden;
    }
    .one{
        width:200px;/* As per your requirment */
        height:auto;
        float:left;
    }

    .two{
        width:200px;/* As per your requirment */
        height:auto;
        float:left;
    }
    .clearfix:before,
    .clearfix:after{
        display: table;
        content: " ";
    }
    .clearfix:after{
        clear: both;
    }

Set default value of an integer column SQLite

Use the SQLite keyword default

db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" 
    + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
    + KEY_NAME + " TEXT NOT NULL, "
    + KEY_WORKED + " INTEGER, "
    + KEY_NOTE + " INTEGER DEFAULT 0);");

This link is useful: http://www.sqlite.org/lang_createtable.html

How to upload files to server using Putty (ssh)

Use WinSCP for file transfer over SSH, putty is only for SSH commands.

How to obtain the last path segment of a URI

You can use getPathSegments() function. (Android Documentation)

Consider your example URI:

String uri = "http://base_path/some_segment/id"

You can get the last segment using:

List<String> pathSegments = uri.getPathSegments();
String lastSegment = pathSegments.get(pathSegments.size - 1);

lastSegment will be id.

font-family is inherit. How to find out the font-family in chrome developer pane?

Your browser's default font-family will be inherited for that case.

You can check the browser default font in chrome: Settings > Web content > Customize fonts...

enter image description here enter image description here

c++ and opencv get and set pixel color to Mat

I would not use .at for performance reasons.

Define a struct:

//#pragma pack(push, 2) //not useful (see comments below)
struct RGB {
    uchar blue;
    uchar green;
    uchar red;  };

And then use it like this on your cv::Mat image:

RGB& rgb = image.ptr<RGB>(y)[x];

image.ptr(y) gives you a pointer to the scanline y. And iterate through the pixels with loops of x and y

jQuery.ajax returns 400 Bad Request

Be sure and use 'get' or 'post' consistantly with your $.ajax call for example.

$.ajax({
    type: 'get',

must be met with

app.get('/', function(req, res) {

=============== and for post

$.ajax({
    type: 'post',

must be met with

app.post('/', function(req, res) {

Converting dictionary to JSON

No need to convert it in a string by using json.dumps()

r = {'is_claimed': 'True', 'rating': 3.5}
file.write(r['is_claimed'])
file.write(str(r['rating']))

You can get the values directly from the dict object.

React Router v4 - How to get current route?

Add

import {withRouter} from 'react-router-dom';

Then change your component export

export default withRouter(ComponentName)

Then you can access the route directly within the component itself (without touching anything else in your project) using:

window.location.pathname

Tested March 2020 with: "version": "5.1.2"

Html/PHP - Form - Input as array

Simply add [] to those names like

 <input type="text" class="form-control" placeholder="Titel" name="levels[level][]">
 <input type="text" class="form-control" placeholder="Titel" name="levels[build_time][]">

Take that template and then you can add those even using a loop.

Then you can add those dynamically as much as you want, without having to provide an index. PHP will pick them up just like your expected scenario example.

Edit

Sorry I had braces in the wrong place, which would make every new value as a new array element. Use the updated code now and this will give you the following array structure

levels > level (Array)
levels > build_time (Array)

Same index on both sub arrays will give you your pair. For example

echo $levels["level"][5];
echo $levels["build_time"][5];

Converting char[] to byte[]

You could make a method:

public byte[] toBytes(char[] data) {
byte[] toRet = new byte[data.length];
for(int i = 0; i < toRet.length; i++) {
toRet[i] = (byte) data[i];
}
return toRet;
}

Hope this helps

Python: avoiding pylint warnings about too many arguments

You could try using Python's variable arguments feature:

def myfunction(*args):
    for x in args:
        # Do stuff with specific argument here

Git push results in "Authentication Failed"

It happens if you change your login or password of git service account (Git). You need to change it in Windows Credentials Manager too. type "Credential Manager" in Windows Search menu open it.

Windows Credentials Manager->Windows Credential and under Generic Credentials edit your git password.

How to pass parameters on onChange of html select

You can try bellow code

<select onchange="myfunction($(this).val())" id="myId">
    </select>

Send and receive messages through NSNotificationCenter in Objective-C?

There is also the possibility of using blocks:

NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[[NSNotificationCenter defaultCenter] 
     addObserverForName:@"notificationName" 
     object:nil
     queue:mainQueue
     usingBlock:^(NSNotification *notification)
     {
          NSLog(@"Notification received!");
          NSDictionary *userInfo = notification.userInfo;

          // ...
     }];

Apple's documentation

Parse query string in JavaScript

Me too! http://jsfiddle.net/drzaus/8EE8k/

(Note: without fancy nested or duplicate checking)

deparam = (function(d,x,params,p,i,j) {
return function (qs) {
    // start bucket; can't cheat by setting it in scope declaration or it overwrites
    params = {};
    // remove preceding non-querystring, correct spaces, and split
    qs = qs.substring(qs.indexOf('?')+1).replace(x,' ').split('&');
    // march and parse
    for (i = qs.length; i > 0;) {
        p = qs[--i];
        // allow equals in value
        j = p.indexOf('=');
        // what if no val?
        if(j === -1) params[d(p)] = undefined;
        else params[d(p.substring(0,j))] = d(p.substring(j+1));
    }

    return params;
};//--  fn  deparam
})(decodeURIComponent, /\+/g);

And tests:

var tests = {};
tests["simple params"] = "ID=2&first=1&second=b";
tests["full url"] = "http://blah.com/?third=c&fourth=d&fifth=e";
tests['just ?'] = '?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses';
tests['with equals'] = 'foo=bar&baz=quux&equals=with=extra=equals&grault=garply';
tests['no value'] = 'foo=bar&baz=&qux=quux';
tests['value omit'] = 'foo=bar&baz&qux=quux';

var $output = document.getElementById('output');
function output(msg) {
    msg = Array.prototype.slice.call(arguments, 0).join("\n");
    if($output) $output.innerHTML += "\n" + msg + "\n";
    else console.log(msg);
}
var results = {}; // save results, so we can confirm we're not incorrectly referencing
$.each(tests, function(msg, test) {
    var q = deparam(test);
    results[msg] = q;
    output(msg, test, JSON.stringify(q), $.param(q));
    output('-------------------');
});

output('=== confirming results non-overwrite ===');
$.each(results, function(msg, result) {
    output(msg, JSON.stringify(result));
    output('-------------------');
});

Results in:

simple params
ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------
full url
http://blah.com/?third=c&fourth=d&fifth=e
{"fifth":"e","fourth":"d","third":"c"}
fifth=e&fourth=d&third=c
-------------------
just ?
?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses
{"spaces":"these are pluses","building":"Empire State Building","fruit":"apple","animal":"bear"}
spaces=these%20are%20pluses&building=Empire%20State%20Building&fruit=apple&animal=bear
-------------------
with equals
foo=bar&baz=quux&equals=with=extra=equals&grault=garply
{"grault":"garply","equals":"with=extra=equals","baz":"quux","foo":"bar"}
grault=garply&equals=with%3Dextra%3Dequals&baz=quux&foo=bar
-------------------
no value
foo=bar&baz=&qux=quux
{"qux":"quux","baz":"","foo":"bar"}
qux=quux&baz=&foo=bar
-------------------
value omit
foo=bar&baz&qux=quux
{"qux":"quux","foo":"bar"}   <-- it's there, i swear!
qux=quux&baz=&foo=bar        <-- ...see, jQuery found it
-------------------

Error using eclipse for Android - No resource found that matches the given name

One general solution to such tiny errors is that you close eclipse and start is again.. 3 irritating problems were solved.. its the problem with eclipse.. some times it didn resolve "R.id", the it didn find @string/somebutton, and then again some random thing... if nothing logical comes in your mind, try this, n conjure d result.. :)

Default argument values in JavaScript functions

In javascript you can call a function (even if it has parameters) without parameters.

So you can add default values like this:

function func(a, b){
   if (typeof(a)==='undefined') a = 10;
   if (typeof(b)==='undefined') b = 20;

   //your code
}

and then you can call it like func(); to use default parameters.

Here's a test:

function func(a, b){
   if (typeof(a)==='undefined') a = 10;
   if (typeof(b)==='undefined') b = 20;

   alert("A: "+a+"\nB: "+b);
}
//testing
func();
func(80);
func(100,200);

What is LD_LIBRARY_PATH and how to use it?

My error was also related to not finding the required .so file by a service. I used LD_LIBRARY_PATH variable to priorities the path picked up by the linker to search the required lib.

I copied both service and .so file in a folder and fed it to LD_LIBRARY_PATH variable as

LD_LIBRARY_PATH=. ./service

being in the same folder I have given the above command and it worked.

PHP How to fix Notice: Undefined variable:

Define the variables at the beginning of the function so if there are no records, the variables exist and you won't get the error. Check for null values in the returned array.

$hn = null;
$pid = null;
$datereg = null;
$prefix = null;
$fname = null;
$lname = null;
$age = null;
$sex = null;

How do I print a list of "Build Settings" in Xcode project?

Although @dunedin15's fantastic answer has served me well on a number of occasions, it can give inaccurate results for some edge-cases, such as when debugging build settings of a static lib for an Archive build.

As an alternative, a Run Script Build Phase can be easily added to any target to “Log Build Settings” when it's built:

Target's Build Phases section w/ added Log Build Settings script phase

To add, (with the target in question selected) under the Build Phases tab-section click the little ? button a dozen-or-so pixels up-left-ward from the Target Dependencies section, and set the shell to /bin/bash and the command to export.  You'll also probably want to drag the phase upwards so that it happens just after Target Dependencies and before Copy Headers or Compile Sources.  Renaming the phase from “Run Script” to “Log Build Settings” isn't a bad idea.

The result is this incredibly helpful listing of current environment variables used for building:

Build Log output w/ export command's results

Using variables inside strings

This functionality is not built-in to C# 5 or below.
Update: C# 6 now supports string interpolation, see newer answers.

The recommended way to do this would be with String.Format:

string name = "Scott";
string output = String.Format("Hello {0}", name);

However, I wrote a small open-source library called SmartFormat that extends String.Format so that it can use named placeholders (via reflection). So, you could do:

string name = "Scott";
string output = Smart.Format("Hello {name}", new{name}); // Results in "Hello Scott".

Hope you like it!

React.js: onChange event for contentEditable

Edit 2015

Someone has made a project on NPM with my solution: https://github.com/lovasoa/react-contenteditable

Edit 06/2016: I've just encoutered a new problem that occurs when the browser tries to "reformat" the html you just gave him, leading to component always re-rendering. See

Edit 07/2016: here's my production contentEditable implementation. It has some additional options over react-contenteditable that you might want, including:

  • locking
  • imperative API allowing to embed html fragments
  • ability to reformat the content

Summary:

FakeRainBrigand's solution has worked quite fine for me for some time until I got new problems. ContentEditables are a pain, and are not really easy to deal with React...

This JSFiddle demonstrates the problem.

As you can see, when you type some characters and click on Clear, the content is not cleared. This is because we try to reset the contenteditable to the last known virtual dom value.

So it seems that:

  • You need shouldComponentUpdate to prevent caret position jumps
  • You can't rely on React's VDOM diffing algorithm if you use shouldComponentUpdate this way.

So you need an extra line so that whenever shouldComponentUpdate returns yes, you are sure the DOM content is actually updated.

So the version here adds a componentDidUpdate and becomes:

var ContentEditable = React.createClass({
    render: function(){
        return <div id="contenteditable"
            onInput={this.emitChange} 
            onBlur={this.emitChange}
            contentEditable
            dangerouslySetInnerHTML={{__html: this.props.html}}></div>;
    },

    shouldComponentUpdate: function(nextProps){
        return nextProps.html !== this.getDOMNode().innerHTML;
    },

    componentDidUpdate: function() {
        if ( this.props.html !== this.getDOMNode().innerHTML ) {
           this.getDOMNode().innerHTML = this.props.html;
        }
    },

    emitChange: function(){
        var html = this.getDOMNode().innerHTML;
        if (this.props.onChange && html !== this.lastHtml) {
            this.props.onChange({
                target: {
                    value: html
                }
            });
        }
        this.lastHtml = html;
    }
});

The Virtual dom stays outdated, and it may not be the most efficient code, but at least it does work :) My bug is resolved


Details:

1) If you put shouldComponentUpdate to avoid caret jumps, then the contenteditable never rerenders (at least on keystrokes)

2) If the component never rerenders on key stroke, then React keeps an outdated virtual dom for this contenteditable.

3) If React keeps an outdated version of the contenteditable in its virtual dom tree, then if you try to reset the contenteditable to the value outdated in the virtual dom, then during the virtual dom diff, React will compute that there are no changes to apply to the DOM!

This happens mostly when:

  • you have an empty contenteditable initially (shouldComponentUpdate=true,prop="",previous vdom=N/A),
  • the user types some text and you prevent renderings (shouldComponentUpdate=false,prop=text,previous vdom="")
  • after user clicks a validation button, you want to empty that field (shouldComponentUpdate=false,prop="",previous vdom="")
  • as both the newly produced and old vdom are "", React does not touch the dom.

unsigned APK can not be installed

An unsigned application cannot be installed. When we run directly from eclipse, that apk is signed with debugger key and can be found in bin\ folder of the project. You can use that for test purpose distribution also.

window.history.pushState refreshing the browser

window.history.pushState({urlPath:'/page1'},"",'/page1')

Only works after page is loaded, and when you will click on refresh it doesn't mean that there is any real URL.

What you should do here is knowing to which URL you are getting redirected when you reload this page. And on that page you can get the conditions by getting the current URL and making all of your conditions.

How to default to other directory instead of home directory

This may help you.

image description

  1. Right click on git bash -> properties
  2. In Shorcut tab -> Start in field -> enter your user defined path
  3. Make sure the Target field does not include --go-to-home or it will continue to start in the directory specified in your HOME variable

Thats it.

How can I get the selected VALUE out of a QCombobox?

It seems you need to do combobox->itemData(combobox->currentIndex()) if you want to get the current data of the QComboBox.

If you are using your own class derived from QComboBox, you can add a currentData() function.

How can I print literal curly-brace characters in a string and also use .format on it?

I recently ran into this, because I wanted to inject strings into preformatted JSON. My solution was to create a helper method, like this:

def preformat(msg):
    """ allow {{key}} to be used for formatting in text
    that already uses curly braces.  First switch this into
    something else, replace curlies with double curlies, and then
    switch back to regular braces
    """
    msg = msg.replace('{{', '<<<').replace('}}', '>>>')
    msg = msg.replace('{', '{{').replace('}', '}}')
    msg = msg.replace('<<<', '{').replace('>>>', '}')
    return msg

You can then do something like:

formatted = preformat("""
    {
        "foo": "{{bar}}"
    }""").format(bar="gas")

Gets the job done if performance is not an issue.

How to adjust the size of y axis labels only in R?

As the title suggests that we want to adjust the size of the labels and not the tick marks I figured that I actually might add something to the question, you need to use the mtext() if you want to specify one of the label sizes, or you can just use par(cex.lab=2) as a simple alternative. Here's a more advanced mtext() example:

set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data=foo,
     yaxt="n", ylab="", 
     xlab="Regular boring x", 
     pch=16,
     col="darkblue")
axis(2,cex.axis=1.2)
mtext("Awesome Y variable", side=2, line=2.2, cex=2)

enter image description here

You may need to adjust the line= option to get the optimal positioning of the text but apart from that it's really easy to use.

Call a python function from jinja2

from jinja2 import Template

def custom_function(a):
    return a.replace('o', 'ay')

template = Template('Hey, my name is {{ custom_function(first_name) }} {{ func2(last_name) }}')
template.globals['custom_function'] = custom_function

You can also give the function in the fields as per Matroskin's answer

fields = {'first_name': 'Jo', 'last_name': 'Ko', 'func2': custom_function}
print template.render(**fields)

Will output:

Hey, my name is Jay Kay

Works with Jinja2 version 2.7.3

And if you want a decorator to ease defining functions on template.globals check out Bruno Bronosky's answer

Check array position for null/empty

If your array is not initialized then it contains randoms values and cannot be checked !

To initialize your array with 0 values:

int array[5] = {0};

Then you can check if the value is 0:

array[4] == 0;

When you compare to NULL, it compares to 0 as the NULL is defined as integer value 0 or 0L.

If you have an array of pointers, better use the nullptr value to check:

char* array[5] = {nullptr}; // we defined an array of char*, initialized to nullptr

if (array[4] == nullptr)
    // do something

regular expression: match any word until first space

I think, a word was created with more than one letters. My suggestion is:

[^\s\s$]{2,}

Script to get the HTTP status code of a list of urls?

wget -S -i *file* will get you the headers from each url in a file.

Filter though grep for the status code specifically.

Maven with Eclipse Juno

From Eclipse

  • Go to Help
  • Eclipse Marketplace
  • Search for m2e or maven integration for eclipse
  • click on Install against - 'Maven Integration for Eclipse (Juno and newer) 1.4'
  • Restart and Enjoy!!!

Writing a pandas DataFrame to CSV file

To write a pandas DataFrame to a CSV file, you will need DataFrame.to_csv. This function offers many arguments with reasonable defaults that you will more often than not need to override to suit your specific use case. For example, you might want to use a different separator, change the datetime format, or drop the index when writing. to_csv has arguments you can pass to address these requirements.

Here's a table listing some common scenarios of writing to CSV files and the corresponding arguments you can use for them.

Write to CSV ma dude

Footnotes

  1. The default separator is assumed to be a comma (','). Don't change this unless you know you need to.
  2. By default, the index of df is written as the first column. If your DataFrame does not have an index (IOW, the df.index is the default RangeIndex), then you will want to set index=False when writing. To explain this in a different way, if your data DOES have an index, you can (and should) use index=True or just leave it out completely (as the default is True).
  3. It would be wise to set this parameter if you are writing string data so that other applications know how to read your data. This will also avoid any potential UnicodeEncodeErrors you might encounter while saving.
  4. Compression is recommended if you are writing large DataFrames (>100K rows) to disk as it will result in much smaller output files. OTOH, it will mean the write time will increase (and consequently, the read time since the file will need to be decompressed).

using jquery $.ajax to call a PHP function

I developed a jQuery plugin that allows you to call any core PHP function or even user defined PHP functions as methods of the plugin: jquery.php

After including jquery and jquery.php in the head of our document and placing request_handler.php on our server we would start using the plugin in the manner described below.

For ease of use reference the function in a simple manner:

    var P = $.fn.php;

Then initialize the plugin:

P('init', 
{
    // The path to our function request handler is absolutely required
    'path': 'http://www.YourDomain.com/jqueryphp/request_handler.php',

    // Synchronous requests are required for method chaining functionality
    'async': false,

    // List any user defined functions in the manner prescribed here
            // There must be user defined functions with these same names in your PHP
    'userFunctions': {

        languageFunctions: 'someFunc1 someFunc2'
    }
});             

And now some usage scenarios:

// Suspend callback mode so we don't work with the DOM
P.callback(false);

// Both .end() and .data return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25

// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]

Demonstrating PHP function chaining:

var data1 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).data();
var data2 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).end();
console.log( data1, data2 );

Demonstrating sending a JSON block of PHP pseudo-code:

var data1 = 
        P.block({
    $str: "Let's use PHP's file_get_contents()!",
    $opts: 
    [
        {
            http: {
                method: "GET",
                header: "Accept-language: en\r\n" +
                        "Cookie: foo=bar\r\n"
            }
        }
    ],
    $context: 
    {
        stream_context_create: ['$opts']
    },
    $contents: 
    {
        file_get_contents: ['http://www.github.com/', false, '$context']
    },
    $html: 
    {
        htmlentities: ['$contents']
    }
}).data();
    console.log( data1 );

The backend configuration provides a whitelist so you can restrict which functions can be called. There are a few other patterns for working with PHP described by the plugin as well.

Converting string to byte array in C#

This work for me, after that I could convert put my picture in a bytea field in my database.

using (MemoryStream s = new MemoryStream(DirEntry.Properties["thumbnailphoto"].Value as byte[]))
{
    return s.ToArray();
}

How can I get the current date and time in UTC or GMT in Java?

Use this Class to get ever the right UTC Time from a Online NTP Server:

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


class NTP_UTC_Time
{
private static final String TAG = "SntpClient";

private static final int RECEIVE_TIME_OFFSET = 32;
private static final int TRANSMIT_TIME_OFFSET = 40;
private static final int NTP_PACKET_SIZE = 48;

private static final int NTP_PORT = 123;
private static final int NTP_MODE_CLIENT = 3;
private static final int NTP_VERSION = 3;

// Number of seconds between Jan 1, 1900 and Jan 1, 1970
// 70 years plus 17 leap days
private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;

private long mNtpTime;

public boolean requestTime(String host, int timeout) {
    try {
        DatagramSocket socket = new DatagramSocket();
        socket.setSoTimeout(timeout);
        InetAddress address = InetAddress.getByName(host);
        byte[] buffer = new byte[NTP_PACKET_SIZE];
        DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);

        buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);

        writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET);

        socket.send(request);

        // read the response
        DatagramPacket response = new DatagramPacket(buffer, buffer.length);
        socket.receive(response);          
        socket.close();

        mNtpTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);            
    } catch (Exception e) {
      //  if (Config.LOGD) Log.d(TAG, "request time failed: " + e);
        return false;
    }

    return true;
}


public long getNtpTime() {
    return mNtpTime;
}


/**
 * Reads an unsigned 32 bit big endian number from the given offset in the buffer.
 */
private long read32(byte[] buffer, int offset) {
    byte b0 = buffer[offset];
    byte b1 = buffer[offset+1];
    byte b2 = buffer[offset+2];
    byte b3 = buffer[offset+3];

    // convert signed bytes to unsigned values
    int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
    int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
    int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
    int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);

    return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
}

/**
 * Reads the NTP time stamp at the given offset in the buffer and returns 
 * it as a system time (milliseconds since January 1, 1970).
 */    
private long readTimeStamp(byte[] buffer, int offset) {
    long seconds = read32(buffer, offset);
    long fraction = read32(buffer, offset + 4);
    return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);        
}

/**
 * Writes 0 as NTP starttime stamp in the buffer. --> Then NTP returns Time OFFSET since 1900
 */    
private void writeTimeStamp(byte[] buffer, int offset) {        
    int ofs =  offset++;

    for (int i=ofs;i<(ofs+8);i++)
      buffer[i] = (byte)(0);             
}

}

And use it with:

        long now = 0;

        NTP_UTC_Time client = new NTP_UTC_Time();

        if (client.requestTime("pool.ntp.org", 2000)) {              
          now = client.getNtpTime();
        }

If you need UTC Time "now" as DateTimeString use function:

private String get_UTC_Datetime_from_timestamp(long timeStamp){

    try{

        Calendar cal = Calendar.getInstance();
        TimeZone tz = cal.getTimeZone();

        int tzt = tz.getOffset(System.currentTimeMillis());

        timeStamp -= tzt;

        // DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());
        DateFormat sdf = new SimpleDateFormat();
        Date netDate = (new Date(timeStamp));
        return sdf.format(netDate);
    }
    catch(Exception ex){
        return "";
     }
    } 

and use it with:

String UTC_DateTime = get_UTC_Datetime_from_timestamp(now);

Validating email addresses using jQuery and regex

$(document).ready(function() {
  $('#emailid').focusout(function(){
    $('#emailid').filter(function(){
      var email = $('#emailid').val();
      var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
      if ( !emailReg.test( email ) ) {
        alert('Please enter valid email');
      } else {
        alert('Thank you for your valid email');
      }
    });
  });                 
});

Easy way to prevent Heroku idling?

I found another free site that will constantly ping your site called Unidler

http://unidler.herokuapp.com/

Same as pingdom, but doesnt need to log in.

How to compare files from two different branches?

Agreeing with the answer suggested by @dahlbyk. If you want the diff to be written to a diff file for code reviews use the following command.

git diff branch master -- filepath/filename.extension > filename.diff --cached

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

UserSelect =null

AlertDialog.Builder builder = new Builder(ImonaAndroidApp.LoginScreen);
            builder.setMessage("you message");
            builder.setPositiveButton("OK", new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    UserSelect = true ;

                }
            });

            builder.setNegativeButton("Cancel", new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    UserSelect = false ;

                }
            });
           // in UI thread
        builder.show();             
        // wait until the user select
            while(UserSelect ==null);

How to decrypt the password generated by wordpress

You will not be able to retrieve a plain text password from wordpress.

Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.

See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password

Facebook api: (#4) Application request limit reached

The Facebook API limit isn't really documented, but apparently it's something like: 600 calls per 600 seconds, per token & per IP. As the site is restricted, quoting the relevant part:

After some testing and discussion with the Facebook platform team, there is no official limit I'm aware of or can find in the documentation. However, I've found 600 calls per 600 seconds, per token & per IP to be about where they stop you. I've also seen some application based rate limiting but don't have any numbers.

As a general rule, one call per second should not get rate limited. On the surface this seems very restrictive but remember you can batch certain calls and use the subscription API to get changes.

As you can access the Graph API on the client side via the Javascript SDK; I think if you travel your request for photos from the client, you won't hit any application limit as it's the user (each one with unique id) who's fetching data, not your application server (unique ID).

This may mean a huge refactor if everything you do go through a server. But it seems like the best solution if you have so many request (as it'll give a breath to your server).

Else, you can try batch request, but I guess you're already going this way if you have big traffic.


If nothing of this works, according to the Facebook Platform Policy you should contact them.

If you exceed, or plan to exceed, any of the following thresholds please contact us as you may be subject to additional terms: (>5M MAU) or (>100M API calls per day) or (>50M impressions per day).

jQuery if checkbox is checked

See main difference between ATTR | PROP | IS below:

Source: http://api.jquery.com/attr/

_x000D_
_x000D_
$( "input" )_x000D_
  .change(function() {_x000D_
    var $input = $( this );_x000D_
    $( "p" ).html( ".attr( 'checked' ): <b>" + $input.attr( "checked" ) + "</b><br>" +_x000D_
      ".prop( 'checked' ): <b>" + $input.prop( "checked" ) + "</b><br>" +_x000D_
      ".is( ':checked' ): <b>" + $input.is( ":checked" ) + "</b>" );_x000D_
  })_x000D_
  .change();
_x000D_
p {_x000D_
    margin: 20px 0 0;_x000D_
  }_x000D_
  b {_x000D_
    color: blue;_x000D_
  }
_x000D_
<meta charset="utf-8">_x000D_
  <title>attr demo</title>_x000D_
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
 _x000D_
<input id="check1" type="checkbox" checked="checked">_x000D_
<label for="check1">Check me</label>_x000D_
<p></p>_x000D_
 _x000D_
_x000D_
 _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

What is the purpose of "pip install --user ..."?

On macOS, the reason for using the --user flag is to make sure we don't corrupt the libraries the OS relies on. A conservative approach for many macOS users is to avoid installing or updating pip with a command that requires sudo. Thus, this includes installing to /usr/local/bin...

Ref: Installing python for Neovim (https://github.com/zchee/deoplete-jedi/wiki/Setting-up-Python-for-Neovim)

I'm not all clear why installing into /usr/local/bin is a risk on a Mac given the fact that the system only relies on python binaries in /Library/Frameworks/ and /usr/bin. I suspect it's because as noted above, installing into /usr/local/bin requires sudo which opens the door to making a costly mistake with the system libraries. Thus, installing into ~/.local/bin is a sure fire way to avoid this risk.

Ref: Using python on a Mac (https://docs.python.org/2/using/mac.html)

Finally, to the degree there is a benefit of installing packages into the /usr/local/bin, I wonder if it makes sense to change the owner of the directory from root to user? This would avoid having to use sudo while still protecting against making system-dependent changes.* Is this a security default a relic of how Unix systems were more often used in the past (as servers)? Or at minimum, just a good way to go for Mac users not hosting a server?

*Note: Mac's System Integrity Protection (SIP) feature also seems to protect the user from changing the system-dependent libraries.

- E