Programs & Examples On #Uservoice

Use this tag for questions about the UserVoice API.

How to use Visual Studio Code as Default Editor for Git

on windows 10 using the 64bit insiders edition the command should be:

git config --global core.editor "'C:\Program Files\Microsoft VS Code Insiders\bin\code-insiders.cmd'"

you can also rename the 'code-insiders.cmd' to 'code.cmd' in the 'Program Files' directory, in this way you can now use the command 'code .' to start editing the files on the . directory

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

I hesitate to post this answer, it is actually technically possible but it doesn't work that well in practice. The version numbers of the CLR and the core framework assemblies were not changed in 4.5. You still target v4.0.30319 of the CLR and the framework assembly version numbers are still 4.0.0.0. The only thing that's distinctive about the assembly manifest when you look at it with a disassembler like ildasm.exe is the presence of a [TargetFramework] attribute that says that 4.5 is needed, that would have to be altered. Not actually that easy, it is emitted by the compiler.

The biggest difference is not that visible, Microsoft made a long-overdue change in the executable header of the assemblies. Which specifies what version of Windows the executable is compatible with. XP belongs to a previous generation of Windows, started with Windows 2000. Their major version number is 5. Vista was the start of the current generation, major version number 6.

.NET compilers have always specified the minimum version number to be 4.00, the version of Windows NT and Windows 9x. You can see this by running dumpbin.exe /headers on the assembly. Sample output looks like this:

OPTIONAL HEADER VALUES
             10B magic # (PE32)
            ...
            4.00 operating system version
            0.00 image version
            4.00 subsystem version              // <=== here!!
               0 Win32 version
            ...

What's new in .NET 4.5 is that the compilers change that subsystem version to 6.00. A change that was over-due in large part because Windows pays attention to that number, beyond just checking if it is small enough. It also turns on appcompat features since it assumes that the program was written to work on old versions of Windows. These features cause trouble, particularly the way Windows lies about the size of a window in Aero is troublesome. It stops lying about the fat borders of an Aero window when it can see that the program was designed to run on a Windows version that has Aero.

You can alter that version number and set it back to 4.00 by running Editbin.exe on your assemblies with the /subsystem option. This answer shows a sample postbuild event.

That's however about where the good news ends, a significant problem is that .NET 4.5 isn't very compatible with .NET 4.0. By far the biggest hang-up is that classes were moved from one assembly to another. Most notably, that happened for the [Extension] attribute. Previously in System.Core.dll, it got moved to Mscorlib.dll in .NET 4.5. That's a kaboom on XP if you declare your own extension methods, your program says to look in Mscorlib for the attribute, enabled by a [TypeForwardedTo] attribute in the .NET 4.5 version of the System.Core reference assembly. But it isn't there when you run your program on .NET 4.0

And of course there's nothing that helps you stop using classes and methods that are only available on .NET 4.5. When you do, your program will fail with a TypeLoadException or MissingMethodException when run on 4.0

Just target 4.0 and all of these problems disappear. Or break that logjam and stop supporting XP, a business decision that programmers cannot often make but can certainly encourage by pointing out the hassles that it is causing. There is of course a non-zero cost to having to support ancient operating systems, just the testing effort is substantial. A cost that isn't often recognized by management, Windows compatibility is legendary, unless it is pointed out to them. Forward that cost to the client and they tend to make the right decision a lot quicker :) But we can't help you with that.

How to create file execute mode permissions in Git on Windows?

I have no touch and chmod command in my cmd.exe and git update-index --chmod=+x foo.sh doesn't work for me.

I finally resolve it by setting skip-worktree bit:

git update-index --skip-worktree --chmod=+x foo.sh

Using PI in python 2.7

To have access to stuff provided by math module, like pi. You need to import the module first:

import math
print (math.pi)

How to define custom exception class in Java, the easiest way?

package customExceptions;

public class MyException extends Exception{

    public MyException(String exc)
    {
        super(exc);
    }
    public String getMessage()
    {
        return super.getMessage();
    }
}

import customExceptions.MyException;

public class UseCustomException {

    MyException newExc=new MyException("This is a custom exception");

    public UseCustomException() throws MyException
    {
        System.out.println("Hello Back Again with custom exception");
        throw newExc;       
}

    public static void main(String args[])
    {
        try
        {
            UseCustomException use=new UseCustomException();
        }
        catch(MyException myEx)
        {
            System.out.println("This is my custom exception:" + myEx.getMessage());
        }
    }
}

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

How to compare only date in moment.js

The docs are pretty clear that you pass in a second parameter to specify granularity.

If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.

moment('2010-10-20').isAfter('2010-01-01', 'year'); // false
moment('2010-10-20').isAfter('2009-12-31', 'year'); // true

As the second parameter determines the precision, and not just a single value to check, using day will check for year, month and day.

For your case you would pass 'day' as the second parameter.

Maven: add a dependency to a jar by relative path

You can use eclipse to generate a runnable Jar : Export/Runable Jar file

Print: Entry, ":CFBundleIdentifier", Does Not Exist

I'v tried all of these solutions but the one that has worked for me is:

  1. run react-native upgrade
  2. open xcode
  3. run the application in xCode
  4. works fine!

How do I correctly upgrade angular 2 (npm) to the latest version?

Upgrade to latest Angular 5

Angular Dep packages: npm install @angular/{animations,common,compiler,core,forms,http,platform-browser,platform-browser-dynamic,router}@latest --save

Other packages that are installed by the angular cli npm install --save core-js@latest rxjs@latest zone.js@latest

Angular Dev packages: npm install --save-dev @angular/{compiler-cli,cli,language-service}@latest

Types Dev packages: npm install --save-dev @types/{jasmine,jasminewd2,node}@latest

Other packages that are installed as dev dev by the angular cli: npm install --save-dev codelyzer@latest jasmine-core@latest jasmine-spec-reporter@latest karma@latest karma-chrome-launcher@latest karma-cli@latest karma-coverage-istanbul-reporter@latest karma-jasmine@latest karma-jasmine-html-reporter@latest protractor@latest ts-node@latest tslint@latest

Install the latest supported version used by the Angular cli (don't do @latest): npm install --save-dev [email protected]

Rename file angular-cli.json to .angular-cli.json and update the content:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "project3-example"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "src/tsconfig.spec.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "e2e/tsconfig.e2e.json",
      "exclude": "**/node_modules/**"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}

Most Pythonic way to provide global configuration variables in config.py?

A small variation on Husky's idea that I use. Make a file called 'globals' (or whatever you like) and then define multiple classes in it, as such:

#globals.py

class dbinfo :      # for database globals
    username = 'abcd'
    password = 'xyz'

class runtime :
    debug = False
    output = 'stdio'

Then, if you have two code files c1.py and c2.py, both can have at the top

import globals as gl

Now all code can access and set values, as such:

gl.runtime.debug = False
print(gl.dbinfo.username)

People forget classes exist, even if no object is ever instantiated that is a member of that class. And variables in a class that aren't preceded by 'self.' are shared across all instances of the class, even if there are none. Once 'debug' is changed by any code, all other code sees the change.

By importing it as gl, you can have multiple such files and variables that lets you access and set values across code files, functions, etc., but with no danger of namespace collision.

This lacks some of the clever error checking of other approaches, but is simple and easy to follow.

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

'JSON' is undefined error in JavaScript in Internet Explorer

I had the very same problem recently. In my case on the top of a php script I had some code generationg obviously some extra output to the browser. Removal of empty lines (between ?> and html-tag ) and simple cleanup helped me out:

<?php 
include('../config.php');

//

ob_clean();
?>
<!DOCTYPE html>

Oracle ORA-12154: TNS: Could not resolve service name Error?

If you have a 32bit DSN and a 64bit DSN with same names, Windows will automatically choose the 64bit one and If your application is 32bit it shows this error. Just watch out for that.

jQuery: If this HREF contains

It doesn't work because it's syntactically nonsensical. You simply can't do that in JavaScript like that.

You can, however, use jQuery:

  if ($(this).is('[href$=?]'))

You can also just look at the "href" value:

  if (/\?$/.test(this.href))

How can I open a popup window with a fixed size using the HREF tag?

Since many browsers block popups by default and popups are really ugly, I recommend using lightbox or thickbox.

They are prettier and are not popups. They are extra HTML markups that are appended to your document's body with the appropriate CSS content.

http://jquery.com/demo/thickbox/

How can I specify my .keystore file with Spring Boot and Tomcat?

It turns out that there is a way to do this, although I'm not sure I've found the 'proper' way since this required hours of reading source code from multiple projects. In other words, this might be a lot of dumb work (but it works).

First, there is no way to get at the server.xml in the embedded Tomcat, either to augment it or replace it. This must be done programmatically.

Second, the 'require_https' setting doesn't help since you can't set cert info that way. It does set up forwarding from http to https, but it doesn't give you a way to make https work so the forwarding isnt helpful. However, use it with the stuff below, which does make https work.

To begin, you need to provide an EmbeddedServletContainerFactory as explained in the Embedded Servlet Container Support docs. The docs are for Java but the Groovy would look pretty much the same. Note that I haven't been able to get it to recognize the @Value annotation used in their example but its not needed. For groovy, simply put this in a new .groovy file and include that file on the command line when you launch spring boot.

Now, the instructions say that you can customize the TomcatEmbeddedServletContainerFactory class that you created in that code so that you can alter web.xml behavior, and this is true, but for our purposes its important to know that you can also use it to tailor server.xml behavior. Indeed, reading the source for the class and comparing it with the Embedded Tomcat docs, you see that this is the only place to do that. The interesting function is TomcatEmbeddedServletContainerFactory.addConnectorCustomizers(), which may not look like much from the Javadocs but actually gives you the Embedded Tomcat object to customize yourself. Simply pass your own implementation of TomcatConnectorCustomizer and set the things you want on the given Connector in the void customize(Connector con) function. Now, there are about a billion things you can do with the Connector and I couldn't find useful docs for it but the createConnector() function in this this guys personal Spring-embedded-Tomcat project is a very practical guide. My implementation ended up looking like this:

package com.deepdownstudios.server

import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.boot.*
import org.springframework.stereotype.*

@Configuration
class MyConfiguration {

@Bean
public EmbeddedServletContainerFactory servletContainer() {
final int port = 8443;
final String keystoreFile = "/path/to/keystore"
final String keystorePass = "keystore-password"
final String keystoreType = "pkcs12"
final String keystoreProvider = "SunJSSE"
final String keystoreAlias = "tomcat"

TomcatEmbeddedServletContainerFactory factory = 
        new TomcatEmbeddedServletContainerFactory(this.port);
factory.addConnectorCustomizers( new TomcatConnectorCustomizer() {
    void    customize(Connector con) {
        Http11NioProtocol proto = (Http11NioProtocol) con.getProtocolHandler();
            proto.setSSLEnabled(true);
        con.setScheme("https");
        con.setSecure(true);
        proto.setKeystoreFile(keystoreFile);
        proto.setKeystorePass(keystorePass);
        proto.setKeystoreType(keystoreType);
        proto.setProperty("keystoreProvider", keystoreProvider);
        proto.setKeyAlias(keystoreAlias);
    }
});
return factory;
}
}

The Autowiring will pick up this implementation an run with it. Once I fixed my busted keystore file (make sure you call keytool with -storetype pkcs12, not -storepass pkcs12 as reported elsewhere), this worked. Also, it would be far better to provide the parameters (port, password, etc) as configuration settings for testing and such... I'm sure its possible if you can get the @Value annotation to work with Groovy.

Is there a difference between `continue` and `pass` in a for loop in python?

continue will jump back to the top of the loop. pass will continue processing.

if pass is at the end for the loop, the difference is negligible as the flow would just back to the top of the loop anyway.

How to access data/data folder in Android device?

You can download a sigle file like that:

adb exec-out run-as debuggable.app.package.name cat files/file.mp4 > file.mp4

Before you download you might wan't to have a look at the file structure in your App-Directory. For this do the following steps THelper noticed above:

adb shell
run-as com.your.packagename 
cd files
ls -als .

The Android-Studio way Shahidul mentioned (https://stackoverflow.com/a/44089388/1256697) also work. For those who don't see the DeviceFile Explorer Option in the Menu: Be sure, to open the /android-Directory in Android Studio. E.g. react-native users have this inside of their Project-Folder right on the same Level as the /ios-Directory.

POST: sending a post request in a url itself

You can post data to a url with JavaScript & Jquery something like that:

$.post("www.abc.com/details", {
    json_string: JSON.stringify({name:"John", phone number:"+410000000"})
});

Pass arguments into C program from command line

You could use getopt.

 #include <ctype.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>

 int
 main (int argc, char **argv)
 {
   int bflag = 0;
   int sflag = 0;
   int index;
   int c;

   opterr = 0;

   while ((c = getopt (argc, argv, "bs")) != -1)
     switch (c)
       {
       case 'b':
         bflag = 1;
         break;
       case 's':
         sflag = 1;
         break;
       case '?':
         if (isprint (optopt))
           fprintf (stderr, "Unknown option `-%c'.\n", optopt);
         else
           fprintf (stderr,
                    "Unknown option character `\\x%x'.\n",
                    optopt);
         return 1;
       default:
         abort ();
       }

   printf ("bflag = %d, sflag = %d\n", bflag, sflag);

   for (index = optind; index < argc; index++)
     printf ("Non-option argument %s\n", argv[index]);
   return 0;
 }

ES6 export all values from object

I can't really recommend this solution work-around but it does function. Rather than exporting an object, you use named exports each member. In another file, import the first module's named exports into an object and export that object as default. Also export all the named exports from the first module using export * from './file1';

values/value.js

let a = 1;
let b = 2;
let c = 3;

export {a, b, c};

values/index.js

import * as values from './value';

export default values;
export * from './value';

index.js

import values, {a} from './values';

console.log(values, a); // {a: 1, b: 2, c: 3} 1

Addition for BigDecimal

BigDecimal no = new BigDecimal(10); //you can add like this also
no = no.add(new BigDecimal(10));
System.out.println(no);

20

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

Pretty-Print JSON in Java

If you are using a Java API for JSON Processing (JSR-353) implementation then you can specify the JsonGenerator.PRETTY_PRINTING property when you create a JsonGeneratorFactory.

The following example has been originally published on my blog post.

import java.util.*;
import javax.json.Json;
import javax.json.stream.*;

Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JsonGenerator.PRETTY_PRINTING, true);
JsonGeneratorFactory jgf = Json.createGeneratorFactory(properties);
JsonGenerator jg = jgf.createGenerator(System.out);

jg.writeStartObject()                    // {
    .write("name", "Jane Doe")           //    "name":"Jane Doe",
    .writeStartObject("address")         //    "address":{
        .write("type", 1)                //        "type":1,
        .write("street", "1 A Street")   //        "street":"1 A Street",
        .writeNull("city")               //        "city":null,
        .write("verified", false)        //        "verified":false
    .writeEnd()                          //    },
    .writeStartArray("phone-numbers")    //    "phone-numbers":[
        .writeStartObject()              //        {
            .write("number", "555-1111") //            "number":"555-1111",
            .write("extension", "123")   //            "extension":"123"
        .writeEnd()                      //        },
        .writeStartObject()              //        {
            .write("number", "555-2222") //            "number":"555-2222",
            .writeNull("extension")      //            "extension":null
        .writeEnd()                      //        }
    .writeEnd()                          //    ]
.writeEnd()                              // }
.close();

How to use a client certificate to authenticate and authorize in a Web API

Update:

Example from Microsoft:

https://docs.microsoft.com/en-us/azure/app-service/app-service-web-configure-tls-mutual-auth#special-considerations-for-certificate-validation

Original

This is how I got client certification working and checking that a specific Root CA had issued it as well as it being a specific certificate.

First I edited <src>\.vs\config\applicationhost.config and made this change: <section name="access" overrideModeDefault="Allow" />

This allows me to edit <system.webServer> in web.config and add the following lines which will require a client certification in IIS Express. Note: I edited this for development purposes, do not allow overrides in production.

For production follow a guide like this to set up the IIS:

https://medium.com/@hafizmohammedg/configuring-client-certificates-on-iis-95aef4174ddb

web.config:

<security>
  <access sslFlags="Ssl,SslNegotiateCert,SslRequireCert" />
</security>

API Controller:

[RequireSpecificCert]
public class ValuesController : ApiController
{
    // GET api/values
    public IHttpActionResult Get()
    {
        return Ok("It works!");
    }
}

Attribute:

public class RequireSpecificCertAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
            {
                ReasonPhrase = "HTTPS Required"
            };
        }
        else
        {
            X509Certificate2 cert = actionContext.Request.GetClientCertificate();
            if (cert == null)
            {
                actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                {
                    ReasonPhrase = "Client Certificate Required"
                };

            }
            else
            {
                X509Chain chain = new X509Chain();

                //Needed because the error "The revocation function was unable to check revocation for the certificate" happened to me otherwise
                chain.ChainPolicy = new X509ChainPolicy()
                {
                    RevocationMode = X509RevocationMode.NoCheck,
                };
                try
                {
                    var chainBuilt = chain.Build(cert);
                    Debug.WriteLine(string.Format("Chain building status: {0}", chainBuilt));

                    var validCert = CheckCertificate(chain, cert);

                    if (chainBuilt == false || validCert == false)
                    {
                        actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                        {
                            ReasonPhrase = "Client Certificate not valid"
                        };
                        foreach (X509ChainStatus chainStatus in chain.ChainStatus)
                        {
                            Debug.WriteLine(string.Format("Chain error: {0} {1}", chainStatus.Status, chainStatus.StatusInformation));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                }
            }

            base.OnAuthorization(actionContext);
        }
    }

    private bool CheckCertificate(X509Chain chain, X509Certificate2 cert)
    {
        var rootThumbprint = WebConfigurationManager.AppSettings["rootThumbprint"].ToUpper().Replace(" ", string.Empty);

        var clientThumbprint = WebConfigurationManager.AppSettings["clientThumbprint"].ToUpper().Replace(" ", string.Empty);

        //Check that the certificate have been issued by a specific Root Certificate
        var validRoot = chain.ChainElements.Cast<X509ChainElement>().Any(x => x.Certificate.Thumbprint.Equals(rootThumbprint, StringComparison.InvariantCultureIgnoreCase));

        //Check that the certificate thumbprint matches our expected thumbprint
        var validCert = cert.Thumbprint.Equals(clientThumbprint, StringComparison.InvariantCultureIgnoreCase);

        return validRoot && validCert;
    }
}

Can then call the API with client certification like this, tested from another web project.

[RoutePrefix("api/certificatetest")]
public class CertificateTestController : ApiController
{

    public IHttpActionResult Get()
    {
        var handler = new WebRequestHandler();
        handler.ClientCertificateOptions = ClientCertificateOption.Manual;
        handler.ClientCertificates.Add(GetClientCert());
        handler.UseProxy = false;
        var client = new HttpClient(handler);
        var result = client.GetAsync("https://localhost:44331/api/values").GetAwaiter().GetResult();
        var resultString = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
        return Ok(resultString);
    }

    private static X509Certificate GetClientCert()
    {
        X509Store store = null;
        try
        {
            store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);

            var certificateSerialNumber= "?81 c6 62 0a 73 c7 b1 aa 41 06 a3 ce 62 83 ae 25".ToUpper().Replace(" ", string.Empty);

            //Does not work for some reason, could be culture related
            //var certs = store.Certificates.Find(X509FindType.FindBySerialNumber, certificateSerialNumber, true);

            //if (certs.Count == 1)
            //{
            //    var cert = certs[0];
            //    return cert;
            //}

            var cert = store.Certificates.Cast<X509Certificate>().FirstOrDefault(x => x.GetSerialNumberString().Equals(certificateSerialNumber, StringComparison.InvariantCultureIgnoreCase));

            return cert;
        }
        finally
        {
            store?.Close();
        }
    }
}

How can I access Oracle from Python?

You can use any of the following way based on Service Name or SID whatever you have.

With SID:

import cx_Oracle
dsn_tns = cx_Oracle.makedsn('server', 'port', 'sid')
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
c = conn.cursor()
c.execute('select count(*) from TABLE_NAME')
for row in c:
   print(row)
conn.close()

OR

With Service Name:

import cx_Oracle
dsn_tns = cx_Oracle.makedsn('server', 'port', service_name='service_name')
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
c = conn.cursor()
c.execute('select count(*) from TABLE_NAME')
for row in c:
   print(row)
conn.close()

Catch multiple exceptions in one line (except block)

How do I catch multiple exceptions in one line (except block)

Do this:

try:
    may_raise_specific_errors():
except (SpecificErrorOne, SpecificErrorTwo) as error:
    handle(error) # might log or have some other default behavior...

The parentheses are required due to older syntax that used the commas to assign the error object to a name. The as keyword is used for the assignment. You can use any name for the error object, I prefer error personally.

Best Practice

To do this in a manner currently and forward compatible with Python, you need to separate the Exceptions with commas and wrap them with parentheses to differentiate from earlier syntax that assigned the exception instance to a variable name by following the Exception type to be caught with a comma.

Here's an example of simple usage:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    sys.exit(0)

I'm specifying only these exceptions to avoid hiding bugs, which if I encounter I expect the full stack trace from.

This is documented here: https://docs.python.org/tutorial/errors.html

You can assign the exception to a variable, (e is common, but you might prefer a more verbose variable if you have long exception handling or your IDE only highlights selections larger than that, as mine does.) The instance has an args attribute. Here is an example:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)

Note that in Python 3, the err object falls out of scope when the except block is concluded.

Deprecated

You may see code that assigns the error with a comma. This usage, the only form available in Python 2.5 and earlier, is deprecated, and if you wish your code to be forward compatible in Python 3, you should update the syntax to use the new form:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError), err: # don't do this in Python 2.6+
    print err
    print err.args
    sys.exit(0)

If you see the comma name assignment in your codebase, and you're using Python 2.5 or higher, switch to the new way of doing it so your code remains compatible when you upgrade.

The suppress context manager

The accepted answer is really 4 lines of code, minimum:

try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass

The try, except, pass lines can be handled in a single line with the suppress context manager, available in Python 3.4:

from contextlib import suppress

with suppress(IDontLikeYouException, YouAreBeingMeanException):
     do_something()

So when you want to pass on certain exceptions, use suppress.

Sum of Numbers C++

try this:

#include <iostream>
using namespace std;

int main()
{
    int positiveInteger;
    int startingNumber = 1;

    cout << "Please input an integer upto 100." << endl;

    cin >> positiveInteger;

    int result = 0;
    for (int i=startingNumber; i <= positiveInteger; i++)
    {
        result += i;
        cout << result;
    }

    cout << result;

    return 0;

}

How to check if a string contains only digits in Java

Try

String regex = "[0-9]+";

or

String regex = "\\d+";

As per Java regular expressions, the + means "one or more times" and \d means "a digit".

Note: the "double backslash" is an escape sequence to get a single backslash - therefore, \\d in a java String gives you the actual result: \d

References:


Edit: due to some confusion in other answers, I am writing a test case and will explain some more things in detail.

Firstly, if you are in doubt about the correctness of this solution (or others), please run this test case:

String regex = "\\d+";

// positive test cases, should all be "true"
System.out.println("1".matches(regex));
System.out.println("12345".matches(regex));
System.out.println("123456789".matches(regex));

// negative test cases, should all be "false"
System.out.println("".matches(regex));
System.out.println("foo".matches(regex));
System.out.println("aa123bb".matches(regex));

Question 1:

Isn't it necessary to add ^ and $ to the regex, so it won't match "aa123bb" ?

No. In java, the matches method (which was specified in the question) matches a complete string, not fragments. In other words, it is not necessary to use ^\\d+$ (even though it is also correct). Please see the last negative test case.

Please note that if you use an online "regex checker" then this may behave differently. To match fragments of a string in Java, you can use the find method instead, described in detail here:

Difference between matches() and find() in Java Regex

Question 2:

Won't this regex also match the empty string, "" ?*

No. A regex \\d* would match the empty string, but \\d+ does not. The star * means zero or more, whereas the plus + means one or more. Please see the first negative test case.

Question 3

Isn't it faster to compile a regex Pattern?

Yes. It is indeed faster to compile a regex Pattern once, rather than on every invocation of matches, and so if performance implications are important then a Pattern can be compiled and used like this:

Pattern pattern = Pattern.compile(regex);
System.out.println(pattern.matcher("1").matches());
System.out.println(pattern.matcher("12345").matches());
System.out.println(pattern.matcher("123456789").matches());

Is there a maximum number you can set Xmx to when trying to increase jvm memory?

Have a look at this for some common errors in setting the java heap. You've probably set the heap size to a larger value than your computer's physical memory.

You should avoid solving this problem by increasing the heap size. Instead, you should profile your application to see where you spend such a large amount of memory.

How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

I just checked with www.browserscope.org and with IE9 and Chrome 24 you can have 6 concurrent connections to a single domain, and up to 17 to multiple ones.

WCF gives an unsecured or incorrectly secured fault error

Mostly this exception happens when there is some errors in the server, the most common one is a wrong configuration of the authentication database, or authentication. In my case there was different clock synchronization make sure both client and server have same settings

Click on Time at your Right-Bottom side -> "Change date time settings..." -> "Internet Time" tab -> Change Settings... -> check the "Synchronise with an internet time server" option if it is unchecked -> from server dropdown select "times.windows.com" -> Update Now -> OK

Inline Form nested within Horizontal Form in Bootstrap 3

I had problems aligning the label to the input(s) elements so I transferred the label element inside the form-inline and form-group too...and it works..

<div class="form-group">
    <div class="col-xs-10">
        <div class="form-inline">
            <div class="form-group">
                <label for="birthday" class="col-xs-2 control-label">Birthday:</label>
            </div>
            <div class="form-group">
                <input type="text" class="form-control" placeholder="year"/>
            </div>
            <div class="form-group">
                <input type="text" class="form-control" placeholder="month"/>
            </div>
            <div class="form-group">
                <input type="text" class="form-control" placeholder="day"/>
            </div>
        </div>
    </div>
</div>

How can I add new item to the String array?

String a []=new String[1];

  a[0].add("kk" );
  a[1].add("pp");

Try this one...

Get paragraph text inside an element

Use jQuery:

$("li").find("p").html()

should work.

Remove the first character of a string

python 2.x

s = ":dfa:sif:e"
print s[1:]

python 3.x

s = ":dfa:sif:e"
print(s[1:])

both prints

dfa:sif:e

'React' must be in scope when using JSX react/react-in-jsx-scope?

Add below setting to .eslintrc.js / .eslintrc.json to ignore these errors:

  rules: {
    // suppress errors for missing 'import React' in files
   "react/react-in-jsx-scope": "off",
    // allow jsx syntax in js files (for next.js project)
   "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }], //should add ".ts" if typescript project
  }

Why? If you're using NEXT.js then you do not require to import React at top of files, nextjs does that for you.

Convert a string to integer with decimal in Python

What sort of rounding behavior do you want? Do you 2.67 to turn into 3, or 2. If you want to use rounding, try this:

s = '234.67'
i = int(round(float(s)))

Otherwise, just do:

s = '234.67'
i = int(float(s))

How to get image height and width using java?

So unfortunately, after trying all the answers from above, I did not get them to work after tireless times of trying. So I decided to do the real hack myself and I go this to work for me. I trust it would work perfectly for you too.

I am using this simple method to get the width of an image generated by the app and yet to be upload later for verification :

Pls. take note : you would have to enable permissions in manifest for access storage.

/I made it static and put in my Global class so I can reference or access it from just one source and if there is any modification, it would all have to be done at just one place. Just maintaining a DRY concept in java. (anyway) :)/

public static int getImageWidthOrHeight(String imgFilePath) {

            Log.d("img path : "+imgFilePath);

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(imgFilePath, o);

            int width_tmp = o.outWidth, height_tmp = o.outHeight;

            Log.d("Image width : ", Integer.toString(width_tmp) );

            //you can decide to rather return height_tmp to get the height.

            return width_tmp;

}

How should I use Outlook to send code snippets?

If you are using Outlook 2010, you can define your own style and select your formatting you want, in the Format options there is one option for Language, here you can specify the language and specify whether you want spell checker to ignore the text with this style.

With this style you can now paste the code as text and select your new style. Outlook will not correct the text and will not perform the spell check on it.

Below is the summary of the style I have defined for emailing the code snippets.

Do not check spelling or grammar, Border:
Box: (Single solid line, Orange,  0.5 pt Line width)
Pattern: Clear (Custom Color(RGB(253,253,217))), Style: Linked, Automatically update, Quick Style
Based on: HTML Preformatted

Android: Internet connectivity change listener

implementation 'com.treebo:internetavailabilitychecker:1.0.1'

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        InternetAvailabilityChecker.init(this);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        InternetAvailabilityChecker.getInstance().removeAllInternetConnectivityChangeListeners();
    }
}

(Built-in) way in JavaScript to check if a string is a valid number

You can use the result of Number when passing an argument to its constructor.

If the argument (a string) cannot be converted into a number, it returns NaN, so you can determinate if the string provided was a valid number or not.

Notes: Note when passing empty string or '\t\t' and '\n\t' as Number will return 0; Passing true will return 1 and false returns 0.

    Number('34.00') // 34
    Number('-34') // -34
    Number('123e5') // 12300000
    Number('123e-5') // 0.00123
    Number('999999999999') // 999999999999
    Number('9999999999999999') // 10000000000000000 (integer accuracy up to 15 digit)
    Number('0xFF') // 255
    Number('Infinity') // Infinity  

    Number('34px') // NaN
    Number('xyz') // NaN
    Number('true') // NaN
    Number('false') // NaN

    // cavets
    Number('    ') // 0
    Number('\t\t') // 0
    Number('\n\t') // 0

XML string to XML document

Using Linq to xml

Add a reference to System.Xml.Linq

and use

XDocument.Parse(string xmlString)

Edit: Sample follows, xml data (TestConfig.xml)..

<?xml version="1.0"?>
<Tests>
  <Test TestId="0001" TestType="CMD">
    <Name>Convert number to string</Name>
    <CommandLine>Examp1.EXE</CommandLine>
    <Input>1</Input>
    <Output>One</Output>
  </Test>
  <Test TestId="0002" TestType="CMD">
    <Name>Find succeeding characters</Name>
    <CommandLine>Examp2.EXE</CommandLine>
    <Input>abc</Input>
    <Output>def</Output>
  </Test>
  <Test TestId="0003" TestType="GUI">
    <Name>Convert multiple numbers to strings</Name>
    <CommandLine>Examp2.EXE /Verbose</CommandLine>
    <Input>123</Input>
    <Output>One Two Three</Output>
  </Test>
  <Test TestId="0004" TestType="GUI">
    <Name>Find correlated key</Name>
    <CommandLine>Examp3.EXE</CommandLine>
    <Input>a1</Input>
    <Output>b1</Output>
  </Test>
  <Test TestId="0005" TestType="GUI">
    <Name>Count characters</Name>
    <CommandLine>FinalExamp.EXE</CommandLine>
    <Input>This is a test</Input>
    <Output>14</Output>
  </Test>
  <Test TestId="0006" TestType="GUI">
    <Name>Another Test</Name>
    <CommandLine>Examp2.EXE</CommandLine>
    <Input>Test Input</Input>
    <Output>10</Output>
  </Test>
</Tests>

C# usage...

XElement root = XElement.Load("TestConfig.xml");
IEnumerable<XElement> tests =
    from el in root.Elements("Test")
    where (string)el.Element("CommandLine") == "Examp2.EXE"
    select el;
foreach (XElement el in tests)
    Console.WriteLine((string)el.Attribute("TestId"));

This code produces the following output: 0002 0006

Find when a file was deleted in Git

You can find the last commit which deleted file as follows:

git rev-list -n 1 HEAD -- [file_path]

Further information is available here

How to create a simple http proxy in node.js?

Here's a more optimized version of Mike's answer above that gets the websites Content-Type properly, supports POST and GET request, and uses your browsers User-Agent so websites can identify your proxy as a browser. You can just simply set the URL by changing url = and it will automatically set HTTP and HTTPS stuff without manually doing it.

var express = require('express')
var app = express()
var https = require('https');
var http = require('http');
const { response } = require('express');


app.use('/', function(clientRequest, clientResponse) {
    var url;
    url = 'https://www.google.com'
    var parsedHost = url.split('/').splice(2).splice(0, 1).join('/')
    var parsedPort;
    var parsedSSL;
    if (url.startsWith('https://')) {
        parsedPort = 443
        parsedSSL = https
    } else if (url.startsWith('http://')) {
        parsedPort = 80
        parsedSSL = http
    }
    var options = { 
      hostname: parsedHost,
      port: parsedPort,
      path: clientRequest.url,
      method: clientRequest.method,
      headers: {
        'User-Agent': clientRequest.headers['user-agent']
      }
    };  
  
    var serverRequest = parsedSSL.request(options, function(serverResponse) { 
      var body = '';   
      if (String(serverResponse.headers['content-type']).indexOf('text/html') !== -1) {
        serverResponse.on('data', function(chunk) {
          body += chunk;
        }); 
  
        serverResponse.on('end', function() {
          // Make changes to HTML files when they're done being read.
          body = body.replace(`example`, `Cat!` );
  
          clientResponse.writeHead(serverResponse.statusCode, serverResponse.headers);
          clientResponse.end(body);
        }); 
      }   
      else {
        serverResponse.pipe(clientResponse, {
          end: true
        }); 
        clientResponse.contentType(serverResponse.headers['content-type'])
      }   
    }); 
  
    serverRequest.end();
  });    


  app.listen(3000)
  console.log('Running on 0.0.0.0:3000')

enter image description here

enter image description here

How to upload a file and JSON data in Postman?

If you want to make a PUT request, just do everything as a POST request but add _method => PUT to your form-data parameters.

How to clear File Input

This works to

 $("#yourINPUTfile").val("");

How to compile LEX/YACC files on Windows?

As for today (2011-04-05, updated 2017-11-29) you will need the lastest versions of:

  1. flex-2.5.4a-1.exe

  2. bison-2.4.1-setup.exe

  3. After that, do a full install in a directory of your preference without spaces in the name. I suggest C:\GnuWin32. Do not install it in the default (C:\Program Files (x86)\GnuWin32) because bison has problems with spaces in directory names, not to say parenthesis.

  4. Also, consider installing Dev-CPP in the default directory (C:\Dev-Cpp)

  5. After that, set the PATH variable to include the bin directories of gcc (in C:\Dev-Cpp\bin) and flex\bison (in C:\GnuWin32\bin). To do that, copy this: ;C:\Dev-Cpp\bin;C:\GnuWin32\bin and append it to the end of the PATH variable, defined in the place show by this figure:
    step-by-step to set PATH variable under Win-7.
    If the figure is not in good resolution, you can see a step-by-step here.

  6. Open a prompt, cd to the directory where your ".l" and ".y" are, and compile them with:

    1. flex hello.l
    2. bison -dy hello.y
    3. gcc lex.yy.c y.tab.c -o hello.exe

Commands to create lexical analyzer, parser and executable.

You will be able to run the program. I made the sources for a simple test (the infamous Hello World):

Hello.l

%{

#include "y.tab.h"
int yyerror(char *errormsg);

%}

%%

("hi"|"oi")"\n"       { return HI;  }
("tchau"|"bye")"\n"   { return BYE; }
.                     { yyerror("Unknown char");  }

%%

int main(void)
{
   yyparse();
   return 0;
}

int yywrap(void)
{
   return 0;
}

int yyerror(char *errormsg)
{
    fprintf(stderr, "%s\n", errormsg);
    exit(1);
}

Hello.y

%{

#include <stdio.h>
#include <stdlib.h>
int yylex(void);
int yyerror(const char *s);

%}

%token HI BYE

%%

program: 
         hi bye
        ;

hi:     
        HI     { printf("Hello World\n");   }
        ;
bye:    
        BYE    { printf("Bye World\n"); exit(0); }
         ;

Edited: avoiding "warning: implicit definition of yyerror and yylex".

Disclaimer: remember, this answer is very old (since 2011!) and if you run into problems due to versions and features changing, you might need more research, because I can't update this answer to reflect new itens. Thanks and I hope this will be a good entry point for you as it was for many.

Updates: if something (really small changes) needs to be done, please check out the official repository at github: https://github.com/drbeco/hellex

Happy hacking.

Using DateTime in a SqlParameter for Stored Procedure, format error

Just use:

 param.AddWithValue("@Date_Of_Birth",DOB);

That will take care of all your problems.

Converting 'ArrayList<String> to 'String[]' in Java

List<String> list = ..;
String[] array = list.toArray(new String[0]);

For example:

List<String> list = new ArrayList<String>();
//add some stuff
list.add("android");
list.add("apple");
String[] stringArray = list.toArray(new String[0]);

The toArray() method without passing any argument returns Object[]. So you have to pass an array as an argument, which will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.

Important update: Originally the code above used new String[list.size()]. However, this blogpost reveals that due to JVM optimizations, using new String[0] is better now.

Add characters to a string in Javascript

var text ="";
for (var member in list) {
        text += list[member];
}

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

Rails 4 - passing variable to partial

Don't use locals in Rails 4.2+

In Rails 4.2 I had to remove the locals part and just use size: 30 instead. Otherwise, it wouldn't pass the local variable correctly.

For example, use this:

<%= render @users, size: 30 %>

How to list all AWS S3 objects in a bucket using Java

You don't want to list all 1000 object in your bucket at a time. A more robust solution will be to fetch a max of 10 objects at a time. You can do this with the withMaxKeys method.

The following code creates an S3 client, fetches 10 or less objects at a time and filters based on a prefix and generates a pre-signed url for the fetched object:

import com.amazonaws.HttpMethod;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;

import java.net.URL;
import java.util.Date;

/**
 * @author shabab
 * @since 21 Sep, 2020
 */
public class AwsMain {

    static final String ACCESS_KEY = "";
    static final String SECRET = "";
    static final Regions BUCKET_REGION = Regions.DEFAULT_REGION;
    static final String BUCKET_NAME = "";

    public static void main(String[] args) {
        BasicAWSCredentials awsCreds = new BasicAWSCredentials(ACCESS_KEY, SECRET);

        try {
            final AmazonS3 s3Client = AmazonS3ClientBuilder
                    .standard()
                    .withRegion(BUCKET_REGION)
                    .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                    .build();

            ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(BUCKET_NAME).withMaxKeys(10);
            ListObjectsV2Result result;

            do {
                result = s3Client.listObjectsV2(req);

                result.getObjectSummaries()
                        .stream()
                        .filter(s3ObjectSummary -> {
                            return s3ObjectSummary.getKey().contains("Market-subscriptions/")
                                    && !s3ObjectSummary.getKey().equals("Market-subscriptions/");
                        })
                        .forEach(s3ObjectSummary -> {

                            GeneratePresignedUrlRequest generatePresignedUrlRequest =
                                    new GeneratePresignedUrlRequest(BUCKET_NAME, s3ObjectSummary.getKey())
                                            .withMethod(HttpMethod.GET)
                                            .withExpiration(getExpirationDate());

                            URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);

                            System.out.println(s3ObjectSummary.getKey() + " Pre-Signed URL: " + url.toString());
                        });

                String token = result.getNextContinuationToken();
                req.setContinuationToken(token);

            } while (result.isTruncated());
        } catch (SdkClientException e) {
            e.printStackTrace();
        }

    }

    private static Date getExpirationDate() {
        Date expiration = new java.util.Date();
        long expTimeMillis = expiration.getTime();
        expTimeMillis += 1000 * 60 * 60;
        expiration.setTime(expTimeMillis);

        return expiration;
    }
}

How do I create a foreign key in SQL Server?

Necromancing.
Actually, doing this correctly is a little bit trickier.

You first need to check if the primary-key exists for the column you want to set your foreign key to reference to.

In this example, a foreign key on table T_ZO_SYS_Language_Forms is created, referencing dbo.T_SYS_Language_Forms.LANG_UID

-- First, chech if the table exists...
IF 0 < (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_TYPE = 'BASE TABLE'
    AND TABLE_SCHEMA = 'dbo'
    AND TABLE_NAME = 'T_SYS_Language_Forms'
)
BEGIN
    -- Check for NULL values in the primary-key column
    IF 0 = (SELECT COUNT(*) FROM T_SYS_Language_Forms WHERE LANG_UID IS NULL)
    BEGIN
        ALTER TABLE T_SYS_Language_Forms ALTER COLUMN LANG_UID uniqueidentifier NOT NULL 

        -- No, don't drop, FK references might already exist...
        -- Drop PK if exists 
        -- ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT pk_constraint_name 
        --DECLARE @pkDropCommand nvarchar(1000) 
        --SET @pkDropCommand = N'ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT ' + QUOTENAME((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
        --WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
        --AND TABLE_SCHEMA = 'dbo' 
        --AND TABLE_NAME = 'T_SYS_Language_Forms' 
        ----AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
        --))
        ---- PRINT @pkDropCommand 
        --EXECUTE(@pkDropCommand) 

        -- Instead do
        -- EXEC sp_rename 'dbo.T_SYS_Language_Forms.PK_T_SYS_Language_Forms1234565', 'PK_T_SYS_Language_Forms';


        -- Check if they keys are unique (it is very possible they might not be) 
        IF 1 >= (SELECT TOP 1 COUNT(*) AS cnt FROM T_SYS_Language_Forms GROUP BY LANG_UID ORDER BY cnt DESC)
        BEGIN

            -- If no Primary key for this table
            IF 0 =  
            (
                SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
                WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
                AND TABLE_SCHEMA = 'dbo' 
                AND TABLE_NAME = 'T_SYS_Language_Forms' 
                -- AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
            )
                ALTER TABLE T_SYS_Language_Forms ADD CONSTRAINT PK_T_SYS_Language_Forms PRIMARY KEY CLUSTERED (LANG_UID ASC)
            ;

            -- Adding foreign key
            IF 0 = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms') 
                ALTER TABLE T_ZO_SYS_Language_Forms WITH NOCHECK ADD CONSTRAINT FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms FOREIGN KEY(ZOLANG_LANG_UID) REFERENCES T_SYS_Language_Forms(LANG_UID); 
        END -- End uniqueness check
        ELSE
            PRINT 'FSCK, this column has duplicate keys, and can thus not be changed to primary key...' 
    END -- End NULL check
    ELSE
        PRINT 'FSCK, need to figure out how to update NULL value(s)...' 
END 

Installing PDO driver on MySQL Linux server

On Ubuntu you should be able to install the necessary PDO parts from apt using sudo apt-get install php5-mysql

There is no limitation between using PDO and mysql_ simultaneously. You will however need to create two connections to your DB, one with mysql_ and one using PDO.

Git: Recover deleted (remote) branch

I'm not an expert. But you can try

git fsck --full --no-reflogs | grep commit

to find the HEAD commit of deleted branch and get them back.

Function pointer as parameter

The correct way to do this is:

typedef void (*callback_function)(void); // type for conciseness

callback_function disconnectFunc; // variable to store function pointer type

void D::setDisconnectFunc(callback_function pFunc)
{
    disconnectFunc = pFunc; // store
}

void D::disconnected()
{
    disconnectFunc(); // call
    connected = false;
}

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

I'm using a popup to show the map in a new window. I'm using the following url

https://www.google.com/maps?z=15&daddr=LATITUDE,LONGITUDE

HTML snippet

<a target='_blank' href='https://www.google.com/maps?z=15&daddr=${location.latitude},${location.longitude}'>Calculate route</a>

How to do a HTTP HEAD request from the windows command line?

I'd download PuTTY and run a telnet session on port 80 to the webserver you want

HEAD /resource HTTP/1.1
Host: www.example.com

You could alternatively download Perl and try LWP's HEAD command. Or write your own script.

Excel formula to display ONLY month and year?

Very easy, trial and error. Go to the cell you want the month in. Type the Month, go to the next cell and type the year, something weird will come up but then go to your number section click on the little arrow in the right bottom and highlight text and it will change to the year you originally typed

Pandas - Get first row value of a given column

To select the ith row, use iloc:

In [31]: df_test.iloc[0]
Out[31]: 
ATime     1.2
X         2.0
Y        15.0
Z         2.0
Btime     1.2
C        12.0
D        25.0
E        12.0
Name: 0, dtype: float64

To select the ith value in the Btime column you could use:

In [30]: df_test['Btime'].iloc[0]
Out[30]: 1.2

There is a difference between df_test['Btime'].iloc[0] (recommended) and df_test.iloc[0]['Btime']:

DataFrames store data in column-based blocks (where each block has a single dtype). If you select by column first, a view can be returned (which is quicker than returning a copy) and the original dtype is preserved. In contrast, if you select by row first, and if the DataFrame has columns of different dtypes, then Pandas copies the data into a new Series of object dtype. So selecting columns is a bit faster than selecting rows. Thus, although df_test.iloc[0]['Btime'] works, df_test['Btime'].iloc[0] is a little bit more efficient.

There is a big difference between the two when it comes to assignment. df_test['Btime'].iloc[0] = x affects df_test, but df_test.iloc[0]['Btime'] may not. See below for an explanation of why. Because a subtle difference in the order of indexing makes a big difference in behavior, it is better to use single indexing assignment:

df.iloc[0, df.columns.get_loc('Btime')] = x

df.iloc[0, df.columns.get_loc('Btime')] = x (recommended):

The recommended way to assign new values to a DataFrame is to avoid chained indexing, and instead use the method shown by andrew,

df.loc[df.index[n], 'Btime'] = x

or

df.iloc[n, df.columns.get_loc('Btime')] = x

The latter method is a bit faster, because df.loc has to convert the row and column labels to positional indices, so there is a little less conversion necessary if you use df.iloc instead.


df['Btime'].iloc[0] = x works, but is not recommended:

Although this works, it is taking advantage of the way DataFrames are currently implemented. There is no guarantee that Pandas has to work this way in the future. In particular, it is taking advantage of the fact that (currently) df['Btime'] always returns a view (not a copy) so df['Btime'].iloc[n] = x can be used to assign a new value at the nth location of the Btime column of df.

Since Pandas makes no explicit guarantees about when indexers return a view versus a copy, assignments that use chained indexing generally always raise a SettingWithCopyWarning even though in this case the assignment succeeds in modifying df:

In [22]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])
In [24]: df['bar'] = 100
In [25]: df['bar'].iloc[0] = 99
/home/unutbu/data/binky/bin/ipython:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self._setitem_with_indexer(indexer, value)

In [26]: df
Out[26]: 
  foo  bar
0   A   99  <-- assignment succeeded
2   B  100
1   C  100

df.iloc[0]['Btime'] = x does not work:

In contrast, assignment with df.iloc[0]['bar'] = 123 does not work because df.iloc[0] is returning a copy:

In [66]: df.iloc[0]['bar'] = 123
/home/unutbu/data/binky/bin/ipython:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

In [67]: df
Out[67]: 
  foo  bar
0   A   99  <-- assignment failed
2   B  100
1   C  100

Warning: I had previously suggested df_test.ix[i, 'Btime']. But this is not guaranteed to give you the ith value since ix tries to index by label before trying to index by position. So if the DataFrame has an integer index which is not in sorted order starting at 0, then using ix[i] will return the row labeled i rather than the ith row. For example,

In [1]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])

In [2]: df
Out[2]: 
  foo
0   A
2   B
1   C

In [4]: df.ix[1, 'foo']
Out[4]: 'C'

How do I configure git to ignore some files locally?

You can simply add a .gitignore file to your home directory, i.e. $HOME/.gitignore or ~/.gitignore. Then tell git to use that file with the command:

git config --global core.excludesfile ~/.gitignore

This is a normal .gitignore file which git references when deciding what to ignore. Since it's in your home directory, it applies only to you and doesn't pollute any project .gitignore files.

I've been using this approach for years with great results.

How do I set the selenium webdriver get timeout?

The solution of driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS) will work on the pages with synch loading. This does not solve, however, the problem on pages loading stuff in async, then the tests will fail all the time if we set the pageLoadTimeOut.

Why does the 260 character path length limit exist in Windows?

As to how to cope with the path size limitation on Windows - using 7zip to pack (and unpack) your path-length sensitive files seems like a viable workaround. I've used it to transport several IDE installations (those Eclipse plugin paths, yikes!) and piles of autogenerated documentation and haven't had a single problem so far.

Not really sure how it evades the 260 char limit set by Windows (from a technical PoV), but hey, it works!

More details on their SourceForge page here:

"NTFS can actually support pathnames up to 32,000 characters in length."

7-zip also support such long names.

But it's disabled in SFX code. Some users don't like long paths, since they don't understand how to work with them. That is why I have disabled it in SFX code.

and release notes:

9.32 alpha 2013-12-01

  • Improved support for file pathnames longer than 260 characters.

4.44 beta 2007-01-20

  • 7-Zip now supports file pathnames longer than 260 characters.

IMPORTANT NOTE: For this to work properly, you'll need to specify the destination path in the 7zip "Extract" dialog directly, rather than dragging & dropping the files into the intended folder. Otherwise the "Temp" folder will be used as an interim cache and you'll bounce into the same 260 char limitation once Windows Explorer starts moving the files to their "final resting place". See the replies to this question for more information.

MVC4 input field placeholder

This works:

@Html.TextBox("name", null,  new { placeholder = "Text" })

"multiple target patterns" Makefile error

Besides having to escape colons as in the original answer, I have found if the indentation is off you could potentially get the same problem. In one makefile, I had to replace spaces with a tab and that allowed me to get past the error.

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

Comment the following lines in the web.config file.

<modules>
    <!--<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>-->
</modules>

<handlers>
    <remove name="WebServiceHandlerFactory-ISAPI-2.0"/>
    <!--<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    <add name="ScriptResource" verb="GET" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>-->
</handlers>

This will work.

Change the row color in DataGridView based on the quantity of a cell value

Using the CellFormating event and the e argument:

If CInt(e.Value) < 5 Then e.CellStyle.ForeColor = Color.Red

How to connect Android app to MySQL database?

Use android vollley, it is very fast and you can betterm manipulate requests. Send post request using Volley and receive in PHP

Basically, you will create a map with key-value params for the php request(POST/GET), the php will do the desired processing and you will return the data as JSON(json_encode()). Then you can either parse the JSON as needed or use GSON from Google to let it do the parsing.

A fast way to delete all rows of a datatable at once

That's the easiest way to delete all rows from the table in dbms via DataAdapter. But if you want to do it in one batch, you can set the DataAdapter's UpdateBatchSize to 0(unlimited).

Another way would be to use a simple SqlCommand with CommandText DELETE FROM Table:

using(var con = new SqlConnection(ConfigurationSettings.AppSettings["con"]))
using(var cmd = new SqlCommand())
{
    cmd.CommandText = "DELETE FROM Table";
    cmd.Connection = con;
    con.Open();
    int numberDeleted = cmd.ExecuteNonQuery();  // all rows deleted
}

But if you instead only want to remove the DataRows from the DataTable, you just have to call DataTable.Clear. That would prevent any rows from being deleted in dbms.

How to hide Bootstrap modal with javascript?

$('#modal').modal('hide'); 
//hide the modal

$('body').removeClass('modal-open'); 
//modal-open class is added on body so it has to be removed

$('.modal-backdrop').remove();
//need to remove div with modal-backdrop class

Sometimes adding a WCF Service Reference generates an empty reference.cs

In my case I had a solution with VB Web Forms project that referenced a C# UserControl. Both the VB project and the CS project had a Service Reference to the same service. The reference appeared under Service References in the VB project and under the Connected Services grouping in the CS (framework) project.

In order to update the service reference (ie, get the Reference.vb file to not be empty) in the VB web forms project, I needed to REMOVE THE CS PROJECT, then update the VB Service Reference, then add the CS project back into the solution.

Stacking DIVs on top of each other?

If you mean by literally putting one on the top of the other, one on the top (Same X, Y positions, but different Z position), try using the z-index CSS attribute. This should work (untested)

<div>
    <div style='z-index: 1'>1</div>
    <div style='z-index: 2'>2</div>
    <div style='z-index: 3'>3</div>
    <div style='z-index: 4'>4</div>
</div>

This should show 4 on the top of 3, 3 on the top of 2, and so on. The higher the z-index is, the higher the element is positioned on the z-axis. I hope this helped you :)

Zipping a file in bash fails

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

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

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

Utilities like dos2unix will fix it:

 dos2unix <backup.bash >improved-backup.sh 

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

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

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

Python iterating through object attributes

UPDATED

For python 3, you should use items() instead of iteritems()

PYTHON 2

for attr, value in k.__dict__.iteritems():
        print attr, value

PYTHON 3

for attr, value in k.__dict__.items():
        print(attr, value)

This will print

'names', [a list with names]
'tweet', [a list with tweet]

IsNumeric function in c#

You could make a helper method. Something like:

public bool IsNumeric(string input) {
    int test;
    return int.TryParse(input, out test);
}

php $_POST array empty upon form submission

In my case (php page on OVH mutualisé server) enctype="text/plain" does not work ($_POST and corresponding $_REQUEST is empty), the other examples below work. `

<form action="?" method="post">
<!-- in this case, my google chrome 45.0.2454.101 uses -->
<!--     Content-Type:application/x-www-form-urlencoded -->
    <input name="say" value="Hi">
    <button>Send my greetings</button>
</form>

<form action="?" method="post" enctype="application/x-www-form-urlencoded">
    <input name="say" value="Hi">
    <button>Send my application/x-www-form-urlencoded greetings</button>
</form>

<form action="?" method="post"  enctype="multipart/form-data">
    <input name="say" value="Hi">
    <button>Send my multipart/form-data greetings</button>
</form>

<form action="?" method="post" enctype="text/plain"><!-- not working -->
    <input name="say" value="Hi">
    <button>Send my text/plain greetings</button>
</form>

`

More here: method="post" enctype="text/plain" are not compatible?

Circle-Rectangle collision detection (intersection)

I developed this algorithm while making this game: https://mshwf.github.io/mates/

If the circle touches the square, then the distance between the centerline of the circle and the centerline of the square should equal (diameter+side)/2. So, let's have a variable named touching that holds that distance. The problem was: which centerline should I consider: the horizontal or the vertical? Consider this frame:

enter image description here

Each centerline gives different distances, and only one is a correct indication to a no-collision, but using our human intuition is a start to understand how the natural algorithm works.

They are not touching, which means that the distance between the two centerlines should be greater than touching, which means that the natural algorithm picks the horizontal centerlines (the vertical centerlines says there's a collision!). By noticing multiple circles, you can tell: if the circle intersects with the vertical extension of the square, then we pick the vertical distance (between the horizontal centerlines), and if the circle intersects with the horizontal extension, we pick the horizontal distance:

enter image description here

Another example, circle number 4: it intersects with the horizontal extension of the square, then we consider the horizontal distance which is equal to touching.

Ok, the tough part is demystified, now we know how the algorithm will work, but how we know with which extension the circle intersects? It's easy actually: we calculate the distance between the most right x and the most left x (of both the circle and the square), and the same for the y-axis, the one with greater value is the axis with the extension that intersects with the circle (if it's greater than diameter+side then the circle is outside the two square extensions, like circle #7). The code looks like:

right = Math.max(square.x+square.side, circle.x+circle.rad);
left = Math.min(square.x, circle.x-circle.rad);

bottom = Math.max(square.y+square.side, circle.y+circle.rad);
top = Math.min(square.y, circle.y-circle.rad);

if (right - left > down - top) {
 //compare with horizontal distance
}
else {
 //compare with vertical distance
}

/*These equations assume that the reference point of the square is at its top left corner, and the reference point of the circle is at its center*/

Dark Theme for Visual Studio 2010 With Productivity Power Tools

So, I tested above themes and found out none of them are showing proper color combination when using Productivity Power Tools in Visual Studio.
Ultimately, being a fan of dark themes, I created one myself which is fully supported from VS2005 to VS2013.
Here's the screenshot

enter image description here

Download this dark theme from here: Obsidian Meets Visual Studio

To use this theme go to Tools -> Import and Export Setting... -> import selected environment settings -> (optional to save current settings) -> Browse select and then Finish.

Output an Image in PHP

For the next guy or gal hitting this problem, here's what worked for me:

ob_start();
header('Content-Type: '.$mimetype);
ob_end_clean();
$fp = fopen($fullyQualifiedFilepath, 'rb');
fpassthru($fp);
exit;

You need all of that, and only that. If your mimetype varies, have a look at PHP's mime_content_type($filepath)

Can you have multiple $(document).ready(function(){ ... }); sections?

You can also do it the following way:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
 $(document).ready(function(){
     $("#hide").click(function(){
     $("#test").hide();
     });
     $("#show").click(function(){
     $("#test").show();
     });
 });
</script>
</head>

<body>
<h2>This is a test of jQuery!</h2>
<p id="test">This is a hidden paragraph.</p>
<button id="hide">Click me to hide</button>
<button id="show">Click me to show</button>
</body>

the previous answers showed using multiple named functions inside a single .ready block, or a single unnamed function in the .ready block, with another named function outside the .ready block. I found this question while researching if there was a way to have multiple unnamed functions inside the .ready block - I could not get the syntax correct. I finally figured it out, and hoped that by posting my test code I would help others looking for the answer to the same question I had

What are forward declarations in C++?

Why forward-declare is necessary in C++

The compiler wants to ensure you haven't made spelling mistakes or passed the wrong number of arguments to the function. So, it insists that it first sees a declaration of 'add' (or any other types, classes or functions) before it is used.

This really just allows the compiler to do a better job of validating the code, and allows it to tidy up loose ends so it can produce a neat looking object file. If you didn't have to forward declare things, the compiler would produce an object file that would have to contain information about all the possible guesses as to what the function 'add' might be. And the linker would have to contain very clever logic to try and work out which 'add' you actually intended to call, when the 'add' function may live in a different object file the linker is joining with the one that uses add to produce a dll or exe. It's possible that the linker may get the wrong add. Say you wanted to use int add(int a, float b), but accidentally forgot to write it, but the linker found an already existing int add(int a, int b) and thought that was the right one and used that instead. Your code would compile, but wouldn't be doing what you expected.

So, just to keep things explicit and avoid the guessing etc, the compiler insists you declare everything before it is used.

Difference between declaration and definition

As an aside, it's important to know the difference between a declaration and a definition. A declaration just gives enough code to show what something looks like, so for a function, this is the return type, calling convention, method name, arguments and their types. But the code for the method isn't required. For a definition, you need the declaration and then also the code for the function too.

How forward-declarations can significantly reduce build times

You can get the declaration of a function into your current .cpp or .h file by #includ'ing the header that already contains a declaration of the function. However, this can slow down your compile, especially if you #include a header into a .h instead of .cpp of your program, as everything that #includes the .h you're writing would end up #include'ing all the headers you wrote #includes for too. Suddenly, the compiler has #included pages and pages of code that it needs to compile even when you only wanted to use one or two functions. To avoid this, you can use a forward-declaration and just type the declaration of the function yourself at the top of the file. If you're only using a few functions, this can really make your compiles quicker compared to always #including the header. For really large projects, the difference could be an hour or more of compile time bought down to a few minutes.

Break cyclic references where two definitions both use each other

Additionally, forward-declarations can help you break cycles. This is where two functions both try to use each other. When this happens (and it is a perfectly valid thing to do), you may #include one header file, but that header file tries to #include the header file you're currently writing.... which then #includes the other header, which #includes the one you're writing. You're stuck in a chicken and egg situation with each header file trying to re #include the other. To solve this, you can forward-declare the parts you need in one of the files and leave the #include out of that file.

Eg:

File Car.h

#include "Wheel.h"  // Include Wheel's definition so it can be used in Car.
#include <vector>

class Car
{
    std::vector<Wheel> wheels;
};

File Wheel.h

Hmm... the declaration of Car is required here as Wheel has a pointer to a Car, but Car.h can't be included here as it would result in a compiler error. If Car.h was included, that would then try to include Wheel.h which would include Car.h which would include Wheel.h and this would go on forever, so instead the compiler raises an error. The solution is to forward declare Car instead:

class Car;     // forward declaration

class Wheel
{
    Car* car;
};

If class Wheel had methods which need to call methods of car, those methods could be defined in Wheel.cpp and Wheel.cpp is now able to include Car.h without causing a cycle.

How to count rows with SELECT COUNT(*) with SQLAlchemy?

Query for just a single known column:

session.query(MyTable.col1).count()

What does the ??!??! operator do in C?

It's a C trigraph. ??! is |, so ??!??! is the operator ||

How to initialise a string from NSData in Swift

Objective - C

NSData *myStringData = [@"My String" dataUsingEncoding:NSUTF8StringEncoding]; 
NSString *myStringFromData = [[NSString alloc] initWithData:myStringData encoding:NSUTF8StringEncoding];
NSLog(@"My string value: %@",myStringFromData);

Swift

//This your data containing the string
   let myStringData = "My String".dataUsingEncoding(NSUTF8StringEncoding)

   //Use this method to convert the data into String
   let myStringFromData =  String(data:myStringData!, encoding: NSUTF8StringEncoding)

   print("My string value:" + myStringFromData!)

http://objectivec2swift.blogspot.in/2016/03/coverting-nsdata-to-nsstring-or-convert.html

Use of the MANIFEST.MF file in Java

Manifest.MF contains information about the files contained in the JAR file.

Whenever a JAR file is created a default manifest.mf file is created inside META-INF folder and it contains the default entries like this:

Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)

These are entries as “header:value” pairs. The first one specifies the manifest version and second one specifies the JDK version with which the JAR file is created.

Main-Class header: When a JAR file is used to bundle an application in a package, we need to specify the class serving an entry point of the application. We provide this information using ‘Main-Class’ header of the manifest file,

Main-Class: {fully qualified classname}

The ‘Main-Class’ value here is the class having main method. After specifying this entry we can execute the JAR file to run the application.

Class-Path header: Most of the times we need to access the other JAR files from the classes packaged inside application’s JAR file. This can be done by providing their fully qualified paths in the manifest file using ‘Class-Path’ header,

Class-Path: {jar1-name jar2-name directory-name/jar3-name}

This header can be used to specify the external JAR files on the same local network and not inside the current JAR.

Package version related headers: When the JAR file is used for package versioning the following headers are used as specified by the Java language specification:

Headers in a manifest
Header                  | Definition
-------------------------------------------------------------------
Name                    | The name of the specification.
Specification-Title     | The title of the specification.
Specification-Version   | The version of the specification.
Specification-Vendor    | The vendor of the specification.
Implementation-Title    | The title of the implementation.
Implementation-Version  | The build number of the implementation.
Implementation-Vendor   | The vendor of the implementation.

Package sealing related headers:

We can also specify if any particular packages inside a JAR file should be sealed meaning all the classes defined in that package must be archived in the same JAR file. This can be specified with the help of ‘Sealed’ header,

Name: {package/some-package/} Sealed:true

Here, the package name must end with ‘/’.

Enhancing security with manifest files:

We can use manifest files entries to ensure the security of the web application or applet it packages with the different attributes as ‘Permissions’, ‘Codebae’, ‘Application-Name’, ‘Trusted-Only’ and many more.

META-INF folder:

This folder is where the manifest file resides. Also, it can contain more files containing meta data about the application. For example, in an EJB module JAR file, this folder contains the EJB deployment descriptor for the EJB module along with the manifest file for the JAR. Also, it contains the xml file containing mapping of an abstract EJB references to concrete container resources of the application server on which it will be run.

Reference:
https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html

Adding values to Arraylist

First simple rule: never use the String(String) constructor, it is absolutely useless (*).

So arr.add("ss") is just fine.

With 3 it's slightly different: 3 is an int literal, which is not an object. Only objects can be put into a List. So the int will need to be converted into an Integer object. In most cases that will be done automagically for you (that process is called autoboxing). It effectively does the same thing as Integer.valueOf(3) which can (and will) avoid creating a new Integer instance in some cases.

So actually writing arr.add(3) is usually a better idea than using arr.add(new Integer(3)), because it can avoid creating a new Integer object and instead reuse and existing one.

Disclaimer: I am focusing on the difference between the second and third code blocks here and pretty much ignoring the generics part. For more information on the generics, please check out the other answers.

(*) there are some obscure corner cases where it is useful, but once you approach those you'll know never to take absolute statements as absolutes ;-)

Please initialize the log4j system properly. While running web service

If you are using Logger.getLogger(ClassName.class) then place your log4j.properties file in your class path:

yourproject/javaresoures/src/log4j.properties (Put inside src folder)

How to convert a color integer to a hex String in Android?

String int2string = Integer.toHexString(INTEGERColor); //to ARGB
String HtmlColor = "#"+ int2string.substring(int2string.length() - 6, int2string.length()); // a stupid way to append your color

bootstrap initially collapsed element

If removing the in class doesn't work for you, such was my case, you can force the collapsed initial state using the CSS display property:

...
<div id="collapseOne" class="accordion-body collapse" style="display: none;">
...

get the value of DisplayName attribute

Following Rich Tebb's and Matt Baker's answer, I wanted to use the ReflectionExtensions methods in a LINQ query, but it didn't work, so I've made this method for it to work.

If DisplayNameAttribute is set the method will return it, otherwise it will return the MemberInfo name.

Test method:

static void Main(string[] args)
{
    var lst = new List<Test>();
    lst.Add(new Test("coucou1", "kiki1"));
    lst.Add(new Test("coucou2", "kiki2"));
    lst.Add(new Test("coucou3", "kiki3"));
    lst.Add(new Test("coucou4", "kiki4"));
    lst.ForEach(i => 
        Console.WriteLine(i.GetAttributeName<Test>(t => t.Name) + ";" + i.GetAttributeName<Test>(t=>t.t2)));
}

Test method output:

Test method output

The class with DisplayName1 Attribute:

public class Test
{
    public Test() { }
    public Test(string name, string T2)
    {
        Name = name;
        t2 = T2;
    }
    [DisplayName("toto")]
    public string Name { get; set; }
    public string t2 { get; set; }
}

And the extension method:

public static string GetAttributeName<T>(this T itm, Expression<Func<T, object>> propertyExpression)
{
    var memberInfo = GetPropertyInformation(propertyExpression.Body);
    if (memberInfo == null)
    {
        throw new ArgumentException(
            "No property reference expression was found.",
            "propertyExpression");
    }

    var pi = typeof(T).GetProperty(memberInfo.Name);
    var ret = pi.GetCustomAttributes(typeof(DisplayNameAttribute), true).Cast<DisplayNameAttribute>().SingleOrDefault();
    return ret != null ? ret.DisplayName : pi.Name;

}

How to split a string between letters and digits (or between digits and letters)?

Use two different patterns: [0-9]* and [a-zA-Z]* and split twice by each of them.

Web scraping with Python

Make your life easier by using CSS Selectors

I know I have come late to party but I have a nice suggestion for you.

Using BeautifulSoup is already been suggested I would rather prefer using CSS Selectors to scrape data inside HTML

import urllib2
from bs4 import BeautifulSoup

main_url = "http://www.example.com"

main_page_html  = tryAgain(main_url)
main_page_soup = BeautifulSoup(main_page_html)

# Scrape all TDs from TRs inside Table
for tr in main_page_soup.select("table.class_of_table"):
   for td in tr.select("td#id"):
       print(td.text)
       # For acnhors inside TD
       print(td.select("a")[0].text)
       # Value of Href attribute
       print(td.select("a")[0]["href"])

# This is method that scrape URL and if it doesnt get scraped, waits for 20 seconds and then tries again. (I use it because my internet connection sometimes get disconnects)
def tryAgain(passed_url):
    try:
        page  = requests.get(passed_url,headers = random.choice(header), timeout = timeout_time).text
        return page
    except Exception:
        while 1:
            print("Trying again the URL:")
            print(passed_url)
            try:
                page  = requests.get(passed_url,headers = random.choice(header), timeout = timeout_time).text
                print("-------------------------------------")
                print("---- URL was successfully scraped ---")
                print("-------------------------------------")
                return page
            except Exception:
                time.sleep(20)
                continue 

pythonw.exe or python.exe?

See here: http://docs.python.org/using/windows.html

pythonw.exe "This suppresses the terminal window on startup."

How can I get enum possible values in a MySQL database?

It is extraordinary how none of you has thought that if you are using an enum field it means that the values to be assigned are known "a priori".

Therefore if the values are known "a priori" the best ways to manage them is through a very simple Enum class.

Kiss rule and save one database call.

<?php
class Genre extends \SplEnum {
 const male = "Male";
 const female = "Female";
}

http://it2.php.net/manual/en/class.splenum.php

Argparse optional positional arguments?

parser.add_argument also has a switch required. You can use required=False. Here is a sample snippet with Python 2.7:

parser = argparse.ArgumentParser(description='get dir')
parser.add_argument('--dir', type=str, help='dir', default=os.getcwd(), required=False)
args = parser.parse_args()

What does the 'b' character do in front of a string literal?

From server side, if we send any response, it will be sent in the form of byte type, so it will appear in the client as b'Response from server'

In order get rid of b'....' simply use below code:

Server file:

stri="Response from server"    
c.send(stri.encode())

Client file:

print(s.recv(1024).decode())

then it will print Response from server

How do I convert strings between uppercase and lowercase in Java?

Yes. There are methods on the String itself for this.

Note that the result depends on the Locale the JVM is using. Beware, locales is an art in itself.

Why do package names often begin with "com"

It's just a namespace definition to avoid collision of class names. The com.domain.package.Class is an established Java convention wherein the namespace is qualified with the company domain in reverse.

What is the size of an enum in C?

An enum is only guaranteed to be large enough to hold int values. The compiler is free to choose the actual type used based on the enumeration constants defined so it can choose a smaller type if it can represent the values you define. If you need enumeration constants that don't fit into an int you will need to use compiler-specific extensions to do so.

jQuery: Count number of list elements?

try

$("#mylist").children().length

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

echo

Not having return type

print

Have return type

print_r()

Outputs as formatted,

What's the difference between an element and a node in XML?

Now i know ,the element is one of node

All node types in here"http://www.w3schools.com/dom/dom_nodetype.asp"

Element is between the start tag and end in the end tag

So text node is a node , but not a element.

What jar should I include to use javax.persistence package in a hibernate based application?

In general, i agree with above answers that recommend to add maven dependency, but i prefer following solution.

Add a dependency with API classes for full JavaEE profile:

<properties>
    <javaee-api.version>7.0</javaee-api.version>
    <hibernate-entitymanager.version>5.1.3.Final</hibernate-entitymanager.version>
</properties>

<depencies>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>${javaee-api.version}</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

Also add dependency with particular JPA provider like antonycc suggested:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>${hibernate-entitymanager.version}</version>
</dependency>

Note <scope>provided</scope> in API dependency section: this means that corresponding jar will not be exported into artifact's lib/, but will be provided by application server. Make sure your application server implements specified version of JavaEE API.

CSS fixed width in a span

<style type="text/css">

span {
  position:absolute;
  width: 50px;
}

</style>

You can do this method for assigning width for inline elements

Java Mouse Event Right Click

To avoid any ambiguity, use the utilities methods from SwingUtilities :

SwingUtilities.isLeftMouseButton(MouseEvent anEvent) SwingUtilities.isRightMouseButton(MouseEvent anEvent) SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)

bootstrap datepicker setDate format dd/mm/yyyy

for me it is daterangepicker worked by this :

     $('#host1field').daterangepicker({
                   locale: {
                            format: 'DD/MM/YYYY'
                            }
                 });

What equivalents are there to TortoiseSVN, on Mac OSX?

I use svnX (http://code.google.com/p/svnx/downloads/list), it is free and usable, but not as user friendly as tortoise. It shows you the review before commit with diff for every file... but sometimes I still had to go to command line to fix some things

How to test Spring Data repositories?

I solved this by using this way -

    @RunWith(SpringRunner.class)
    @EnableJpaRepositories(basePackages={"com.path.repositories"})
    @EntityScan(basePackages={"com.model"})
    @TestPropertySource("classpath:application.properties")
    @ContextConfiguration(classes = {ApiTestConfig.class,SaveActionsServiceImpl.class})
    public class SaveCriticalProcedureTest {

        @Autowired
        private SaveActionsService saveActionsService;
        .......
        .......
}

firefox proxy settings via command line

This is the final compiled solution which worked for me... Tried and tested...

Steps to Change Proxy settings in Mozilla Firefox via cmd in Windows

  1. cd /D "%APPDATA%\Mozilla\Firefox\Profiles"
  2. cd *.default

To Replace Already Present Proxy Settings with User-defined ones

  1. powershell -Command "(gc prefs.js) -replace 'user_pref(\"network.proxy.http\", \"already present IP\")\;', 'user_pref(\"network.proxy.http\", \"your http proxy ip\");' | Set-Content prefs.js"
  2. powershell -Command "(gc prefs.js) -replace 'user_pref(\"network.proxy.http_port\", already present port)\;', 'user_pref(\"network.proxy.http_port\", your http proxy port);' | Set-Content prefs.js"
  3. powershell -Command "(gc prefs.js) -replace 'user_pref(\"network.proxy.share_proxy_settings\", already present value)\;', 'user_pref(\"network.proxy.share_proxy_settings\", true);' | Set-Content prefs.js"
  4. powershell -Command "(gc prefs.js) -replace 'user_pref(\"network.proxy.type\", already present value)\;', 'user_pref(\"network.proxy.type\", 1);' | Set-Content prefs.js"

    0 - No Proxy

    1 - Manual Proxy Configuration

    4 - Auto detect Proxy Settings

    5 - Use System Settings(default)

  5. cd %windir%

To Check Already Present Proxy Settings

  1. cd C:\Users\{username}\AppData\Roaming\Mozilla\Firefox\Profiles\sat2m7dr.default\
  2. find /i "network.proxy" prefs.js

To Start Firefox from CMD using your defined proxy settings

  1. cd C:\Program Files\
  2. cd "Mozilla Firefox"
  3. firefox.exe -ProfileManager
  4. Select default from the list (default-release is selected by default) and click ok.

NOTE: You may not have to run step 14 again. Instead you can directly run firefox.exe

How do I change the hover over color for a hover over table in Bootstrap?

try:

.table-hover > tbody > tr.active:hover > th {
                background-color: #color;
            }

Cannot use a leading ../ to exit above the top directory

You can use ~/img/myImage.png instead of ../img/myImage.png to avoid this error in ASP.NET pages.

Get the current file name in gulp.src()

I found this plugin to be doing what I was expecting: gulp-using

Simple usage example: Search all files in project with .jsx extension

gulp.task('reactify', function(){
        gulp.src(['../**/*.jsx']) 
            .pipe(using({}));
        ....
    });

Output:

[gulp] Using gulpfile /app/build/gulpfile.js
[gulp] Starting 'reactify'...
[gulp] Finished 'reactify' after 2.92 ms
[gulp] Using file /app/staging/web/content/view/logon.jsx
[gulp] Using file /app/staging/web/content/view/components/rauth.jsx

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

Try this, it will combine your arrays removing duplicates

array1 = ["foo", "bar"]
array2 = ["foo1", "bar1"]

array3 = array1|array2

http://www.ruby-doc.org/core/classes/Array.html

Further documentation look at "Set Union"

LIKE vs CONTAINS on SQL Server

Having run both queries on a SQL Server 2012 instance, I can confirm the first query was fastest in my case.

The query with the LIKE keyword showed a clustered index scan.

The CONTAINS also had a clustered index scan with additional operators for the full text match and a merge join.

Plan

Visual Studio: Relative Assembly References Paths

As mentioned before, you can manually edit your project's .csproj file in order to apply it manually.

I also noticed that Visual Studio 2013 attempts to apply a relative path to the reference hintpath, probably because of an attempt to make the project file more portable.

Best C/C++ Network Library

Aggregated List of Libraries

How can I revert multiple Git commits (already pushed) to a published repository?

git revert HEAD -m 1

In the above code line. "Last argument represents"

  • 1 - reverts one commits. 2 - reverts last commits. n - reverts last n commits

or

git reset --hard siriwjdd

How should I use try-with-resources with JDBC?

There's no need for the outer try in your example, so you can at least go down from 3 to 2, and also you don't need closing ; at the end of the resource list. The advantage of using two try blocks is that all of your code is present up front so you don't have to refer to a separate method:

public List<User> getUser(int userId) {
    String sql = "SELECT id, username FROM users WHERE id = ?";
    List<User> users = new ArrayList<>();
    try (Connection con = DriverManager.getConnection(myConnectionURL);
         PreparedStatement ps = con.prepareStatement(sql)) {
        ps.setInt(1, userId);
        try (ResultSet rs = ps.executeQuery()) {
            while(rs.next()) {
                users.add(new User(rs.getInt("id"), rs.getString("name")));
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return users;
}

Check if string is upper, lower, or mixed case in Python

There are a number of "is methods" on strings. islower() and isupper() should meet your needs:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

Here's an example of how to use those methods to classify a list of strings:

>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']

What does cmd /C mean?

/C Carries out the command specified by the string and then terminates.

You can get all the cmd command line switches by typing cmd /?.

Angular 4 checkbox change value

Inside your component class:

checkValue(event: any) {
  this.userForm.patchValue({
    state: event
  })
}

Now in controls you have value A or B

How to add elements of a string array to a string array list?

I prefer this,

List<String> temp = Arrays.asList(speciesArr);
species.addAll(temp);

The reason is Arrays.asList() method will create a fixed sized List. So if you directly store it into species then you will not be able to add any more element, still its not read-only. You can surely edit your items. So take it into temporary list.

Alternative for this is,

Collections.addAll(species, speciesArr);

In this case, you can add, edit, remove your items.

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

Sorry, no reputation to add this as a comment. So it goes as an complementary answer.

Depending on how often you will call clock_gettime(), you should keep in mind that only some of the "clocks" are provided by Linux in the VDSO (i.e. do not require a syscall with all the overhead of one -- which only got worse when Linux added the defenses to protect against Spectre-like attacks).

While clock_gettime(CLOCK_MONOTONIC,...), clock_gettime(CLOCK_REALTIME,...), and gettimeofday() are always going to be extremely fast (accelerated by the VDSO), this is not true for, e.g. CLOCK_MONOTONIC_RAW or any of the other POSIX clocks.

This can change with kernel version, and architecture.

Although most programs don't need to pay attention to this, there can be latency spikes in clocks accelerated by the VDSO: if you hit them right when the kernel is updating the shared memory area with the clock counters, it has to wait for the kernel to finish.

Here's the "proof" (GitHub, to keep bots away from kernel.org): https://github.com/torvalds/linux/commit/2aae950b21e4bc789d1fc6668faf67e8748300b7

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

I same thing happen with me, If your code is correct and then also give 405 error. this error due to some authorization problem. go to authorization menu and change to "Inherit auth from parent".

Authorization Type options menu Authorization Inherit auth from parent selected

How can I read a text file in Android?

Shortest form for small text files (in Kotlin):

val reader = FileReader(path)
val txt = reader.readText()
reader.close()

Multiple models in a view

Another way is to use:

@model Tuple<LoginViewModel,RegisterViewModel>

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

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

In the view:

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

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

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

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

if an actionlink is required you can use:

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

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

Example:

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

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

Check Whether a User Exists

Login to the server. grep "username" /etc/passwd This will display the user details if present.

How to secure phpMyAdmin

The best way to secure phpMyAdmin is the combination of all these 4:

1. Change phpMyAdmin URL
2. Restrict access to localhost only.
3. Connect through SSH and tunnel connection to a local port on your computer
4. Setup SSL to already encrypted SSH connection. (x2 security)

Here is how to do these all with: Ubuntu 16.4 + Apache 2 Setup Windows computer + PuTTY to connect and tunnel the SSH connection to a local port:

# Secure Web Serving of phpMyAdmin (change URL of phpMyAdmin):

    sudo nano /etc/apache2/conf-available/phpmyadmin.conf
            /etc/phpmyadmin/apache.conf
        Change: phpmyadmin URL by this line:
            Alias /newphpmyadminname /usr/share/phpmyadmin
        Add: AllowOverride All
            <Directory /usr/share/phpmyadmin>
                Options FollowSymLinks
                DirectoryIndex index.php
                AllowOverride Limit
                ...
        sudo systemctl restart apache2
        sudo nano /usr/share/phpmyadmin/.htaccess
            deny from all
            allow from 127.0.0.1

        alias phpmyadmin="sudo nano /usr/share/phpmyadmin/.htaccess"
        alias myip="echo ${SSH_CONNECTION%% *}"

# Secure Web Access to phpMyAdmin:

        Make sure pma.yourdomain.com is added to Let's Encrypt SSL configuration:
            https://www.digitalocean.com/community/tutorials/how-to-secure-apache-with-let-s-encrypt-on-ubuntu-16-04

        PuTTY => Source Port (local): <local_free_port> - Destination: 127.0.0.1:443 (OR localhost:443) - Local, Auto - Add

        C:\Windows\System32\drivers\etc
            Notepad - Run As Administrator - open: hosts
                127.0.0.1 pma.yourdomain.com

        https://pma.yourdomain.com:<local_free_port>/newphpmyadminname/ (HTTPS OK, SSL VPN OK)
        https://localhost:<local_free_port>/newphpmyadminname/ (HTTPS ERROR, SSL VPN OK)

        # Check to make sure you are on SSH Tunnel
            1. Windows - CMD:
                ping pma.yourdomain.com
                ping www.yourdomain.com

                # See PuTTY ports:
                netstat -ano |find /i "listening"

            2. Test live:
                https://pma.yourdomain.com:<local_free_port>/newphpmyadminname/

If you are able to do these all successfully,

you now have your own url path for phpmyadmin,
you denied all access to phpmyadmin except localhost,
you connected to your server with SSH,
you tunneled that connection to a port locally,
you connected to phpmyadmin as if you are on your server,
you have additional SSL conenction (HTTPS) to phpmyadmin in case something leaks or breaks.

Python: fastest way to create a list of n lists

The list comprehensions actually are implemented more efficiently than explicit looping (see the dis output for example functions) and the map way has to invoke an ophaque callable object on every iteration, which incurs considerable overhead overhead.

Regardless, [[] for _dummy in xrange(n)] is the right way to do it and none of the tiny (if existent at all) speed differences between various other ways should matter. Unless of course you spend most of your time doing this - but in that case, you should work on your algorithms instead. How often do you create these lists?

Signing a Windows EXE file

You can try using Microsoft's Sign Tool

You download it as part of the Windows SDK for Windows Server 2008 and .NET 3.5. Once downloaded you can use it from the command line like so:

signtool sign /a MyFile.exe

This signs a single executable, using the "best certificate" available. (If you have no certificate, it will show a SignTool error message.)

Or you can try:

signtool signwizard

This will launch a wizard that will walk you through signing your application. (This option is not available after Windows SDK 7.0.)


If you'd like to get a hold of certificate that you can use to test your process of signing the executable you can use the .NET tool Makecert.

Certificate Creation Tool (Makecert.exe)

Once you've created your own certificate and have used it to sign your executable, you'll need to manually add it as a Trusted Root CA for your machine in order for UAC to tell the user running it that it's from a trusted source. Important. Installing a certificate as ROOT CA will endanger your users privacy. Look what happened with DELL. You can find more information for accomplishing this both in code and through Windows in:

Hopefully that provides some more information for anyone attempting to do this!

How to fix request failed on channel 0

in my case, the SFTP server will reject your SSH connection.

How to run mysql command on bash?

I have written a shell script which will read data from properties file and then run mysql script on shell script. sharing this may help to others.

#!/bin/bash
    PROPERTY_FILE=filename.properties

    function getProperty {
       PROP_KEY=$1
       PROP_VALUE=`cat $PROPERTY_FILE | grep "$PROP_KEY" | cut -d'=' -f2`
       echo $PROP_VALUE
    }

    echo "# Reading property from $PROPERTY_FILE"
    DB_USER=$(getProperty "db.username")
    DB_PASS=$(getProperty "db.password")
    ROOT_LOC=$(getProperty "root.location")
    echo $DB_USER
    echo $DB_PASS
    echo $ROOT_LOC
    echo "Writing on DB ... "
    mysql -u$DB_USER -p$DB_PASS dbname<<EOFMYSQL

    update tablename set tablename.value_ = "$ROOT_LOC" where tablename.name_="Root directory location";
    EOFMYSQL
    echo "Writing root location($ROOT_LOC) is done ... "
    counter=`mysql -u${DB_USER} -p${DB_PASS} dbname -e "select count(*) from tablename where tablename.name_='Root directory location' and tablename.value_ = '$ROOT_LOC';" | grep -v "count"`;

    if [ "$counter" = "1" ]
    then
    echo "ROOT location updated"
    fi

How to analyze disk usage of a Docker container

You can use

docker history IMAGE_ID

to see how the image size is ditributed between its various sub-components.

javax.websocket client simple example

Use this library org.java_websocket

First thing you should import that library in build.gradle

repositories {
 mavenCentral()
 }

then add the implementation in dependency{}

implementation "org.java-websocket:Java-WebSocket:1.3.0"

Then you can use this code

In your activity declare object for Websocketclient like

private WebSocketClient mWebSocketClient;

then add this method for callback

 private void ConnectToWebSocket() {
URI uri;
try {
    uri = new URI("ws://your web socket url");
} catch (URISyntaxException e) {
    e.printStackTrace();
    return;
}

mWebSocketClient = new WebSocketClient(uri) {
    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        Log.i("Websocket", "Opened");
        mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
    }

    @Override
    public void onMessage(String s) {
        final String message = s;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TextView textView = (TextView)findViewById(R.id.edittext_chatbox);
                textView.setText(textView.getText() + "\n" + message);
            }
        });
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        Log.i("Websocket", "Closed " + s);
    }

    @Override
    public void onError(Exception e) {
        Log.i("Websocket", "Error " + e.getMessage());
    }
};
mWebSocketClient.connect();

}

Importing the private-key/public-certificate pair in the Java KeyStore

A keystore needs a keystore file. The KeyStore class needs a FileInputStream. But if you supply null (instead of FileInputStream instance) an empty keystore will be loaded. Once you create a keystore, you can verify its integrity using keytool.

Following code creates an empty keystore with empty password

  KeyStore ks2 = KeyStore.getInstance("jks");
  ks2.load(null,"".toCharArray());
  FileOutputStream out = new FileOutputStream("C:\\mykeytore.keystore");
  ks2.store(out, "".toCharArray());

Once you have the keystore, importing certificate is very easy. Checkout this link for the sample code.

How to return 2 values from a Java method?

Instead of returning an array that contains the two values or using a generic Pair class, consider creating a class that represents the result that you want to return, and return an instance of that class. Give the class a meaningful name. The benefits of this approach over using an array are type safety and it will make your program much easier to understand.

Note: A generic Pair class, as proposed in some of the other answers here, also gives you type safety, but doesn't convey what the result represents.

Example (which doesn't use really meaningful names):

final class MyResult {
    private final int first;
    private final int second;

    public MyResult(int first, int second) {
        this.first = first;
        this.second = second;
    }

    public int getFirst() {
        return first;
    }

    public int getSecond() {
        return second;
    }
}

// ...

public static MyResult something() {
    int number1 = 1;
    int number2 = 2;

    return new MyResult(number1, number2);
}

public static void main(String[] args) {
    MyResult result = something();
    System.out.println(result.getFirst() + result.getSecond());
}

Error: EPERM: operation not permitted, unlink 'D:\Sources\**\node_modules\fsevents\node_modules\abbrev\package.json'

This was the only thing that worked for me:

npm cache clean --force

npm install -g npm@latest --force

rm package-lock.json

npm i -force

How can I know when an EditText loses focus?

Have your Activity implement OnFocusChangeListener() if you want a factorized use of this interface, example:

public class Shops extends AppCompatActivity implements View.OnFocusChangeListener{

In your OnCreate you can add a listener for example:

editTextResearch.setOnFocusChangeListener(this);
editTextMyWords.setOnFocusChangeListener(this);
editTextPhone.setOnFocusChangeListener(this);

then android studio will prompt you to add the method from the interface, accept it... it will be like:

@Override
public void onFocusChange(View v, boolean hasFocus) {
// todo your code here...
}

and as you've got a factorized code, you'll just have to do that:

@Override
public void onFocusChange(View v, boolean hasFocus) {
   if (hasFocus) {
        editTextResearch.setText("");
        editTextMyWords.setText("");
        editTextPhone.setText("");
    }
    if (!hasFocus){
        editTextResearch.setText("BlaBlaBla");
        editTextMyWords.setText(" One Two Tree!");
        editTextPhone.setText("\"your phone here:\"");
    }
}

anything you code in the !hasFocus is for the behavior of the item that loses focus, that should do the trick! But beware that in such state, the change of focus might overwrite the user's entries!

How to use a variable inside a regular expression?

more example

I have configus.yml with flows files

"pattern":
  - _(\d{14})_
"datetime_string":
  - "%m%d%Y%H%M%f"

in python code I use

data_time_real_file=re.findall(r""+flows[flow]["pattern"][0]+"", latest_file)

Stored Procedure error ORA-06550

Could you try this one:

create or replace 
procedure point_triangle
IS
BEGIN
  FOR thisteam in (select P.FIRSTNAME,P.LASTNAME, SUM(P.PTS) S from PLAYERREGULARSEASON P  where P.TEAM = 'IND'  group by P.FIRSTNAME, P.LASTNAME order by SUM(P.PTS) DESC)
  LOOP
    dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME  || ':' || thisteam.S);
  END LOOP;

END;

Why is nginx responding to any domain name?

I was unable to resolve my problem with any of the other answers. I resolved the issue by checking to see if the host matched and returning a 403 if it did not. (I had some random website pointing to my web servers content. I'm guessing to hijack search rank)

server {
    listen 443;
    server_name example.com;

    if ($host != "example.com") {
        return 403;
    }

    ...
}

What is java pojo class, java bean, normal class?

POJO = Plain Old Java Object. It has properties, getters and setters for respective properties. It may also override Object.toString() and Object.equals().

Java Beans : See Wiki link.

Normal Class : Any java Class.

How to replace a whole line with sed?

You can also use sed's change line to accomplish this:

sed -i "/aaa=/c\aaa=xxx" your_file_here

This will go through and find any lines that pass the aaa= test, which means that the line contains the letters aaa=. Then it replaces the entire line with aaa=xxx. You can add a ^ at the beginning of the test to make sure you only get the lines that start with aaa= but that's up to you.

Push items into mongo array via mongoose

Another way to push items into array using Mongoose is- $addToSet, if you want only unique items to be pushed into array. $push operator simply adds the object to array whether or not the object is already present, while $addToSet does that only if the object is not present in the array so as not to incorporate duplicacy.

PersonModel.update(
  { _id: person._id }, 
  { $addToSet: { friends: friend } }
);

This will look for the object you are adding to array. If found, does nothing. If not, adds it to the array.

References:

Is it better practice to use String.format over string Concatenation in Java?

Here's the same test as above with the modification of calling the toString() method on the StringBuilder. The results below show that the StringBuilder approach is just a bit slower than String concatenation using the + operator.

file: StringTest.java

class StringTest {

  public static void main(String[] args) {

    String formatString = "Hi %s; Hi to you %s";

    long start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
        String s = String.format(formatString, i, +i * 2);
    }

    long end = System.currentTimeMillis();
    System.out.println("Format = " + ((end - start)) + " millisecond");

    start = System.currentTimeMillis();

    for (int i = 0; i < 1000000; i++) {
        String s = "Hi " + i + "; Hi to you " + i * 2;
    }

    end = System.currentTimeMillis();

    System.out.println("Concatenation = " + ((end - start)) + " millisecond");

    start = System.currentTimeMillis();

    for (int i = 0; i < 1000000; i++) {
        StringBuilder bldString = new StringBuilder("Hi ");
        bldString.append(i).append("Hi to you ").append(i * 2).toString();
    }

    end = System.currentTimeMillis();

    System.out.println("String Builder = " + ((end - start)) + " millisecond");

  }
}

Shell Commands : (compile and run StringTest 5 times)

> javac StringTest.java
> sh -c "for i in \$(seq 1 5); do echo \"Run \${i}\"; java StringTest; done"

Results :

Run 1
Format = 1290 millisecond
Concatenation = 115 millisecond
String Builder = 130 millisecond

Run 2
Format = 1265 millisecond
Concatenation = 114 millisecond
String Builder = 126 millisecond

Run 3
Format = 1303 millisecond
Concatenation = 114 millisecond
String Builder = 127 millisecond

Run 4
Format = 1297 millisecond
Concatenation = 114 millisecond
String Builder = 127 millisecond

Run 5
Format = 1270 millisecond
Concatenation = 114 millisecond
String Builder = 126 millisecond

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

Simply install Win64 OpenSSL v1.0.2a or Win32 OpenSSL v1.0.2a, you can download these from http://slproweb.com/products/Win32OpenSSL.html. Works out of the box, no configuration needed.

How to get the current location in Google Maps Android API v2?

It will give the current location.

mMap.setMyLocationEnabled(true);
Location userLocation = mMap.getMyLocation();
        LatLng myLocation = null;
        if (userLocation != null) {
            myLocation = new LatLng(userLocation.getLatitude(),
                    userLocation.getLongitude());
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation,
                    mMap.getMaxZoomLevel()-5));

Real differences between "java -server" and "java -client"?

From Goetz - Java Concurrency in Practice:

  1. Debugging tip: For server applications, be sure to always specify the -server JVM command line switch when invoking the JVM, even for development and testing. The server JVM performs more optimization than the client JVM, such as hoisting variables out of a loop that are not modified in the loop; code that might appear to work in the development environment (client JVM) can break in the deployment environment (server JVM). For example, had we “forgotten” to declare the variable asleep as volatile in Listing 3.4, the server JVM could hoist the test out of the loop (turning it into an infinite loop), but the client JVM would not. An infinite loop that shows up in development is far less costly than one that only shows up in production.

Listing 3.4. Counting sheep.

volatile boolean asleep; ... while (!asleep) countSomeSheep();

My emphasis. YMMV

Convert UTC/GMT time to local time

This code block uses universal time to convert current DateTime object then converts it back to local DateTime. Works perfect for me I hope it helps!

CreatedDate.ToUniversalTime().ToLocalTime();

How to Call Controller Actions using JQuery in ASP.NET MVC

You can easily call any controller's action using jQuery AJAX method like this:

Note in this example my controller name is Student

Controller Action

 public ActionResult Test()
 {
     return View();
 }

In Any View of this above controller you can call the Test() action like this:

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
    $(document).ready(function () {
        $.ajax({
            url: "@Url.Action("Test", "Student")",
            success: function (result, status, xhr) {
                alert("Result: " + status + " " + xhr.status + " " + xhr.statusText)
            },
            error: function (xhr, status, error) {
                alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
            }
        });
    });
</script>

Authentication failed because remote party has closed the transport stream

using (var client = new HttpClient(handler))
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, apiEndPoint)).ConfigureAwait(false);
                await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            }

This worked for me

How to list imported modules?

let say you've imported math and re:

>>import math,re

now to see the same use

>>print(dir())

If you run it before the import and after the import, one can see the difference.

PreparedStatement with list of parameters in a IN clause

You can't replace ? in your query with an arbitrary number of values. Each ? is a placeholder for a single value only. To support an arbitrary number of values, you'll have to dynamically build a string containing ?, ?, ?, ... , ? with the number of question marks being the same as the number of values you want in your in clause.

How to change text and background color?

Colors are bit-encoded. If You want to change the Text color in C++ language There are many ways. In the console, you can change the properties of output.click this icon of the console and go to properties and change color.

The second way is calling the system colors.

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
    //Changing Font Colors of the System

    system("Color 7C");
    cout << "\t\t\t ****CEB Electricity Bill Calculator****\t\t\t " << endl;
    cout << "\t\t\t  ***                MENU           ***\t\t\t  " <<endl;

    return 0;

}

FPDF utf-8 encoding (HOW-TO)

You can make a class to extend FPDF and add this:

class utfFPDF extends FPDF {

function Cell($w, $h=0, $txt="", $border=0, $ln=0, $align='', $fill=false, $link='')
{
    if (!empty($txt)){
        if (mb_detect_encoding($txt, 'UTF-8', false)){
            $txt = iconv('UTF-8', 'ISO-8859-5', $txt);

        }
    }
    parent::Cell($w, $h, $txt, $border, $ln, $align, $fill, $link);

} 

}

How to improve performance of ngRepeat over a huge dataset (angular.js)?

I recommend to see this:

Optimizing AngularJS: 1200ms to 35ms

they made a new directive by optimizing ng-repeat at 4 parts:

Optimization#1: Cache DOM elements

Optimization#2: Aggregate watchers

Optimization#3: Defer element creation

Optimization#4: Bypass watchers for hidden elements

the project is here on github:

Usage:

1- include these files in your single-page app:

  • core.js
  • scalyr.js
  • slyEvaluate.js
  • slyRepeat.js

2- add module dependency:

var app = angular.module("app", ['sly']);

3- replace ng-repeat

<tr sly-repeat="m in rows"> .....<tr>

ENjoY!

How do I sum values in a column that match a given condition using pandas?

You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :

df[df['a']==1]['b'].sum()

or you can also try :

sum(df[df['a']==1]['b'])

Another way could be to use the numpy library of python :

import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())

Initializing multiple variables to the same value in Java

You can declare multiple variables, and initialize multiple variables, but not both at the same time:

 String one,two,three;
 one = two = three = "";

However, this kind of thing (especially the multiple assignments) would be frowned upon by most Java developers, who would consider it the opposite of "visually simple".

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

You should probably set all of the cookie properties not just the value of it. setPath(), setDomain() ... etc

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

In My case, I had a added async at app.js like shown below.

const App = async() => {
return(
<Text>Hello world</Text>
)
}

But it was not necessary, when testing something I had added it and it was no longer required. After removing it, as shown below, things started working.

 const App =() => {
    return(
    <Text>Hello world</Text>
    )
}

jquery remove "selected" attribute of option?

It's something in the way jQuery translates to IE8, not necessarily the browser itself.

I was able to work around by going old school and breaking out of jQuery for one line:

document.getElementById('myselect').selectedIndex = -1;

Should functions return null or an empty object?

I typically return null. It provides a quick and easy mechanism to detect if something screwed up without throwing exceptions and using tons of try/catch all over the place.

Python 3 turn range to a list

The reason why Python3 lacks a function for directly getting a ranged list is because the original Python3 designer was quite novice in Python2. He only considered the use of range() function in a for loop, thus, the list should never need to be expanded. In fact, very often we do need to use the range() function to produce a list and pass into a function.

Therefore, in this case, Python3 is less convenient as compared to Python2 because:

  • In Python2, we have xrange() and range();
  • In Python3, we have range() and list(range())

Nonetheless, you can still use list expansion in this way:

[*range(N)]

Comparing two joda DateTime instances

This code (example) :

    Chronology ch1 = GregorianChronology.getInstance();     Chronology ch2 = ISOChronology.getInstance();      DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1);     DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2);      System.out.println(dt);     System.out.println(dt2);      boolean b = dt.equals(dt2);      System.out.println(b); 

Will print :

2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false 

You are probably comparing two DateTimes with same date but different Chronology.

SQL Server: Best way to concatenate multiple columns?

Try using below:

SELECT 
    (RTRIM(LTRIM(col_1))) + (RTRIM(LTRIM(col_2))) AS Col_newname,
    col_1,
    col_2 
FROM 
    s_cols 
WHERE
    col_any_condition = ''
;

How to apply a CSS filter to a background image

The following is a simple solution for modern browsers in pure CSS with a 'before' pseudo element, like the solution from Matthew Wilcoxson.

To avoid the need of accessing the pseudo element for changing the image and other attributes in JavaScript, simply use inherit as the value and access them via the parent element (here body).

body::before {
    content: ""; /* Important */
    z-index: -1; /* Important */
    position: inherit;
    left: inherit;
    top: inherit;
    width: inherit;
    height: inherit;
    background-image: inherit;
    background-size: cover;
    filter: blur(8px);
}

body {
  background-image: url("xyz.jpg");
  background-size: 0 0;  /* Image should not be drawn here */
  width: 100%;
  height: 100%;
  position: fixed; /* Or absolute for scrollable backgrounds */
}

What are SP (stack) and LR in ARM?

LR is link register used to hold the return address for a function call.

SP is stack pointer. The stack is generally used to hold "automatic" variables and context/parameters across function calls. Conceptually you can think of the "stack" as a place where you "pile" your data. You keep "stacking" one piece of data over the other and the stack pointer tells you how "high" your "stack" of data is. You can remove data from the "top" of the "stack" and make it shorter.

From the ARM architecture reference:

SP, the Stack Pointer

Register R13 is used as a pointer to the active stack.

In Thumb code, most instructions cannot access SP. The only instructions that can access SP are those designed to use SP as a stack pointer. The use of SP for any purpose other than as a stack pointer is deprecated. Note Using SP for any purpose other than as a stack pointer is likely to break the requirements of operating systems, debuggers, and other software systems, causing them to malfunction.

LR, the Link Register

Register R14 is used to store the return address from a subroutine. At other times, LR can be used for other purposes.

When a BL or BLX instruction performs a subroutine call, LR is set to the subroutine return address. To perform a subroutine return, copy LR back to the program counter. This is typically done in one of two ways, after entering the subroutine with a BL or BLX instruction:

• Return with a BX LR instruction.

• On subroutine entry, store LR to the stack with an instruction of the form: PUSH {,LR} and use a matching instruction to return: POP {,PC} ...

This link gives an example of a trivial subroutine.

Here is an example of how registers are saved on the stack prior to a call and then popped back to restore their content.

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

Take a look at FileSaver.js. It provides a handy saveAs function which takes care of most browser specific quirks.

How to remove word wrap from textarea?

textarea {
  white-space: pre;
  overflow-wrap: normal;
  overflow-x: scroll;
}

white-space: nowrap also works if you don't care about whitespace, but of course you don't want that if you're working with code (or indented paragraphs or any content where there might deliberately be multiple spaces) ... so i prefer pre.

overflow-wrap: normal (was word-wrap in older browsers) is needed in case some parent has changed that setting; it can cause wrapping even if pre is set.

also -- contrary to the currently accepted answer -- textareas do often wrap by default. pre-wrap seems to be the default on my browser.

How to determine whether a given Linux is 32 bit or 64 bit?

That system is 32bit. iX86 in uname means it is a 32-bit architecture. If it was 64 bit, it would return

Linux mars 2.6.9-67.0.15.ELsmp #1 SMP Tue Apr 22 13:50:33 EDT 2008 x86_64 i686 x86_64 x86_64 GNU/Linux

How do I get the last character of a string using an Excel function?

=RIGHT(A1)  

is quite sufficient (where the string is contained in A1).

Similar in nature to LEFT, Excel's RIGHT function extracts a substring from a string starting from the right-most character:

SYNTAX

RIGHT( text, [number_of_characters] )

Parameters or Arguments

text

The string that you wish to extract from.

number_of_characters

Optional. It indicates the number of characters that you wish to extract starting from the right-most character. If this parameter is omitted, only 1 character is returned.

Applies To

Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Since number_of_characters is optional and defaults to 1 it is not required in this case.

However, there have been many issues with trailing spaces and if this is a risk for the last visible character (in general):

=RIGHT(TRIM(A1))  

might be preferred.

Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

Go to Path C:\ProgramData\Oracle\Java\javapath (This path is in my case might be different in your case). Rename the folder ORACLE with other name line ORACLE_OLD. And Restart the STS/IDE . This works for me

How do I find the MySQL my.cnf location

for me it was that i had "ENGINE=MyISAM" kind of tables , once i changed it to "ENGINE=InnoDB" it worked:) in PhpMyAdmin on Azure App Service :)

Sort a Custom Class List<T>

You are correct that your cTag class must implement IComparable<T> interface. Then you can just call Sort() on your list.

To implement IComparable<T> interface, you must implement CompareTo(T other) method. The easiest way to do this is to call CompareTo method of the field you want to compare, which in your case is date.

public class cTag:IComparable<cTag> {
    public int id { get; set; }
    public int regnumber { get; set; }
    public string date { get; set; }
    public int CompareTo(cTag other) {
        return date.CompareTo(other.date);
    }
}

However, this wouldn't sort well, because this would use classic sorting on strings (since you declared date as string). So I think the best think to do would be to redefine the class and to declare date not as string, but as DateTime. The code would stay almost the same:

public class cTag:IComparable<cTag> {
    public int id { get; set; }
    public int regnumber { get; set; }
    public DateTime date { get; set; }
    public int CompareTo(cTag other) {
        return date.CompareTo(other.date);
    }
}

Only thing you'd have to do when creating the instance of the class to convert your string containing the date into DateTime type, but it can be done easily e.g. by DateTime.Parse(String) method.

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

2GB and about 15M records is a very small database - I've run much bigger ones on a pentium III(!) and everything has still run pretty fast.. If yours is slow it is a database/application design problem, not a mysql one.

Ordering issue with date values when creating pivot tables

Try creating a new pivot table, and not just refreshing.

I had a case where I forgot to add in a few dates. After adding them in I updated the pivot table range and hit refresh. They appeared at the end of the pivot table, out of order. I then tried to simply create a new pivot table and the dates where all in order.

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

i had the same problem i had linked jquery twice . The later version was overwriting my plugin.

I just removed the later jquery it started working.

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

This message digital envelope routines: EVP_DecryptFInal_ex: bad decrypt can also occur when you encrypt and decrypt with an incompatible versions of openssl.

The issue I was having was that I was encrypting on Windows which had version 1.1.0 and then decrypting on a generic Linux system which had 1.0.2g.

It is not a very helpful error message!


Working solution:

A possible solution from @AndrewSavinykh that worked for many (see the comments):

Default digest has changed between those versions from md5 to sha256. One can specify the default digest on the command line as -md sha256 or -md md5 respectively

Throughput and bandwidth difference?

In most cases with "bandwidth" and "throughput" it is OVER complicated; like trying to learn calculus in one day. There is NO need for this, in MOST cases when referencing "Bandwidth" and "Throughput".

All you need to know in MOST cases is this:

"MB" means mega "BYTES"; OR 8 bits and 8 bits and 8 bits, etc; is being sent down the line. Mb means mega "bits". OR a single bit and bit and bit, etc; down the line.

Example: IF your carrier says this is a "6 Mb line"; it means that is the maximum Bandwidth. More succinctly it means that you ONLY are going to benefit 750 kilobytes per/sec "throughput". Now why? Because the line is only sending a series of "bits", which uses 8 bits/sec to create a byte. Thus; you must divide bits/sec by 8 to get to bytes/sec. Thus: a 6Mb line can ONLY deliver 750 thousand bytes/sec.

Another example: I just got a fiber optic line from A T & T; and they LOVE to talk about "bits". So they advertise a whopping "100 mega bits per second". Big deal. Because that is only 12.5 "MBytes/per second.

Remember, EACH "character" on your keyboard or printed on the screen, etc, requires 8 bits; for the other end to "distinguish" what character it is, etc.

So even though I have a "Gargantuan" fiber line touted as "100Mb"; it is really only 12.5 MBytes (characters) per second (100 divided by 8).

Worse: MOST interchange the terms "MB" and "Mb". Worse yet; EVEN The technician that installed the Fiber Optic line and router in my home, did not know what the terms meant. So he thought, and his co-workers (according to him) believed the same. IE: That 100Mb line was a 100MB line. This is very sad.

A T & T reps on the phone rarely know the difference either. Even some of their supervisors do not know it either. Even sadder.

To summarize: "Bandwidth" uses "bits". "Throughput" uses "bytes". And...one byte takes up 8 bits. So again: a 100Mb line (bandwidth) can ONLY produce 12.5 MBytes/sec (throughput).

For whatever it's worth.

Iif equivalent in C#

It's the ternary operator ?

string newString = i == 1 ? "i is one" : "i is not one";

How to PUT a json object with an array using curl

Although the original post had other issues (i.e. the missing "-d"), the error message is more generic.

curl: (3) [globbing] nested braces not supported at pos X

This is because curly braces {} and square brackets [] are special globbing characters in curl. To turn this globbing off, use the "-g" option.

As an example, the following Solr facet query will fail without the "-g" to turn off curl globbing: curl -g 'http://localhost:8983/solr/query?json.facet={x:{terms:"myfield"}}'

Vim multiline editing like in sublimetext?

There are several ways to accomplish that in Vim. I don't know which are most similar to Sublime Text's though.


The first one would be via multiline insert mode. Put your cursor to the second "a" in the first line, press Ctrl-V, select all lines, then press I, and put in a doublequote. Pressing <esc> will repeat the operation on every line.


The second one is via macros. Put the cursor on the first character, and start recording a macro with qa. Go the your right with llll, enter insert mode with a, put down a doublequote, exit insert mode, and go back to the beginning of your row with <home> (or equivalent). Press j to move down one row. Stop recording with q. And then replay the macro with @a. Several times.


Does any of the above approaches work for you?

Dynamic creation of table with DOM

In My example call add function from button click event and then get value from form control's and call function generateTable.
In generateTable Function check first Table is Generaed or not. If table is undefined then call generateHeader Funtion and Generate Header and then call addToRow function for adding new row in table.

<input type="button" class="custom-rounded-bttn bttn-save" value="Add" id="btnAdd" onclick="add()">


<div class="row">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
        <div class="dataGridForItem">
        </div>
    </div>
</div>

//Call Function From Button click Event

var counts = 1;
function add(){ 
    var Weightage = $('#Weightage').val();
    var ItemName = $('#ItemName option:selected').text();  
    var ItemNamenum = $('#ItemName').val();
    generateTable(Weightage,ItemName,ItemNamenum);
     $('#Weightage').val('');
     $('#ItemName').val(-1);
     return true;
 } 


function generateTable(Weightage,ItemName,ItemNamenum){
    var tableHtml = '';
    if($("#rDataTable").html() == undefined){
        tableHtml = generateHeader();
    }else{
        tableHtml = $("#rDataTable");
    } 
    var temp = $("<div/>");
    var row = addToRow(Weightage,ItemName,ItemNamenum);
    $(temp).append($(row));
    $("#dataGridForItem").html($(tableHtml).append($(temp).html()));
}


//Generate Header


function generateHeader(){
        var html = "<table id='rDataTable' class='table table-striped'>";
        html+="<tr class=''>";
        html+="<td class='tb-heading ui-state-default'>"+'Sr.No'+"</td>";
        html+="<td class='tb-heading ui-state-default'>"+'Item Name'+"</td>";
        html+="<td class='tb-heading ui-state-default'>"+'Weightage'+"</td>";
        html+="</tr></table>";
        return html; 
}

//Add New Row


function addToRow(Weightage,ItemName,ItemNamenum){
    var html="<tr class='trObj'>";
    html+="<td>"+counts+"</td>";
    html+="<td>"+ItemName+"</td>";
    html+="<td>"+Weightage+"</td>";
    html+="</tr>";
    counts++;
    return html;
}

Date difference in years using C#

I found this at TimeSpan for years, months and days:

DateTime target_dob = THE_DOB;
DateTime true_age = DateTime.MinValue + ((TimeSpan)(DateTime.Now - target_dob )); // Minimum value as 1/1/1
int yr = true_age.Year - 1;

How do I resolve git saying "Commit your changes or stash them before you can merge"?

Before using reset think about using revert so you can always go back.

https://www.pixelstech.net/article/1549115148-git-reset-vs-git-revert

On request

Source: https://www.pixelstech.net/article/1549115148-git-reset-vs-git-revert

git reset vs git revert   sonic0002        2019-02-02 08:26:39 

When maintaining code using version control systems such as git, it is unavoidable that we need to rollback some wrong commits either due to bugs or temp code revert. In this case, rookie developers would be very nervous because they may get lost on what they should do to rollback their changes without affecting others, but to veteran developers, this is their routine work and they can show you different ways of doing that. In this post, we will introduce two major ones used frequently by developers.

  • git reset
  • git revert

What are their differences and corresponding use cases? We will discuss them in detail below. git reset Assuming we have below few commits. enter image description here

Commit A and B are working commits, but commit C and D are bad commits. Now we want to rollback to commit B and drop commit C and D. Currently HEAD is pointing to commit D 5lk4er, we just need to point HEAD to commit B a0fvf8 to achieve what we want.  It's easy to use git reset command.

git reset --hard a0fvf8

After executing above command, the HEAD will point to commit B. enter image description here

But now the remote origin still has HEAD point to commit D, if we directly use git push to push the changes, it will not update the remote repo, we need to add a -f option to force pushing the changes.

git push -f

The drawback of this method is that all the commits after HEAD will be gone once the reset is done. In case one day we found that some of the commits ate good ones and want to keep them, it is too late. Because of this, many companies forbid to use this method to rollback changes.

git revert The use of git revert is to create a new commit which reverts a previous commit. The HEAD will point to the new reverting commit.  For the example of git reset above, what we need to do is just reverting commit D and then reverting commit C. 

git revert 5lk4er
git revert 76sdeb

Now it creates two new commit D' and C',  enter image description here

In above example, we have only two commits to revert, so we can revert one by one. But what if there are lots of commits to revert? We can revert a range indeed.

git revert OLDER_COMMIT^..NEWER_COMMIT

This method would not have the disadvantage of git reset, it would point HEAD to newly created reverting commit and it is ok to directly push the changes to remote without using the -f option. Now let's take a look at a more difficult example. Assuming we have three commits but the bad commit is the second commit.  enter image description here

It's not a good idea to use git reset to rollback the commit B since we need to keep commit C as it is a good commit. Now we can revert commit C and B and then use cherry-pick to commit C again.  enter image description here

From above explanation, we can find out that the biggest difference between git reset and git revert is that git reset will reset the state of the branch to a previous state by dropping all the changes post the desired commit while git revert will reset to a previous state by creating new reverting commits and keep the original commits. It's recommended to use git revert instead of git reset in enterprise environment.  Reference: https://kknews.cc/news/4najez2.html

How can I get the iOS 7 default blue color programmatically?

iOS 7 default blue color is R:0.0 G:122.0 B:255.0

UIColor *ios7BlueColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];

Spring Data JPA find by embedded object property

If you are using BookId as an combined primary key, then remember to change your interface from:

public interface QueuedBookRepo extends JpaRepository<QueuedBook, Long> {

to:

public interface QueuedBookRepo extends JpaRepository<QueuedBook, BookId> {

And change the annotation @Embedded to @EmbeddedId, in your QueuedBook class like this:

public class QueuedBook implements Serializable {

@EmbeddedId
@NotNull
private BookId bookId;

...

Stored procedure with default parameters

I wrote with parameters that are predefined

They are not "predefined" logically, somewhere inside your code. But as arguments of SP they have no default values and are required. To avoid passing those params explicitly you have to define default values in SP definition:

Alter Procedure [Test]
    @StartDate AS varchar(6) = NULL, 
    @EndDate AS varchar(6) = NULL
AS
...

NULLs or empty strings or something more sensible - up to you. It does not matter since you are overwriting values of those arguments in the first lines of SP.

Now you can call it without passing any arguments e.g. exec dbo.TEST

Console app arguments, how arguments are passed to Main method

Command line arguments is one way to pass the arguments in. This msdn sample is worth checking out. The MSDN Page for command line arguments is also worth reading.

From within visual studio you can set the command line arguments by Choosing the properties of your console application then selecting the Debug tab

Change app language programmatically in Android

Just handle in method

@Override public void onConfigurationChanged(android.content.res.Configuration newConfig).

Follow the Link

I think it is useful

How can one pull the (private) data of one's own Android app?

This answer is based on my experience with other answers, and comments in the answers. My hope is I can help someone in a similar situation.

I am doing this on OSX via terminal.

Previously Vinicius Avellar's answer worked great for me. I was only ever most of the time needing the database from the device from a debug application.

Today I had a use case where I needed multiple private files. I ended up with two solutions that worked good for this case.

  1. Use the accepted answer along with Someone Somewhere's OSX specific comments. Create a backup and use the 3rd party solution, sourceforge.net/projects/adbextractor/files/?source=navbar to unpack into a tar. I'll write more about my experience with this solution at the bottom of this answer. Scroll down if this is what you are looking for.

  2. A faster solution which I settled with. I created a script for pulling multiple files similar to Tamas' answer. I am able to do it this way because my app is a debug app and I have access to run-as on my device. If you don't have access to run-as this method won't work for you on OSX.

Here is my script for pulling multiple private files that I'll share with you, the reader, who is also investigating this awesome question ;) :

#!/bin/bash
#
# Strict mode: http://redsymbol.net/articles/unofficial-bash-strict-mode/
set -euo pipefail
IFS=$'\n\t'

# 
# Usage: script -f fileToPull -p packageName
# 

# This script is for pulling private files from an Android device
# using run-as. Note: not all devices have run-as access, and
# application must be a debug version for run-as to work.
# 
# If run-as is deactivated on your device use one of the
# alternative methods here:
# http://stackoverflow.com/questions/15558353/how-can-one-pull-the-private-data-of-ones-own-android-app
# 
# If you have encrypted backup files use:
# sourceforge.net/projects/adbextractor/files/?source=navbar 
# From comments in the accepted answer in the above SO question
# 
# If your files aren't encrypted use the accepted answer 
# ( see comments and other answers for OSX compatibility )
# 
# This script is open to expansions to allow selecting 
# device used. Currently first selected device from
# adb shell will be used.

#Check we have one connected device
adb devices -l | grep -e 'device\b' > /dev/null

if [ $? -gt 0 ]; then
    echo "No device connected to adb."
    exit 1
fi

# Set filename or directory to pull from device
# Set package name we will run as
while getopts f:p: opt; do
    case $opt in
        f)
            fileToPull=$OPTARG
            ;;
        p)
            packageName=$OPTARG
            ;;
    esac
done;

# Block file arg from being blank
if [ -z "$fileToPull" ]; then
    echo "Please specify file or folder to pull with -f argument"
    exit 1
fi

# Block package name arg from being blank
if [ -z "$packageName" ]; then
    echo "Please specify package name to run as when pulling file"
    exit 1
fi

# Check package exists
adb shell pm list packages | grep "$packageName" > /dev/null
if [ $? -gt 0 ]; then
    echo "Package name $packageName does not exist on device"
    exit 1
fi

# Check file exists and has permission with run-as
fileCheck=`adb shell "run-as $packageName ls $fileToPull"`
if [[ $fileCheck =~ "Permission denied" ]] || [[ $fileCheck =~ "No such file or directory" ]]; then
    echo "Error: $fileCheck"
    echo "With file -> $fileToPull"
    exit 1
fi

# Function to pull private file
#
# param 1 = package name
# param 2 = file to pull
# param 3 = output file
function pull_private_file () {

    mkdir -p `dirname $3`

    echo -e "\033[0;35m***" >&2
    echo -e "\033[0;36m Coping file $2 -> $3" >&2
    echo -e "\033[0;35m***\033[0m" >&2

    adb shell "run-as $1 cat $2" > $3
}

# Check if a file is a directory
# 
# param 1 = directory to check
function is_file_dir() {

    adb shell "if [ -d \"$1\" ]; then echo TRUE; fi"
}

# Check if a file is a symbolic link
# 
# param 1 = directory to check
function is_file_symlink() {

    adb shell "if [ -L \"$1\" ]; then echo TRUE; fi"
}

# recursively pull files from device connected to adb
# 
# param 1 = package name
# param 2 = file to pull
# param 3 = output file
function recurse_pull_private_files() {

    is_dir=`is_file_dir "$2"`
    is_symlink=`is_file_symlink "$2"`

    if [ -n "$is_dir" ]; then

        files=`adb shell "run-as $1 ls \"$2\""`

        # Handle the case where directory is a symbolic link
        if [ -n "$is_symlink" ]; then
            correctPath=`adb shell "run-as $1 ls -l \"$2\"" | sed 's/.*-> //' | tr -d '\r'`
            files=`adb shell "run-as $1 ls \"$correctPath\""`
        fi

        for i in $files; do

            # Android adds nasty carriage return that screws with bash vars
            # This removes it. Otherwise weird behavior happens
            fileName=`echo "$i" | tr -d '\r'` 

            nextFile="$2/$fileName"
            nextOutput="$3/$fileName"
            recurse_pull_private_files "$1" "$nextFile" "$nextOutput"
        done
    else

        pull_private_file "$1" "$2" "$3"
    fi
}

recurse_pull_private_files "$packageName" "$fileToPull" "`basename "$fileToPull"`"

Gist: https://gist.github.com/davethomas11/6c88f92c6221ffe6bc26de7335107dd4


Back to method 1, decrypting a backup using Android Backup Extractor

Here are the steps I took on my Mac, and issues I came across:

First I queued up a backup ( and set a password to encrypt my backup, my device required it ):

adb backup -f myAndroidBackup.ab  com.corp.appName

Second I downloaded just abe.jar from here: https://sourceforge.net/projects/adbextractor/files/abe.jar/download

Next I ran:

java -jar ./abe.jar unpack myAndroidBackup.ab myAndroidBackup.tar

At this point I got an error message. Because my archive is encrypted, java gave me an error that I needed to install some security policy libraries.

  • So I went to http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html and downloaded the security policy jars I needed. Now in my case the install instructions told me the wrong location to put the jar files. It says that the proper location is <java-home>/lib/security. I put them there first and still got the error message. So I investigated and on my Mac with Java 1.8 the correct place to put them was: <java-home>/jre/lib/security. I made sure to backup the original policy jars, and put them there. Vola I was able to enter a password with abe.jar and decrypt to a tar file.

Lastly I just ran ( after running previous command again )

tar xvf myAndroidBackup.tar

Now it is important to note that if you can just run-as and cat, it is much much faster. One, you only get the files you want and not the entire application. Two, the more files ( + encryption for me ) makes it slower to transfer. So knowing to do this way is important if you don't have run-as on OSX, but the script should be first goto for a debug application.

Mind you I just wrote it today and tested it a few times, so please notify me of any bugs!

Git Push Error: insufficient permission for adding an object to repository database

For Ubuntu (or any Linux)

From project root,

cd .git/objects
ls -al
sudo chown -R yourname:yourgroup *

You can tell what yourname and yourgroup should be by looking at the permissions on the majority of the output from that ls -al command

Note: remember the star at the end of the sudo line

How to make java delay for a few seconds?

waiting for some(like 10) seconds your compiler to use this static class method
TimeUnit.SECONDS.sleep(10);
it's including in java.util.concurrent.TimeUnit libery

SELECTING with multiple WHERE conditions on same column

Consider using INTERSECT like this:

SELECT contactid WHERE flag = 'Volunteer' 
INTERSECT
SELECT contactid WHERE flag = 'Uploaded'

I think it it the most logistic solution.

installation app blocked by play protect

I solved this problem by changing my application package name according to signature certificate details. At first I created application with com.foo.xyz but my certificate organization was 'bar'. So I change my package name to com.bar.xyz and now there is no google play protect warning!

Print a div using javascript in angularJS single page application

This is what worked for me in Chrome and Firefox! This will open the little print window and close it automatically once you've clicked print.

var printContents = document.getElementById('div-id-selector').innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no,top=50');
            popupWin.window.focus();
            popupWin.document.open();
            popupWin.document.write('<!DOCTYPE html><html><head><title>TITLE OF THE PRINT OUT</title>' 
                                    +'<link rel="stylesheet" type="text/css" href="app/directory/file.css" />' 
                                    +'</head><body onload="window.print(); window.close();"><div>' 
                                    + printContents + '</div></html>');
            popupWin.document.close();