Programs & Examples On #Fingerprint

Biometric modality that matches images of finger tips.

ERROR in ./node_modules/css-loader?

Run this command:

npm install --save node-sass

This does the same as above. Similarly to the answer above.

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

How to define and use function inside Jenkins Pipeline config?

Solved! The call build job: project, parameters: params fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List when params = [:]. Replacing it with params = null solved the issue. Here the working code below.

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1')
    }
}

Can a website detect when you are using Selenium with chromedriver?

Write an html page with the following code. You will see that in the DOM selenium applies a webdriver attribute in the outerHTML

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <script type="text/javascript">_x000D_
  <!--_x000D_
    function showWindow(){_x000D_
      javascript:(alert(document.documentElement.outerHTML));_x000D_
    }_x000D_
  //-->_x000D_
  </script>_x000D_
</head>_x000D_
<body>_x000D_
  <form>_x000D_
    <input type="button" value="Show outerHTML" onclick="showWindow()">_x000D_
  </form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to ignore ansible SSH authenticity checking?

Changing host_key_checking to false for all hosts is a very bad idea.

The only time you want to ignore it, is on "first contact", which these two tasks will accomplish:

    - name: Check SSH known_hosts for {{ inventory_hostname }}
      local_action: shell ssh-keygen -F {{ inventory_hostname }}
      register: checkForKnownHostsEntry
      failed_when: false
      changed_when: false
      ignore_errors: yes
    - name: Add {{ inventory_hostname }} to SSH known hosts automatically
      when: checkForKnownHostsEntry.rc == 1
      changed_when: checkForKnownHostsEntry.rc == 1
      set_fact:
        ansible_ssh_common_args: '-o StrictHostKeyChecking=no'

So we only turn off host key checking if we don't have the host key in our known_hosts file.

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

I found a very easy process to find you MD5, SHA-1 fingerprint using Android Studio.

  1. Run your project
  2. Go to Gradle Menu (Menu: View -> Tool Windows -> Gradle)
  3. Go to 'signingReport' in Gradle window. (Your project -> Tasks -> android -> signingReport)
  4. Run it. (Using double-click or Ctrl + Shift + F10)
  5. In Run window you will find all info.

It's work only for debug mode. In realease mode I can not see sha-1. Here result of gradlew signingReport

Variant: release
Config: none
----------
Variant: releaseUnitTest
Config: none
----------
Variant: debug
Config: debug
Store: path\Android\avd\.android\debug.keystore
Alias: AndroidDebugKey
MD5: xx:xx:xx:62:86:B7:9C:BC:FB:AD:C8:C6:64:69:xx:xx
SHA1: xx:xx:xx:xx:0F:B0:82:86:1D:14:0D:AF:67:99:58:1A:01:xx:xx:xx
Valid until: Friday, July 19, 2047
----------

So I must use keytool to get sha-1. Here official Firebase doc:

Get_sha-1_for_release

Chrome DevTools Devices does not detect device when plugged in

workaround if you don't have ADT (Android Development Toolkit) installed:

Managed to detect android based Samsung Galaxy phone after downloading andorid SDK platform-tools.zip and running the following command: "adb devices". It started some deamon, found attached device, and I was also able to see it in chrome canary inspect tab.

previously I also installed "Universal ADB driver" but not sure if this was required

ssh remote host identification has changed

SOLUTION:

1- delete from "$HOME/.ssh/known_hosts" the line referring to the host towards which is impossible to connect.

2- execute this command: ssh-keygen -R "IP_ADDRESSorHOSTNAME" (substitute "IP_ADDRESSorHOSTNAME" with your destination ip or destination hostname)

3- Retry ssh connection (if it fails please check permission on .ssh directory, it has to be 700)

Unique device identification

It looks like the phoneGap plugin will allow you to get the device's uid.

http://docs.phonegap.com/en/3.0.0/cordova_device_device.md.html#device.uuid

Update: This is dependent on running native code. We used this solution writing javascript that was being compiled to native code for a native phone application we were creating.

Rails 4: assets not loading in production

I just had the same problem and found this setting in config/environments/production.rb:

# Rails 4:
config.serve_static_assets = false

# Or for Rails 5:
config.public_file_server.enabled = false

Changing it to true got it working. It seems by default Rails expects you to have configured your front-end webserver to handle requests for files out of the public folder instead of proxying them to the Rails app. Perhaps you've done this for your javascript files but not your CSS stylesheets?

(See Rails 5 documentation). As noted in comments, with Rails 5 you may just set the RAILS_SERVE_STATIC_FILES environment variable, since the default setting is config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?.

Could not open a connection to your authentication agent

Use parameter -A when you connect to server, example:

ssh -A root@myhost

from man page :

-A Enables forwarding of the authentication agent connection.  
   This can also be specified on a per-host basis in a configuration file.

   Agent forwarding should be enabled with caution.  Users with the ability to bypass file permissions on the remote host (for the agent's
   UNIX-domain socket) can access the local agent through the forwarded 
   connection.  An attacker cannot obtain key material from the agent,
   however they can perform operations on the keys that enable them to
   authenticate using the identities loaded into the agent.

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

For me, on Android Studio 4.1, what did the trick was good ole File > Invalidate Cache & Restart

No more Fatal Signals after that. I'm sure it had something to do with the profiler, but can't be certain. I just know restarting AS stopped the crashes on my emulator. enter image description here

Failed to add the host to the list of know hosts

This is the solution i needed.

sudo chmod 700 ~/.ssh/
sudo chmod 600 ~/.ssh/*
sudo chown -R ${USER} ~/.ssh/
sudo chgrp -R ${USER} ~/.ssh/

Selenium WebDriver How to Resolve Stale Element Reference Exception?

I have solved this problem with the following code.

public WebElement waitForElement(final By findBy, final int waitTime) {
    Wait<AppiumDriver> wait = new FluentWait<>((AppiumDriver) driver)
            .withTimeout(waitTime, TimeUnit.SECONDS)
            .pollingEvery(POLL_TIME, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class,StaleElementReferenceException.class);

    WebElement webElement = wait.until(new Function<AppiumDriver, WebElement>() {
        @Override
        public WebElement apply(AppiumDriver driver) {
            System.out.println("Trying to find element " + findBy.toString());                
            WebElement element = driver.findElement(findBy);
            return element;
        }
    });
    return webElement;
}

SHA-1 fingerprint of keystore certificate

![Go to far left[![][1][1]

Please refer to the following images and get the SHA-1 key Refresh

View in console panel at bottom

Android ADB device offline, can't issue commands

For anyone wondering about 4.2.2, there is a security question that appears on the phone requesting RSA verification with the PC. Be sure your tools are updated AND you allow the PC access by verifying the security question on the devices in question. This fixed it for me.

And as always, verify you have debugging enabled in the developer options ;)

write a shell script to ssh to a remote machine and execute commands

There are multiple remote linux machines, and I need to write a shell script which will execute the same set of commands in each machine. (Including some sudo operations). How can this be done using shell scripting?

You can do this with ssh, for example:

#!/bin/bash
USERNAME=someUser
HOSTS="host1 host2 host3"
SCRIPT="pwd; ls"
for HOSTNAME in ${HOSTS} ; do
    ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}"
done

When ssh'ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication.

You can add the StrictHostKeyChecking=no option to ssh:

ssh -o StrictHostKeyChecking=no -l username hostname "pwd; ls"

This will disable the host key check and automatically add the host key to the list of known hosts. If you do not want to have the host added to the known hosts file, add the option -o UserKnownHostsFile=/dev/null.

Note that this disables certain security checks, for example protection against man-in-the-middle attack. It should therefore not be applied in a security sensitive environment.

How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?

Using portecle :

  • File > Open Keystore file
  • Enter Keystore password
  • Right click on alias name > Certificate details > SHA-1 Fingerprint

How to do a https request with bad certificate?

All of these answers are wrong! Do not use InsecureSkipVerify to deal with a CN that doesn't match the hostname. The Go developers unwisely were adamant about not disabling hostname checks (which has legitimate uses - tunnels, nats, shared cluster certs, etc), while also having something that looks similar but actually completely ignores the certificate check. You need to know that the certificate is valid and signed by a cert that you trust. But in common scenarios, you know that the CN won't match the hostname you connected with. For those, set ServerName on tls.Config. If tls.Config.ServerName == remoteServerCN, then the certificate check will succeed. This is what you want. InsecureSkipVerify means that there is NO authentication; and it's ripe for a Man-In-The-Middle; defeating the purpose of using TLS.

There is one legitimate use for InsecureSkipVerify: use it to connect to a host and grab its certificate, then immediately disconnect. If you setup your code to use InsecureSkipVerify, it's generally because you didn't set ServerName properly (it will need to come from an env var or something - don't belly-ache about this requirement... do it correctly).

In particular, if you use client certs and rely on them for authentication, you basically have a fake login that doesn't actually login any more. Refuse code that does InsecureSkipVerify, or you will learn what is wrong with it the hard way!

Calculate RSA key fingerprint

The fastest way if your keys are in an SSH agent:

$ ssh-add -L | ssh-keygen -E md5 -lf /dev/stdin

Each key in the agent will be printed as:

4096 MD5:8f:c9:dc:40:ec:9e:dc:65:74:f7:20:c1:29:d1:e8:5a /Users/cmcginty/.ssh/id_rsa (RSA)

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

all you can do is to navigate to your jre destination in your computer via command line and then once you reach bin, you type the keytool command and it would work.

C:\Program Files (x86)\Java\jre7\bin>
C:\Program Files (x86)\Java\jre7\bin>keytool -list -v -keystore"%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android



Alias name: androiddebugkey
Creation date: 23 Feb, 2014
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Android Debug, O=Android, C=US
Issuer: CN=Android Debug, O=Android, C=US
Serial number: 479d4fe7
Valid from: Sun Feb 23 06:19:02 IST 2014 until: Tue Feb 16 06:19:02 IST 2044
Certificate fingerprints:
MD5:  DB:6A:8E:48:22:5B:37:73:B1:91:EF:43:3F:26:F0:EC
SHA1: B4:6B:2E:5F:5A:30:C5:E4:E7:12:BB:F0:74:FC:2B:43:64:3A:FC:15
SHA256: CB:59:F3:20:7D:5B:87:99:6C:0D:32:79:79:CF:4E:8C:16:C2:37:81:7B:
B0:AF:D2:EC:3C:11:21:53:58:62:F6
Signature algorithm name: SHA256withRSA
Version: 3
Extensions:
#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: FA 96 17 9E 94 73 C3 42   F0 4B 55 5B C7 5B EE BB  .....s.B.KU[.[..
0010: C3 E5 D3 61                                        ...a
]
]

git - Server host key not cached

Changing from PuTTY to OpenSSH fixed this issue for me, without needing to unset GIT_SSH, etc.

The apk must be signed with the same certificates as the previous version

My [silly] mistake was that i used app-debug.apk file instead of app-release.apk file. You need to to choose "release" in "Build Variants" frame when you generate signed APK. The app-release.apk file should be located under "app\release" folder in your project root.

Simple and fast method to compare images for similarity

If for matching identical images - code for L2 distance

// Compare two images by getting the L2 error (square-root of sum of squared error).
double getSimilarity( const Mat A, const Mat B ) {
if ( A.rows > 0 && A.rows == B.rows && A.cols > 0 && A.cols == B.cols ) {
    // Calculate the L2 relative error between images.
    double errorL2 = norm( A, B, CV_L2 );
    // Convert to a reasonable scale, since L2 error is summed across all pixels of the image.
    double similarity = errorL2 / (double)( A.rows * A.cols );
    return similarity;
}
else {
    //Images have a different size
    return 100000000.0;  // Return a bad value
}

Fast. But not robust to changes in lighting/viewpoint etc. Source

How to establish ssh key pair when "Host key verification failed"

This issue arises when the host key is expired or changed. you can remove the keys that host is using and try to ssh again, so that you are adding new key that is known to both client and server.

You can check the keys associated with your hosts with cat /.ssh/known_hosts . Now, You can remove the hosts keys manually or using the ssh-keygen option. You can do either of the following option.

  1. Manual removal of keys

    vim /.ssh/known_hosts

delete the key that is associated with your host.

  1. Remove key using ssh-keygen

    ssh-keygen -R your_host_or_host_ip

This will remove your key associated with the host.

Now, you can ssh to your host as usual and you will be asked if you want to continue to this host. Once your enter yes, this host will be added to your/.ssh/known_hosts with updated key. By now, you should be your host.

ssh: The authenticity of host 'hostname' can't be established

Do this -> chmod +w ~/.ssh/known_hosts. This adds write permission to the file at ~/.ssh/known_hosts. After that the remote host will be added to the known_hosts file when you connect to it the next time.

I can’t find the Android keytool

The 4-Step Answer above worked for me, but it returns the SH1-key... but Google asks for the MD5-key to generate your API key.

One needs simply to add a '-v' in the command in step 3. -like so:

Updated 4-Step Answer

Ok I did this in Windows 7 32-bit system.

step 1: go to - C:\Program Files\Java\jdk1.7.0\bin - and run jarsigner.exe first ( double click)

step2: locate debug.keystore (in Eclipse: Windows/Preferences/Android/build..), in my case it was - C:\Users\MyPcName.android

step3: open command prompt and go to dir - C:\Program Files\Java\jdk1.7.0\bin and give the following command: keytool -v -list -keystore "C:\Users\MyPcName.android\debug.keystore"

step4: it will ask for Keystore password now. The default is 'android'

com.jcraft.jsch.JSchException: UnknownHostKey

I lost a lot of time on this stupid issue, and i think the message is quite right "there is not the host in the file i'm accessing" but you can have more than a know_host file around on your system (as example i'm using mobaXterm and it keep it's own inside the installation directory mounting the home from that root).

If you are experiencing : it's working from command line but not form the application try to access to your remote server with ssh and check with verbose -v option which file is currently used an example following:

 ssh -v [email protected]
 OpenSSH_6.2p2, OpenSSL 1.0.1g 7 Apr 2014
 debug1: Reading configuration data /etc/ssh_config
 debug1: Connecting to gitlab.com [104.210.2.228] port 22.
 debug1: Connection established.
 debug1: identity file /home/mobaxterm/.ssh/id_rsa type 1
 debug1: identity file /home/mobaxterm/.ssh/id_rsa-cert type -1
 debug1: identity file /home/mobaxterm/.ssh/id_dsa type -1
 debug1: identity file /home/mobaxterm/.ssh/id_dsa-cert type -1
 debug1: identity file /home/mobaxterm/.ssh/id_ecdsa type -1
 debug1: identity file /home/mobaxterm/.ssh/id_ecdsa-cert type -1
 debug1: Enabling compatibility mode for protocol 2.0
 debug1: Local version string SSH-2.0-OpenSSH_6.2
 debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2      Ubuntu-4ubuntu2.1
 debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.1 pat OpenSSH*
 debug1: SSH2_MSG_KEXINIT sent
 debug1: SSH2_MSG_KEXINIT received
 debug1: kex: server->client aes128-ctr [email protected] [email protected]
 debug1: kex: client->server aes128-ctr [email protected] [email protected]
 debug1: sending SSH2_MSG_KEX_ECDH_INIT
 debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
 debug1: Server host key: RSA b6:03:0e:39:97:9e:d0:e7:24:ce:a3:77:3e:01:42:09
 debug1: Host 'gitlab.com' is known and matches the RSA host key.
 debug1: Found key in /home/mobaxterm/.ssh/known_hosts:19
 debug1: ssh_rsa_verify: signature correct

as you can see the key was found in :

debug1: Found key in /home/mobaxterm/.ssh/known_hosts:19

and not in my windows home under C:\Users\my_local_user\.ssh , i simply merged them and aligned for solve the issue.

Hope this help someone in future

Difference between an API and SDK

API is like the building blocks of some puzzling game that a child plays with to join blocks in different shapes and build something they can think of.

SDK, on the other hand, is a proper workshop where all of the development tools are available, rather than pre-shaped building blocks. In a workshop you have the actual tools and you are not limited to blocks, and can therefore make your own blocks, or can create something without any blocks to begin with.

coding without an SDK or API is like making everything from scratch without a workshop - you have to even make your own tools

How do you uninstall all dependencies listed in package.json (NPM)?

Tip for Windows users: Run this PowerShell command from within node_modules parent directory:

ls .\node_modules | % {npm uninstall $_}

Converting List<String> to String[] in Java

hope this can help someone out there:

List list = ..;

String [] stringArray = list.toArray(new String[list.size()]);

great answer from here: https://stackoverflow.com/a/4042464/1547266

How to convert dataframe into time series?

See this question: Converting data.frame to xts order.by requires an appropriate time-based object, which suggests looking at argument to order.by,

Currently acceptable classes include: ‘Date’, ‘POSIXct’, ‘timeDate’, as well as ‘yearmon’ and ‘yearqtr’ where the index values remain unique.

And further suggests an explicit conversion using order.by = as.POSIXct,

df$Date <- as.POSIXct(strptime(df$Date,format),tz="UTC")
xts(df[, -1], order.by=as.POSIXct(df$Date))

Where your format is assigned elswhere,

format <- "%m/%d/%Y" #see strptime for details

How to control the width and height of the default Alert Dialog in Android?

Before trying to adjust the size post-layout, first check what style your dialog is using. Make sure that nothing in the style tree sets

<item name="windowMinWidthMajor">...</item>
<item name="windowMinWidthMinor">...</item>

If that's happening, it's just as simple as supplying your own style to the [builder constructor that takes in a themeResId](http://developer.android.com/reference/android/app/AlertDialog.Builder.html#AlertDialog.Builder(android.content.Context, int)) available API 11+

<style name="WrapEverythingDialog" parent=[whatever you were previously using]>
    <item name="windowMinWidthMajor">0dp</item>
    <item name="windowMinWidthMinor">0dp</item>
</style>

How to define two fields "unique" as couple

Django 2.2+

Using the constraints features UniqueConstraint is preferred over unique_together.

From the Django documentation for unique_together:

Use UniqueConstraint with the constraints option instead.
UniqueConstraint provides more functionality than unique_together.
unique_together may be deprecated in the future.

For example:

class Volume(models.Model):
    id = models.AutoField(primary_key=True)
    journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name="Journal")
    volume_number = models.CharField('Volume Number', max_length=100)
    comments = models.TextField('Comments', max_length=4000, blank=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['journal_id', 'volume_number'], name='name of constraint')
        ]

validation of input text field in html using javascript

<form name="myForm" id="myForm" method="post" onsubmit="return validateForm();">
    First Name: <input type="text" id="name" /> <br />
    <span id="nameErrMsg" class="error"></span> <br />
    <!-- ... all your other stuff ... -->
</form>
  <p>
    1.word should be atleast 5 letter<br>
    2.No space should be encountered<br>
    3.No numbers and special characters allowed<br>
    4.letters can be repeated upto 3(eg: aa is allowed aaa is not allowed)
  </p>
  <button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>


validateForm = function () {
    return checkName();
}

function checkName() {
    var x = document.myForm;
    var input = x.name.value;
    var errMsgHolder = document.getElementById('nameErrMsg');
    if (input.length < 5) {
        errMsgHolder.innerHTML =
            'Please enter a name with at least 5 letters';
        return false;
    } else if (!(/^\S{3,}$/.test(input))) {
        errMsgHolder.innerHTML =
            'Name cannot contain whitespace';
        return false;
    }else if(!(/^[a-zA-Z]+$/.test(input)))
    {
        errMsgHolder.innerHTML=
                'Only alphabets allowed'
    }
    else if(!(/^(?:(\w)(?!\1\1))+$/.test(input)))
    {
        errMsgHolder.innerHTML=
                'per 3 alphabets allowed'
    }
    else {
        errMsgHolder.innerHTML = '';
        return undefined;
    }       

}

.error {
color: #E00000;
 }

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document'

Although this is valid in HTML, you can't use an ID starting with an integer in CSS selectors.

As pointed out, you can use getElementById instead, but you can also still achieve the same with a querySelector:

document.querySelector("[id='22']")

How to create a temporary directory/folder in Java?

Do not use deleteOnExit() even if you explicitly delete it later.

Google 'deleteonexit is evil' for more info, but the gist of the problem is:

  1. deleteOnExit() only deletes for normal JVM shutdowns, not crashes or killing the JVM process.

  2. deleteOnExit() only deletes on JVM shutdown - not good for long running server processes because:

  3. The most evil of all - deleteOnExit() consumes memory for each temp file entry. If your process is running for months, or creates a lot of temp files in a short time, you consume memory and never release it until the JVM shuts down.

How do I show a "Loading . . . please wait" message in Winforms for a long loading form?

or if you don't want anything fancy like animation etc. you can create a label and dock it to form then change it's z-index from document outline window to 0 and give it a background color so other controls wont be visible than run Application.DoEvents() once in form load event and do all your coding in form shown event and at the and of shown event set your label visible property to false then run Application.DoEvents() again.

How to add and get Header values in WebApi

You need to get the HttpRequestMessage from the current OperationContext. Using OperationContext you can do it like so

OperationContext context = OperationContext.Current;
MessageProperties messageProperties = context.IncomingMessageProperties;

HttpRequestMessageProperty requestProperty = messageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;

string customHeaderValue = requestProperty.Headers["Custom"];

How to truncate milliseconds off of a .NET DateTime

To round down to the second:

dateTime.AddTicks(-dateTime.Ticks % TimeSpan.TicksPerSecond)

Replace with TicksPerMinute to round down to the minute.


If your code is performance sensitive, be cautious about

new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second)

My app was spending 12% of CPU time in System.DateTime.GetDatePart.

How to use a wildcard in the classpath to add multiple jars?

This works on Windows:

java -cp "lib/*" %MAINCLASS%

where %MAINCLASS% of course is the class containing your main method.

Alternatively:

java -cp "lib/*" -jar %MAINJAR%

where %MAINJAR% is the jar file to launch via its internal manifest.

animating addClass/removeClass with jQuery

You could use jquery ui's switchClass, Heres an example:

$( "selector" ).switchClass( "oldClass", "newClass", 1000, "easeInOutQuad" );

Or see this jsfiddle.

How to execute a .sql script from bash

You simply need to start mysql and feed it with the content of db.sql:

mysql -u user -p < db.sql

Best way to track onchange as-you-type in input type="text"?

Method 1: Add an event listener for input:

element.addEventListener("input", myFunction);

 

Method 2: Define the oninput property with JavaScript:

element.oninput = function()
{
    myFunction();
};

 

Method 3: Define the oninput property with HTML:

<input type="text" oninput="myFunction();">

How to parse JSON Array (Not Json Object) in Android

In this example there are several objects inside one json array. That is,

This is the json array: [{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]

This is one object: {"name":"name1","url":"url1"}

Assuming that you have got the result to a String variable called jSonResultString:

JSONArray arr = new JSONArray(jSonResultString);

  //loop through each object
  for (int i=0; i<arr.length(); i++){

  JSONObject jsonProductObject = arr.getJSONObject(i);
  String name = jsonProductObject.getString("name");
  String url = jsonProductObject.getString("url");


}

Receiving "Attempted import error:" in react app

This is another option:

export default function Counter() {

}

How to SUM and SUBTRACT using SQL?

An example for subtraction is given below:

Select value1 - (select value2 from AnyTable1) from AnyTable2

value1 & value2 can be count,sum,average output etc. But the values should be comapatible

CSS vertical alignment text inside li

Give this solution a try

Works best in most of the cases

you may have to use div instead of li for that

_x000D_
_x000D_
.DivParent {_x000D_
    height: 100px;_x000D_
    border: 1px solid lime;_x000D_
    white-space: nowrap;_x000D_
}_x000D_
.verticallyAlignedDiv {_x000D_
    display: inline-block;_x000D_
    vertical-align: middle;_x000D_
    white-space: normal;_x000D_
}_x000D_
.DivHelper {_x000D_
    display: inline-block;_x000D_
    vertical-align: middle;_x000D_
    height:100%;_x000D_
}
_x000D_
<div class="DivParent">_x000D_
    <div class="verticallyAlignedDiv">_x000D_
        <p>Isnt it good!</p>_x000D_
     _x000D_
    </div><div class="DivHelper"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Iterator Loop vs index loop

Iterators make your code more generic.
Every standard library container provides an iterator hence if you change your container class in future the loop wont be affected.

How to specify Memory & CPU limit in docker compose version 3

Docker Compose does not support the deploy key. It's only respected when you use your version 3 YAML file in a Docker Stack.

This message is printed when you add the deploy key to you docker-compose.yml file and then run docker-compose up -d

WARNING: Some services (database) use the 'deploy' key, which will be ignored. Compose does not support 'deploy' configuration - use docker stack deploy to deploy to a swarm.

The documentation (https://docs.docker.com/compose/compose-file/#deploy) says:

Specify configuration related to the deployment and running of services. This only takes effect when deploying to a swarm with docker stack deploy, and is ignored by docker-compose up and docker-compose run.

What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?

On my system (OSX 10.6) that package is at

/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/pkg_resources.py

I hope that helps you figure out if it's missing or just not on your path.

Disable browser cache for entire ASP.NET website

I know this answer is not 100% related to the question, but it might help someone.

If you want to disable the browser cache for the entire ASP.NET MVC Website, but you only want to do this TEMPORARILY, then it is better to disable the cache in your browser.

Here's a screenshot in Chrome

HTML/CSS: how to put text both right and left aligned in a paragraph

Least amount of markup possible (you only need one span):

<p>This text is left. <span>This text is right.</span></p>

How you want to achieve the left/right styles is up to you, but I would recommend an external style on an ID or a class.

The full HTML:

<p class="split-para">This text is left. <span>This text is right.</span></p>

And the CSS:

.split-para      { display:block;margin:10px;}
.split-para span { display:block;float:right;width:50%;margin-left:10px;}

addID in jQuery?

ID is an attribute, you can set it with the attr function:

$(element).attr('id', 'newID');

I'm not sure what you mean about adding IDs since an element can only have one identifier and this identifier must be unique.

Cannot make a static reference to the non-static method fxn(int) from the type Two

  1. A static method can NOT access a Non-static method or variable.

  2. public static void main(String[] args) is a static method, so can NOT access the Non-static public static int fxn(int y) method.

  3. Try it this way...

    static int fxn(int y)

    public class Two {
    
    
        public static void main(String[] args) {
            int x = 0;
    
            System.out.println("x = " + x);
            x = fxn(x);
            System.out.println("x = " + x);
        }
    
        static int fxn(int y) {
            y = 5;
            return y;
        }
    

    }

Restricting JTextField input to Integers

When you type integer numbers to JtextField1 after key release it will go to inside try , for any other character it will throw NumberFormatException. If you set empty string to jTextField1 inside the catch so the user cannot type any other keys except positive numbers because JTextField1 will be cleared for each bad attempt.

 //Fields 
int x;
JTextField jTextField1;

 //Gui Code Here

private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {                                        
    try {
        x = Integer.parseInt(jTextField1.getText());
    } catch (NumberFormatException nfe) {
        jTextField1.setText("");
    }
}   

An exception of type 'System.NullReferenceException' occurred in myproject.DLL but was not handled in user code

It means somewhere in your chain of calls, you tried to access a Property or call a method on an object that was null.

Given your statement:

img1.ImageUrl = ConfigurationManager
                    .AppSettings
                    .Get("Url")
                    .Replace("###", randomString) 
                + Server.UrlEncode(
                      ((System.Web.UI.MobileControls.Form)Page
                      .FindControl("mobileForm"))
                      .Title);

I'm guessing either the call to AppSettings.Get("Url") is returning null because the value isn't found or the call to Page.FindControl("mobileForm") is returning null because the control isn't found.

You could easily break this out into multiple statements to solve the problem:

var configUrl = ConfigurationManager.AppSettings.Get("Url");
var mobileFormControl = Page.FindControl("mobileForm")
                            as System.Web.UI.MobileControls.Form;

if(configUrl != null && mobileFormControl != null)
{
    img1.ImageUrl = configUrl.Replace("###", randomString) + mobileControl.Title;
}

sql server #region

Another option is

if your purpose is analyse your query, Notepad+ has useful automatic wrapper for Sql.

bootstrap button shows blue outline when clicked

Override the exact bootstrap statements:

.btn-primary.focus, .btn-primary:focus, .btn-primary:not(:disabled):not(.disabled).active:focus,.btn-primary:not(:disabled):not(.disabled):active:focus,.show>.btn-primary.dropdown-toggle:focus{
 box-shadow: none;
}

How do I style (css) radio buttons and labels?

For any CSS3-enabled browser you can use an adjacent sibling selector for styling your labels

input:checked + label {
    color: white;
}  

MDN's browser compatibility table says essentially all of the current, popular browsers (Chrome, IE, Firefox, Safari), on both desktop and mobile, are compatible.

C++ template typedef

C++11 added alias declarations, which are generalization of typedef, allowing templates:

template <size_t N>
using Vector = Matrix<N, 1>;

The type Vector<3> is equivalent to Matrix<3, 1>.


In C++03, the closest approximation was:

template <size_t N>
struct Vector
{
    typedef Matrix<N, 1> type;
};

Here, the type Vector<3>::type is equivalent to Matrix<3, 1>.

Combining INSERT INTO and WITH/CTE

You need to put the CTE first and then combine the INSERT INTO with your select statement. Also, the "AS" keyword following the CTE's name is not optional:

WITH tab AS (
    bla bla
)
INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos (
BatchID,
AccountNo,
APartyNo,
SourceRowID
)  
SELECT * FROM tab

Please note that the code assumes that the CTE will return exactly four fields and that those fields are matching in order and type with those specified in the INSERT statement. If that is not the case, just replace the "SELECT *" with a specific select of the fields that you require.

As for your question on using a function, I would say "it depends". If you are putting the data in a table just because of performance reasons, and the speed is acceptable when using it through a function, then I'd consider function to be an option. On the other hand, if you need to use the result of the CTE in several different queries, and speed is already an issue, I'd go for a table (either regular, or temp).

WITH common_table_expression (Transact-SQL)

Removing all script tags from html with JS Regular Expression

Whenever you have to resort to Regex based script tag cleanup. At least add a white-space to the closing tag in the form of

</script\s*>

Otherwise things like

<script>alert(666)</script   >

would remain since trailing spaces after tagnames are valid.

Enabling error display in PHP via htaccess only

php_flag display_errors on

To turn the actual display of errors on.

To set the types of errors you are displaying, you will need to use:

php_value error_reporting <integer>

Combined with the integer values from this page: http://php.net/manual/en/errorfunc.constants.php

Note if you use -1 for your integer, it will show all errors, and be future proof when they add in new types of errors.

How can I align all elements to the left in JPanel?

The easiest way I've found to place objects on the left is using FlowLayout.

JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));

adding a component normally to this panel will place it on the left

What's the equivalent of Java's Thread.sleep() in JavaScript?

For Best solution, Use async/await statement for ecma script 2017

await can use only inside of async function

function sleep(time) {
    return new Promise((resolve) => {
        setTimeout(resolve, time || 1000);
    });
}

await sleep(10000); //this method wait for 10 sec.

Note : async / await not actualy stoped thread like Thread.sleep but simulate it

plain count up timer in javascript

@Cybernate, I was looking for the same script today thanks for your input. However I changed it just a bit for jQuery...

function clock(){
    $('body').prepend('<div id="clock"><label id="minutes">00</label>:<label id="seconds">00</label></div>');
         var totalSeconds = 0;
        setInterval(setTime, 1000);
        function setTime()
        {
            ++totalSeconds;
            $('#clock > #seconds').html(pad(totalSeconds%60));
            $('#clock > #minutes').html(pad(parseInt(totalSeconds/60)));
        }
        function pad(val)
        {
            var valString = val + "";
            if(valString.length < 2)
            {
                return "0" + valString;
            }
            else
            {
                return valString;
            }
        }
}
$(document).ready(function(){
    clock();
    });

the css part:

<style>
#clock {
    padding: 10px;
    position:absolute;
    top: 0px;
    right: 0px;
    color: black;
}
</style>

Convert Float to Int in Swift

You can convert Float to Int in Swift like this:

var myIntValue:Int = Int(myFloatValue)
println "My value is \(myIntValue)"

You can also achieve this result with @paulm's comment:

var myIntValue = Int(myFloatValue)

How to Change color of Button in Android when Clicked?

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- default -->
    <item
        android:state_pressed="false"
        android:state_focused="false">
        <shape
            android:innerRadiusRatio="1"
            android:shape="rectangle" >
            <solid android:color="#00a3e2" />

            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp" />

        </shape>
    </item>

    <!-- button focused -->
    <item
        android:state_pressed="false"
        android:state_focused="true">
        <shape
            android:innerRadiusRatio="1"
            android:shape="rectangle" >
            <solid android:color="#5a97f5" />

            <padding
                android:bottom="5dp"
                android:left="10dp"
                android:right="10dp"
                android:top="5dp" />
        </shape></item>

    <!-- button pressed -->
    <item
        android:state_pressed="true"
        android:state_focused="false">
        <shape
            android:innerRadiusRatio="1"
            android:shape="rectangle" >
            <solid android:color="#478df9"/>
            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp" />
        </shape></item>
</selector>

C# JSON Serialization of Dictionary into {key:value, ...} instead of {key:key, value:value, ...}

use property UseSimpleDictionaryFormat on DataContractJsonSerializer and set it to true.

Does the job :)

How can I execute Shell script in Jenkinsfile?

There's the Managed Script Plugin which provides an easy way of managing user scripts. It also adds a build step action which allows you to select which user script to execute.

Python string.join(list) on object array rather than string array

You could use a list comprehension or a generator expression instead:

', '.join([str(x) for x in list])  # list comprehension
', '.join(str(x) for x in list)    # generator expression

Box-Shadow on the left side of the element only

You probably need more blur and a little less spread.

box-shadow: -10px 0px 10px 1px #aaaaaa;

Try messing around with the box shadow generator here http://css3generator.com/ until you get your desired effect.

How to use `replace` of directive definition?

You are getting confused with transclude: true, which would append the inner content.

replace: true means that the content of the directive template will replace the element that the directive is declared on, in this case the <div myd1> tag.

http://plnkr.co/edit/k9qSx15fhSZRMwgAIMP4?p=preview

For example without replace:true

<div myd1><span class="replaced" myd1="">directive template1</span></div>

and with replace:true

<span class="replaced" myd1="">directive template1</span>

As you can see in the latter example, the div tag is indeed replaced.

PHP 7 simpleXML

  1. Use php -v //PHP 8.0.1

  2. Check the latest version of simple xml here

https://pkgs.org/download/php-simplexml

  1. Mine was version 8 so
sudo apt-get install php8.0-xml

Java: Difference between the setPreferredSize() and setSize() methods in components

IIRC ...

setSize sets the size of the component.

setPreferredSize sets the preferred size. The Layoutmanager will try to arrange that much space for your component.

It depends on whether you're using a layout manager or not ...

Remove numbers from string sql server

Remove everything after first digit (was adequate for my use case): LEFT(field,PATINDEX('%[0-9]%',field+'0')-1)

Remove trailing digits: LEFT(field,len(field)+1-PATINDEX('%[^0-9]%',reverse('0'+field))

Rename master branch for both local and remote Git repositories

The selected answer failed when I tried it. It throws an error: refusing to delete the current branch: refs/heads/master. I guess I'll post what works for me:

git checkout master             # if not in master already

git branch placeholder          # create placeholder branch
git checkout placeholder        # checkout to placeholder
git push remote placeholder     # push placeholder to remote repository

git branch -d master            # remove master in local repository
git push remote :master         # remove master from remote repository.

The trick is to checkout to the placeholder right before pushing it to remote repository. The rest is self explanatory, deleting the master branch and push it to the remote repository should works now. Excerpted from here.

Make xargs execute the command once for each line of input

It seems I don't have enough reputation to add a comment to Tobia's answer above, so I am adding this "answer" to help those of us wanting to experiment with xargs the same way on the Windows platforms.

Here is a windows batch file that does the same thing as Tobia's quickly coded "show" script:

@echo off
REM
REM  cool trick of using "set" to echo without new line
REM  (from:  http://www.psteiner.com/2012/05/windows-batch-echo-without-new-line.html)
REM
if "%~1" == "" (
    exit /b
)

<nul set /p=Args:  "%~1"
shift

:start
if not "%~1" == "" (
    <nul set /p=, "%~1"
    shift
    goto start
)
echo.

Add to integers in a list

You can append to the end of a list:

foo = [1, 2, 3, 4, 5]
foo.append(4)
foo.append([8,7])    
print(foo)            # [1, 2, 3, 4, 5, 4, [8, 7]]

You can edit items in the list like this:

foo = [1, 2, 3, 4, 5]
foo[3] = foo[3] + 4     
print(foo)            # [1, 2, 3, 8, 5]

Insert integers into the middle of a list:

x = [2, 5, 10]
x.insert(2, 77)
print(x)              # [2, 5, 77, 10]

How to pass boolean parameter value in pipeline to downstream jobs?

Assuming

value: update_composer

was the issue, try

value: Boolean.valueOf(update_composer)

is there a less cumbersome way in which I can just pass ALL the pipeline parameters to the downstream job

Not that I know of, at least not without using Jenkins API calls and disabling the Groovy sandbox.

Adding a splash screen to Flutter apps

For Android, go to this path,

android > app > src > main > res > drawable > launcher_background.xml

default code is for white colour background screen. like this,

<!-- You can insert your own image assets here -->
 <item>
    <bitmap
        android:gravity="center"
        android:src="@mipmap/launch_image" />
</item> 

enter image description here You can changes its color or modify this by adding icon or any custom design. for more customisation detail checkout this for android.


for Ios

open Ios project in Xcode.

select Runner and then.inside Runner folder Main.Storyboard file is there, enter image description here

by default its colour is white, you can customise or change colour this by your requirement, for more customisation check out this Ios.

enter image description here

A beginner's guide to SQL database design

It's been a while since I read it (so, I'm not sure how much of it is still relevant), but my recollection is that Joe Celko's SQL for Smarties book provides a lot of info on writing elegant, effective, and efficient queries.

ORA-00984: column not allowed here

Replace double quotes with single ones:

INSERT
INTO    MY.LOGFILE
        (id,severity,category,logdate,appendername,message,extrainfo)
VALUES  (
       'dee205e29ec34',
       'FATAL',
       'facade.uploader.model',
       '2013-06-11 17:16:31',
       'LOGDB',
       NULL,
       NULL
       )

In SQL, double quotes are used to mark identifiers, not string constants.

How to get $HOME directory of different user in bash script?

For the sake of an alternative answer for those searching for a lightweight way to just find a user's home dir...

Rather than messing with su hacks, or bothering with the overhead of launching another bash shell just to find the $HOME environment variable...

Lightweight Simple Homedir Query via Bash

There is a command specifically for this: getent

getent passwd someuser | cut -f6 -d:

getent can do a lot more... just see the man page. The passwd nsswitch database will return the user's entry in /etc/passwd format. Just split it on the colon : to parse out the fields.

It should be installed on most Linux systems (or any system that uses GNU Lib C (RHEL: glibc-common, Deb: libc-bin)

How to Get the Query Executed in Laravel 5? DB::getQueryLog() Returning Empty Array

I think the answer located in this article: https://arjunphp.com/laravel-5-5-log-eloquent-queries/

is fast and simple to achieve query logging.

You just have to add to the AppServiceProvider in the boot method a callback to listen to DB queries:

namespace App\Providers;

use DB;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        DB::listen(function($query) {
            logger()->info($query->sql . print_r($query->bindings, true));
        });
    }
}

Prevent the keyboard from displaying on activity start

just add this on your Activity:

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
      if (getCurrentFocus() != null) {
           InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
           imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
      }
      return super.dispatchTouchEvent(ev);
}

What is the first character in the sort order used by Windows Explorer?

The first visible character is '!' according to ASCII table.And the last one is '~' So "!file.doc" or "~file.doc' will be the top one depending your ranking order. You can check the ascii table here: http://www.asciitable.com/

Edit: This answer is based on the opinion of the author and not facts.

How to get item count from DynamoDB?

If you happen to reach here, and you are working with C#, here is the code:

var cancellationToken = new CancellationToken();

var request = new ScanRequest("TableName") {Select = Select.COUNT};

var result = context.Client.ScanAsync(request, cancellationToken).Result;

totalCount = result.Count;

Best lightweight web server (only static content) for Windows

You can use Python as a quick way to host static content. On Windows, there are many options for running Python, I've personally used CygWin and ActivePython.

To use Python as a simple HTTP server just change your working directory to the folder with your static content and type python -m SimpleHTTPServer 8000, everything in the directory will be available at http:/localhost:8000/

Python 3

To do this with Python, 3.4.1 (and probably other versions of Python 3), use the http.server module:

python -m http.server <PORT>
# or possibly:
python3 -m http.server <PORT>

# example:
python -m http.server 8080

On Windows:

py -m http.server <PORT>

How to make Google Fonts work in IE?

While Yi Jiang's solution may work, I don't believe abandoning the Google Web Font API is the right answer here. We serve a local jQuery file when it's not properly loaded from the CDN, right?

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="/js/jquery-1.9.0.min.js"><\/script>')</script>

So why wouldn't we do the same for fonts, specifically for < IE9?

<link href='http://fonts.googleapis.com/css?family=Cardo:400,400italic,700' rel='stylesheet' type='text/css'>
<!--[if lt IE 9]><link href='/css/fonts.css' rel='stylesheet' type='text/css'><![endif]-->

Here's my process when using custom fonts:

  1. Download the font's ZIP folder from Google, and use Font Squirrel's @font-face Generator to create the local web font.
  2. Create a fonts.css file that calls the newly created, locally hosted font files (only linking to the file if < IE9, as shown above). NOTE: The @font-face Generator creates this file for you.

    @font-face {
      font-family: 'cardoitalic';
      src: url('cardo-italic-webfont.eot');
      src: url('cardo-italic-webfont.eot?#iefix') format('embedded-opentype'),
        url('cardo-italic-webfont.woff') format('woff'),
        url('cardo-italic-webfont.ttf') format('truetype'),
        url('cardo-italic-webfont.svg#cardoitalic') format('svg');
      font-weight: normal;
      font-style: normal;
    }
    @font-face {
      font-family: 'cardobold';
      src: url('cardo-bold-webfont.eot');
      src: url('cardo-bold-webfont.eot?#iefix') format('embedded-opentype'),
        url('cardo-bold-webfont.woff') format('woff'),
        url('cardo-bold-webfont.ttf') format('truetype'),
        url('cardo-bold-webfont.svg#cardobold') format('svg');
      font-weight: normal;
      font-style: normal;
    }
    @font-face {
      font-family: 'cardoregular';
      src: url('cardo-regular-webfont.eot');
      src: url('cardo-regular-webfont.eot?#iefix') format('embedded-opentype'),
         url('cardo-regular-webfont.woff') format('woff'),
         url('cardo-regular-webfont.ttf') format('truetype'),
         url('cardo-regular-webfont.svg#cardoregular') format('svg');
      font-weight: normal;
      font-style: normal;
    }
    
  3. Using IE conditional classes in your main stylesheet to avoide faux weights and styles, your font styles might look like this:

    h1{
      font-size:3.25em;
      font-weight:normal;
      font-style:italic;
      font-family:'Cardo','cardoitalic',serif;
      line-height:1.25em;
    }
    h2{
      font-size:2.75em;
      font-weight:700;
      font-family:'Cardo','cardobold',serif;
      line-height:1.25em;
    }
    strong
    ,b{
      font-family:'Cardo','cardobold',serif;
      font-weight:700,
    }
    .lt-ie9 h1{
      font-style:normal;
    }
    .lt-ie9 h2{
      font-weight:normal;
    }
    .lt-ie9 strong,
    .lt-ie9 b{
      font-weight:normal,
    }
    

Sure, it's a little extra work, but haven't we come to expect this from IE? Besides, it becomes second-nature after awhile.

Reading numbers from a text file into an array in C

for (i = 0; i < 16; i++)
{
    fscanf(myFile, "%d", &numberArray[i]);
}

This is attempting to read the whole string, "5623125698541159" into &numArray[0]. You need spaces between the numbers:

5 6 2 3 ...

Android Studio doesn't recognize my device

Solution for those working with Huawei phones - You will get this error when ADB interface is not installed. Check if you have installed Huawei HiSuite. USB driver gets installed when you install HiSuite (I suppose this is true for most of the new phones that come with a Sync Software). If the ADB interface is installed on your computer you should see 'Android Composite ADB Interface' under Android Phone in your Device Manager as shown in this picture. enter image description here

How do I remove leading whitespace in Python?

The question doesn't address multiline strings, but here is how you would strip leading whitespace from a multiline string using python's standard library textwrap module. If we had a string like:

s = """
    line 1 has 4 leading spaces
    line 2 has 4 leading spaces
    line 3 has 4 leading spaces
"""

if we print(s) we would get output like:

>>> print(s)
    this has 4 leading spaces 1
    this has 4 leading spaces 2
    this has 4 leading spaces 3

and if we used textwrap.dedent:

>>> import textwrap
>>> print(textwrap.dedent(s))
this has 4 leading spaces 1
this has 4 leading spaces 2
this has 4 leading spaces 3

Regular expression - starting and ending with a character string

^wp.*\.php$ Should do the trick.

The .* means "any character, repeated 0 or more times". The next . is escaped because it's a special character, and you want a literal period (".php"). Don't forget that if you're typing this in as a literal string in something like C#, Java, etc., you need to escape the backslash because it's a special character in many literal strings.

How to detect string which contains only spaces?

if(!str.trim()){
  console.log('string is empty or only contains spaces');
}

Removing the whitespace from a string can be done using String#trim().

To check if a string is null or undefined, one can check if the string itself is falsey, in which case it is null, undefined, or an empty string. This first check is necessary, as attempting to invoke methods on null or undefined will result in an error. To check if it contains only spaces, one can check if the string is falsey after trimming, which means that it is an empty string at that point.

if(!str || !str.trim()){
   //str is null, undefined, or contains only spaces
}

This can be simplified using the optional chaining operator.

if(!str?.trim()){
   //str is null, undefined, or contains only spaces
}

If you are certain that the variable will be a string, only the second check is necessary.

if(!str.trim()){
   console.log("str is empty or contains only spaces");
}

Spring Data: "delete by" is supported?

2 ways:-

1st one Custom Query

@Modifying
@Query("delete from User where firstName = :firstName")
void deleteUsersByFirstName(@Param("firstName") String firstName);

2nd one JPA Query by method

List<User> deleteByLastname(String lastname);

When you go with query by method (2nd way) it will first do a get call

select * from user where last_name = :firstName

Then it will load it in a List Then it will call delete id one by one

delete from user where id = 18
delete from user where id = 19

First fetch list of object, then for loop to delete id one by one

But, the 1st option (custom query),

It's just a single query It will delete wherever the value exists.

Go through this link too https://www.baeldung.com/spring-data-jpa-deleteby

Showing empty view when ListView is empty

I highly recommend you to use ViewStubs like this

<FrameLayout
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="1" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <ViewStub
        android:id="@android:id/empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout="@layout/empty" />
</FrameLayout>

See the full example from Cyril Mottier

Escaping single quotes in JavaScript string for JavaScript evaluation

var str ="fsdsd'4565sd"; str.replace(/'/g,"'")

This worked for me. Kindly try this

enter image description here

Share Text on Facebook from Android App via ACTION_SEND

Check this out : By this we can check activity results also....
// Open all sharing option for user
                    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); 
                    sharingIntent.setType("text/plain");                    
                    sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, ShortDesc+" from "+BusinessName);
                    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, ShortDesc+" "+ShareURL);
                    sharingIntent.putExtra(Intent.EXTRA_TITLE, ShortDesc+" "+ShareURL);
                    startActivityForResult(Intent.createChooser(sharingIntent, "Share via"),1000);
/**
     * Get the result when we share any data to another activity 
     * */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch(requestCode) {
        case 1000:
            if(resultCode == RESULT_OK)
                Toast.makeText(getApplicationContext(), "Activity 1 returned OK", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(getApplicationContext(), "Activity 1 returned NOT OK", Toast.LENGTH_LONG).show();
            break;
        case 1002:
            if(resultCode == RESULT_OK)
                Toast.makeText(getApplicationContext(), "Activity 2 returned OK", Toast.LENGTH_LONG).show();
            break;
        }// end switch



    }// end onActivityResult

String escape into XML

And if you want, like me when I found this question, to escape XML node names, like for example when reading from an XML serialization, use the easiest way:

XmlConvert.EncodeName(string nameToEscape)

It will also escape spaces and any non-valid characters for XML elements.

http://msdn.microsoft.com/en-us/library/system.security.securityelement.escape%28VS.80%29.aspx

Returning Promises from Vuex actions

TL:DR; return promises from you actions only when necessary, but DRY chaining the same actions.

For a long time I also though that returning actions contradicts the Vuex cycle of uni-directional data flow.

But, there are EDGE CASES where returning a promise from your actions might be "necessary".

Imagine a situation where an action can be triggered from 2 different components, and each handles the failure case differently. In that case, one would need to pass the caller component as a parameter to set different flags in the store.

Dumb example

Page where the user can edit the username in navbar and in /profile page (which contains the navbar). Both trigger an action "change username", which is asynchronous. If the promise fails, the page should only display an error in the component the user was trying to change the username from.

Of course it is a dumb example, but I don't see a way to solve this issue without duplicating code and making the same call in 2 different actions.

How to read the last row with SQL Server

In order to retrieve the last row of a table for MS SQL database 2005, You can use the following query:

select top 1 column_name from table_name order by column_name desc; 

Note: To get the first row of the table for MS SQL database 2005, You can use the following query:

select top 1 column_name from table_name; 

How can I parse a local JSON file from assets folder into a ListView?

If you are using Kotlin in android then you can create Extension function.
Extension Functions are defined outside of any class - yet they reference the class name and can use this. In our case we use applicationContext.
So in Utility class you can define all extension functions.


Utility.kt

fun Context.loadJSONFromAssets(fileName: String): String {
    return applicationContext.assets.open(fileName).bufferedReader().use { reader ->
        reader.readText()
    }
}

MainActivity.kt

You can define private function for load JSON data from assert like this:

 lateinit var facilityModelList: ArrayList<FacilityModel>
 private fun bindJSONDataInFacilityList() {
    facilityModelList = ArrayList<FacilityModel>()
    val facilityJsonArray = JSONArray(loadJSONFromAsserts("NDoH_facility_list.json")) // Extension Function call here
    for (i in 0 until facilityJsonArray.length()){
        val facilityModel = FacilityModel()
        val facilityJSONObject = facilityJsonArray.getJSONObject(i)
        facilityModel.Facility = facilityJSONObject.getString("Facility")
        facilityModel.District = facilityJSONObject.getString("District")
        facilityModel.Province = facilityJSONObject.getString("Province")
        facilityModel.Subdistrict = facilityJSONObject.getString("Facility")
        facilityModel.code = facilityJSONObject.getInt("code")
        facilityModel.gps_latitude = facilityJSONObject.getDouble("gps_latitude")
        facilityModel.gps_longitude = facilityJSONObject.getDouble("gps_longitude")

        facilityModelList.add(facilityModel)
    }
}

You have to pass facilityModelList in your ListView


FacilityModel.kt

class FacilityModel: Serializable {
    var District: String = ""
    var Facility: String = ""
    var Province: String = ""
    var Subdistrict: String = ""
    var code: Int = 0
    var gps_latitude: Double= 0.0
    var gps_longitude: Double= 0.0
}

In my case JSON response start with JSONArray

[
  {
    "code": 875933,
    "Province": "Eastern Cape",
    "District": "Amathole DM",
    "Subdistrict": "Amahlathi LM",
    "Facility": "Amabele Clinic",
    "gps_latitude": -32.6634,
    "gps_longitude": 27.5239
  },

  {
    "code": 455242,
    "Province": "Eastern Cape",
    "District": "Amathole DM",
    "Subdistrict": "Amahlathi LM",
    "Facility": "Burnshill Clinic",
    "gps_latitude": -32.7686,
    "gps_longitude": 27.055
  }
]

input checkbox true or checked or yes

Accordingly to W3C checked input's attribute can be absent/ommited or have "checked" as its value. This does not invalidate other values because there's no restriction to the browser implementation to allow values like "true", "on", "yes" and so on. To guarantee that you'll write a cross-browser checkbox/radio use checked="checked", as recommended by W3C.

disabled, readonly and ismap input's attributes go on the same way.

EDITED

empty is not a valid value for checked, disabled, readonly and ismap input's attributes, as warned by @Quentin

Difference between logical addresses, and physical addresses?

This answer is by no means exhaustive but it may explain it enough to make things click.

In virtual memory systems, there is a disconnect between logical and physical addresses.

An application can be given a virtual address space of (let's say) 4G. This is its usable memory and it's free to use it as it sees fit. It's a nice contiguous block of memory (from the point of view of the application).

However, it is not the only application running, and the OS has to mediate between them all. Underneath that nice contiguous model, there is a lot of mapping going on to convert logical to physical addresses.

With this mapping, the OS and hardware (I'll just call these the lower layers from here on in) is free to put the application pages anywhere it wants (either in physical memory or swapped out to secondary storage).

When the application tries to access memory at logical address 50, the lower levels can translate that to a physical address using translation tables. And, if it tries to access logical memory that's been swapped out to disk, a page fault is raised and the lower levels can bring the relevant data back into memory, at whatever physical address it wants.

In the bad old days when physical addresses were all you had, code had to be relocatable (or fixed up on load) since it could load anywhere. With virtual memory, that code (and data) can be at logical memory location 50 in a dozen different processes at the same time - it's actual physical address will be different however.

It can even be shared so that one physical copy exists in the address space of many processes at once. This is the crux of shared code (so we don't use more physical memory than we need) and shared memory to allow easy inter-process communication).

It is, of course, less efficient than a pure physical-address environment but the CPU manufacturers try to make it as insanely efficient as possible, since it's used heavily. The advantages far outweigh the disadvantages.

Transitions on the CSS display property

I started an open source skeleton project called Toggle Display Animate.

This skeleton helper will allow you to easily mimic jQuery show/hide, but with in/out CSS 3 transition animations.

It uses class toggles so you can use any CSS methods you want on elements besides display:none|block|table|inline, etc. as well as other alternate uses that can be thought up.

Its main design purpose is for element toggle states, and it supports a revert state where hiding the object allows you to run your keyframe in reverse or play an alternate animation for hiding the element.

Most of the markup for the concept I am working on is CSS, and there is very little JavaScript actually used.

There is a demo here: http://marcnewton.co.uk/projects/toggle-display-animate/

How to add hours to current date in SQL Server?

The DATEADD() function adds or subtracts a specified time interval from a date.

DATEADD(datepart,number,date)

datepart(interval) can be hour, second, day, year, quarter, week etc; number (increment int); date(expression smalldatetime)

For example if you want to add 30 days to current date you can use something like this

 select dateadd(dd, 30, getdate())

To Substract 30 days from current date

select dateadd(dd, -30, getdate())

Better way to call javascript function in a tag

Some advantages to the second option:

  1. You can use this inside onclick to reference the anchor itself (doing the same in option 1 will give you window instead).

  2. You can set the href to a non-JS compatible URL to support older browsers (or those that have JS disabled); browsers that support JavaScript will execute the function instead (to stay on the page you have to use onclick="return someFunction();" and return false from inside the function or onclick="return someFunction(); return false;" to prevent default action).

  3. I've seen weird stuff happen when using href="javascript:someFunction()" and the function returns a value; the whole page would get replaced by just that value.

Pitfalls

Inline code:

  1. Runs in document scope as opposed to code defined inside <script> tags which runs in window scope; therefore, symbols may be resolved based on an element's name or id attribute, causing the unintended effect of attempting to treat an element as a function.

  2. Is harder to reuse; delicate copy-paste is required to move it from one project to another.

  3. Adds weight to your pages, whereas external code files can be cached by the browser.

Detect click inside/outside of element with single event handler

What about this?

<style type="text/css">
div {border: 1px solid red; color: black; background-color: #9999DD;
width: 20em; height: 40em;}
</style>

<script type="text/javascript">
function sayLoc(e) {
e = e || window.event;
var tgt = e.target || e.srcElement;

// Get top lef co-ords of div
var divX = findPosX(tgt);
var divY = findPosY(tgt);

// Workout if page has been scrolled
var pXo = getPXoffset();
var pYo = getPYoffset();

// Subtract div co-ords from event co-ords
var clickX = e.clientX - divX + pXo;
var clickY = e.clientY - divY + pYo;

alert('Co-ords within div (x, y): '
+ clickX + ', ' + clickY);
}

function findPosX(obj) {
var curleft = 0;
if (obj.offsetParent) {
while (obj.offsetParent) {
curleft += obj.offsetLeft
obj = obj.offsetParent;
}
} else if (obj.x) {
curleft += obj.x;
}
return curleft;
}

function findPosY(obj) {
var curtop = 0;
if (obj.offsetParent) {
while (obj.offsetParent) {
curtop += obj.offsetTop
obj = obj.offsetParent;
}
} else if (obj.y) {
curtop += obj.y;
}
return curtop;
}

function getPXoffset(){
if (self.pageXOffset) { // all except Explorer
return self.pageXOffset;
} else if (document.documentElement
&& document.documentElement.scrollTop) {// Explorer 6 Strict
return document.documentElement.scrollLeft;
} else if (document.body) { // all other Explorers
return document.body.scrollLeft;
}
}

function getPYoffset(){
if (self.pageYOffset) { // all except Explorer
return self.pageYOffset;
} else if (document.documentElement
&& document.documentElement.scrollTop) {// Explorer 6 Strict
return document.documentElement.scrollTop;
} else if (document.body) { // all other Explorers
return document.body.scrollTop;
}
}
</script>

<div onclick="sayLoc(event);"></div>

(from http://bytes.com/topic/javascript/answers/151689-detect-click-inside-div-mozilla, using the Google.)

Boolean.parseBoolean("1") = false...?

Returns true if comes 'y', '1', 'true', 'on'or whatever you add in similar way

boolean getValue(String value) {
  return ("Y".equals(value.toUpperCase()) 
      || "1".equals(value.toUpperCase())
      || "TRUE".equals(value.toUpperCase())
      || "ON".equals(value.toUpperCase()) 
     );
}

java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?

SSSSSS is microseconds. Let us say the time is 10:30:22 (Seconds 22) and 10:30:22.1 would be 22 seconds and 1/10 of a second . Extending the same logic , 10:32.22.000132 would be 22 seconds and 132/1,000,000 of a second, which is nothing but microseconds.

How can a file be copied?

Copying a file is a relatively straightforward operation as shown by the examples below, but you should instead use the shutil stdlib module for that.

def copyfileobj_example(source, dest, buffer_size=1024*1024):
    """      
    Copy a file from source to dest. source and dest
    must be file-like objects, i.e. any object with a read or
    write method, like for example StringIO.
    """
    while True:
        copy_buffer = source.read(buffer_size)
        if not copy_buffer:
            break
        dest.write(copy_buffer)

If you want to copy by filename you could do something like this:

def copyfile_example(source, dest):
    # Beware, this example does not handle any edge cases!
    with open(source, 'rb') as src, open(dest, 'wb') as dst:
        copyfileobj_example(src, dst)

How to replace a string in multiple files in linux command line

I am giving an example for fixing a common shebang error in python sources.

You can try the grep/sed approach. Here is one that works with GNU sed and won't break a git repo:

$ grep -rli --exclude '*.git*' '#!/usr/bin/python' . | xargs -I {} \
gsed -i '' -e 's/#!\/usr\/bin\/python/#!\/usr\/bin\/env python/' {}

Or you can use greptile :)

$ greptile -x .py -l -i -g '#!/usr/bin/env python' -r '#!/usr/bin/python' .

I just tested the first script, and the second should work as well. Be careful with escape characters, I think it should be easier to use greptile in most cases. Of course, you can do many interesting things with sed, and for that it may be preferable to master using it with xargs.

Resolve build errors due to circular dependency amongst classes

In some cases it is possible to define a method or a constructor of class B in the header file of class A to resolve circular dependencies involving definitions. In this way you can avoid having to put definitions in .cc files, for example if you want to implement a header only library.

// file: a.h
#include "b.h"
struct A {
  A(const B& b) : _b(b) { }
  B get() { return _b; }
  B _b;
};

// note that the get method of class B is defined in a.h
A B::get() {
  return A(*this);
}

// file: b.h
class A;
struct B {
  // here the get method is only declared
  A get();
};

// file: main.cc
#include "a.h"
int main(...) {
  B b;
  A a = b.get();
}

How can I find the OWNER of an object in Oracle?

I found this question as the top result while Googling how to find the owner of a table in Oracle, so I thought that I would contribute a table specific answer for others' convenience.

To find the owner of a specific table in an Oracle DB, use the following query:

select owner from ALL_TABLES where TABLE_NAME ='<MY-TABLE-NAME>';

Keylistener in Javascript

The code is

document.addEventListener('keydown', function(event){
    alert(event.keyCode);
} );

This return the ascii code of the key. If you need the key representation, use event.key (This will return 'a', 'o', 'Alt'...)

How to add an image in Tkinter?

Python 3.3.1 [MSC v.1600 32 bit (Intel)] on win32 14.May.2013

This worked for me, by following the code above

from tkinter import *
from PIL import ImageTk, Image
import os

root = Tk()
img = ImageTk.PhotoImage(Image.open("True1.gif"))
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()

HMAC-SHA256 Algorithm for signature calculation

This is working fine for me

I have add dependency

compile 'commons-codec:commons-codec:1.9'

ref: http://mvnrepository.com/artifact/commons-codec/commons-codec/1.9

my function

public String encode(String key, String data) {
    try {

        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        return new String(Hex.encodeHex(sha256_HMAC.doFinal(data.getBytes("UTF-8"))));

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return null;
}

Can I use tcpdump to get HTTP requests, response header and response body?

There are tcpdump filters for HTTP GET & HTTP POST (or for both plus message body):

  • Run man tcpdump | less -Ip examples to see some examples

  • Here’s a tcpdump filter for HTTP GET (GET = 0x47, 0x45, 0x54, 0x20):

    sudo tcpdump -s 0 -A 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420'
    
  • Here’s a tcpdump filter for HTTP POST (POST = 0x50, 0x4f, 0x53, 0x54):

    sudo tcpdump -s 0 -A 'tcp dst port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354)'
    
  • Monitor HTTP traffic including request and response headers and message body (source):

    tcpdump -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
    tcpdump -X -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
    

For more information on the bit-twiddling in the TCP header see: String-Matching Capture Filter Generator (link to Sake Blok's explanation).

Add custom icons to font awesome

Similar approach to @Samuel-bergström:

  • Download Fontawesome SVG https://github.com/FortAwesome/Font-Awesome/blob/master/src/assets/font-awesome/fonts/fontawesome-webfont.svg
  • Download FontForge http://fontforge.github.io/en-US/downloads/
  • Download Inkscape
  • Open Inskscape and create a single layer shape as your new font icon
  • Save SVG file, Close Inkscape
  • Open FontForge (If you have multiple monitors, use Windows-LeftArrow, to reposition as they have strange SWING java windows that go off monitor, and have modal problems with popups - I had to check my task bar for some)
  • File | Open fontawesome-webfont.svg
  • File | Import
  • Scroll to the bottom, Right Click on Icon | Glyph Info
  • Update Glyph Name to uniFXXX (XXX is something like 501, a higher number than the highest Unicode used in v4.5 of FontAwesome)
  • Unicode Vlaue U+fXXX
  • Click OK
  • File | Save
  • File | Generate Fonts ...
  • Close FontForge
  • Open your web project
  • Copy your font files to the (in my project) "\Content\fonts\" folder.
  • Edit "\Content\styles\fa\path.less" to be like:

_x000D_
_x000D_
@font-face {_x000D_
      font-family: 'FontAwesome';_x000D_
      //src: url('@{fa-font-path}/fontawesome-webfont.eot?v=@{fa-version}');_x000D_
      src: _x000D_
     //url('@{fa-font-path}/fontawesome-webfont.eot?#iefix&v=@{fa-version}') format('embedded-opentype'),_x000D_
        //url('@{fa-font-path}/fontawesome-webfont.woff2?v=@{fa-version}') format('woff2'),_x000D_
        url('@{fa-font-path}/fontawesomeregular.woff?v=@{fa-version}') format('woff'),_x000D_
        url('@{fa-font-path}/fontawesomeregular.ttf?v=@{fa-version}') format('truetype'),_x000D_
        url('@{fa-font-path}/fontawesomeregular.svg?v=@{fa-version}#fontawesomeregular') format('svg');_x000D_
    //  src: url('@{fa-font-path}/FontAwesome.otf') format('opentype'); // used when developing fonts_x000D_
      font-weight: normal;_x000D_
      font-style: normal;_x000D_
    }
_x000D_
_x000D_
_x000D_

I know it may be 'controversial' to comment out other file types, but happy to hear how to generate .eot or .otf files in the comments.

  • and finally, as Samuel mentions, update your CSS/LESS with:

    .fa-XXX:before { content: "\f501"; }

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

It is about string concatenation performance. It's potentially significant if your have dense logging statements.

(Prior to SLF4J 1.7) But only two parameters are possible

Because the vast majority of logging statements have 2 or fewer parameters, so SLF4J API up to version 1.6 covers (only) the majority of use cases. The API designers have provided overloaded methods with varargs parameters since API version 1.7.

For those cases where you need more than 2 and you're stuck with pre-1.7 SLF4J, then just use either string concatenation or new Object[] { param1, param2, param3, ... }. There should be few enough of them that the performance is not as important.

How to implement an android:background that doesn't stretch?

You should use ImageView if you don't want it to stretch. Background images will always stretch to fit the view. You need to set it as a Drawable to force the image aspect to the object.

Otherwise, if you are sticking with the Button idea, then you will need to force the scaling in the button to prevent the image from stretching.

Code:

onCreate(Bundle bundle) {
  // Set content layout, etc up here

  // Now adjust button sizes
  Button b = (Button) findViewById(R.id.somebutton);
  int someDimension = 50; //50pixels
  b.setWidth(someDimension);
  b.setHeight(someDimension);
}

An Iframe I need to refresh every 30 seconds (but not the whole page)

Okay... so i know that i'm answering to a decade question, but wanted to add something! I wanted to add a google calendar with special iframe parameters. Problem is that the calendar didn't work without it. 30 seconds is a bit short for my use, so i changed that in my own file to 15 minutes This worked for me.

<script>
window.setInterval("reloadIFrame();", 30000);
function reloadIFrame() {
 document.getElementById("calendar").src=calendar.src;
}
</script>

    <iframe id="calendar" src="[URL]" style="border-width:0" width=100% height=100% frameborder="0" scrolling="no"></iframe>

How to get the absolute path to the public_html folder?

Where is the file that you're running? If it is in your public html folder, you can do echo dirname(__FILE__);

How to enable C++11/C++0x support in Eclipse CDT?

For me on Eclipse Neon I followed Trismegistos answer here above , YET I also added an additional step:

  • Go to project --> Properties --> C++ General --> Preprocessor Include paths,Macros etc. --> Providers --> CDT Cross GCC Built-in Compiler Settings, append the flag "-std=c++11"

Hit apply and OK.

Cheers,

Guy.

Spring Boot War deployed to Tomcat

Update 2018-02-03 with Spring Boot 1.5.8.RELEASE.

In pom.xml, you need to tell Spring plugin when it is building that it is a war file by change package to war, like this:

<packaging>war</packaging>

Also, you have to excluded the embedded tomcat while building the package by adding this:

    <!-- to deploy as a war in tomcat -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

The full runable example is in here https://www.surasint.com/spring-boot-create-war-for-tomcat/

Android getting value from selected radiobutton

mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        RadioButton radioButton = (RadioButton)group.findViewById(checkedId);
    }
});

How to prevent multiple definitions in C?

Including the implementation file (test.c) causes it to be prepended to your main.c and complied there and then again separately. So, the function test has two definitions -- one in the object code of main.c and once in that of test.c, which gives you a ODR violation. You need to create a header file containing the declaration of test and include it in main.c:

/* test.h */
#ifndef TEST_H
#define TEST_H
void test(); /* declaration */
#endif /* TEST_H */

SQL select join: is it possible to prefix all columns as 'prefix.*'?

Or you could use Red Gate SQL Refactor or SQL Prompt, which expands your SELECT * into column lists with a click of the Tab button

so in your case, if you type in SELECT * FROM A JOIN B ... Go to the end of *, Tab button, voila! you'll see SELECT A.column1, A.column2, .... , B.column1, B.column2 FROM A JOIN B

It's not free though

Setting cursor at the end of any text of a textbox

There are multiple options:

txtBox.Focus();
txtBox.SelectionStart = txtBox.Text.Length;

OR

txtBox.Focus();
txtBox.CaretIndex = txtBox.Text.Length;

OR

txtBox.Focus();
txtBox.Select(txtBox.Text.Length, 0);

Simplest way to do a recursive self-join?

The Quassnoi query with a change for large table. Parents with more childs then 10: Formating as str(5) the row_number()

WITH    q AS 
        (
        SELECT  m.*, CAST(str(ROW_NUMBER() OVER (ORDER BY m.ordernum),5) AS VARCHAR(MAX)) COLLATE Latin1_General_BIN AS bc
        FROM    #t m
        WHERE   ParentID =0
        UNION ALL
        SELECT  m.*,  q.bc + '.' + str(ROW_NUMBER()  OVER (PARTITION BY m.ParentID ORDER BY m.ordernum),5) COLLATE Latin1_General_BIN
        FROM    #t m
        JOIN    q
        ON      m.parentID = q.DBID
        )
SELECT  *
FROM    q
ORDER BY
        bc

Why does instanceof return false for some literals?

I use:

function isString(s) {
    return typeof(s) === 'string' || s instanceof String;
}

Because in JavaScript strings can be literals or objects.

How can I install Apache Ant on Mac OS X?

Use Brew is always good way to install ANT and other needs. To install type below command on terminal.

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

after Brew installation , type

brew install ant

This will install Ant on your system. Also you will not need to worry about setting up the path.

Also i have documented on the same - How to Install ANT on Mac OS?

Template not provided using create-react-app

This work's for me :

Let's, uninstall create-react-app globally by this command:

npm uninstall -g create-react-app

After that in your project directory:

npm install create-react-app@latest

At the last:

npx create-react-app my-app

For typescript :

npx create-react-app my-app --template typescript

How to select records without duplicate on just one field in SQL?

Having Clause is the easiest way to find duplicate entry in Oracle and using rowid we can remove duplicate data..

DELETE FROM products WHERE rowid IN (
  SELECT MAX(sl) FROM (
  SELECT itemcode, (rowid) sl FROM products WHERE itemcode IN (
  SELECT itemcode FROM products GROUP BY itemcode HAVING COUNT(itemcode)>1
)) GROUP BY itemcode);

How to check if a variable is empty in python?

Just use not:

if not your_variable:
    print("your_variable is empty")

and for your 0 as string use:

if your_variable == "0":
    print("your_variable is 0 (string)")

combine them:

if not your_variable or your_variable == "0":
    print("your_variable is empty")

Python is about simplicity, so is this answer :)

ReactJS - Does render get called any time "setState" is called?

Yes. It calls the render() method every time we call setState only except when "shouldComponentUpdate" returns false.

How do I change the data type for a column in MySQL?

To change column data type there are change method and modify method

ALTER TABLE student_info CHANGE roll_no roll_no VARCHAR(255);

ALTER TABLE student_info MODIFY roll_no VARCHAR(255);

To change the field name also use the change method

ALTER TABLE student_info CHANGE roll_no identity_no VARCHAR(255);

How to check if a date is in a given range?

Use the DateTime class if you have PHP 5.3+. Easier to use, better functionality.

DateTime internally supports timezones, with the other solutions is up to you to handle that.

<?php    
/**
 * @param DateTime $date Date that is to be checked if it falls between $startDate and $endDate
 * @param DateTime $startDate Date should be after this date to return true
 * @param DateTime $endDate Date should be before this date to return true
 * return bool
 */
function isDateBetweenDates(DateTime $date, DateTime $startDate, DateTime $endDate) {
    return $date > $startDate && $date < $endDate;
}

$fromUser = new DateTime("2012-03-01");
$startDate = new DateTime("2012-02-01 00:00:00");
$endDate = new DateTime("2012-04-30 23:59:59");

echo isDateBetweenDates($fromUser, $startDate, $endDate);

Checking if a variable is defined?

This is useful if you want to do nothing if it does exist but create it if it doesn't exist.

def get_var
  @var ||= SomeClass.new()
end

This only creates the new instance once. After that it just keeps returning the var.

What's the difference between "super()" and "super(props)" in React when using es6 classes?

super() is used to call the parent constructor.

super(props) would pass props to the parent constructor.

From your example, super(props) would call the React.Component constructor passing in props as the argument.

More information on super: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super

How to implement a SQL like 'LIKE' operator in java?

i dont know exactly about the greedy issue, but try this if it works for you:

public boolean like(final String str, String expr)
  {
    final String[] parts = expr.split("%");
    final boolean traillingOp = expr.endsWith("%");
    expr = "";
    for (int i = 0, l = parts.length; i < l; ++i)
    {
      final String[] p = parts[i].split("\\\\\\?");
      if (p.length > 1)
      {
        for (int y = 0, l2 = p.length; y < l2; ++y)
        {
          expr += p[y];
          if (i + 1 < l2) expr += ".";
        }
      }
      else
      {
        expr += parts[i];
      }
      if (i + 1 < l) expr += "%";
    }
    if (traillingOp) expr += "%";
    expr = expr.replace("?", ".");
    expr = expr.replace("%", ".*");
    return str.matches(expr);
}

How to sort an ArrayList?

|*| Sorting an List :

import java.util.Collections;

|=> Sort Asc Order :

Collections.sort(NamAryVar);

|=> Sort Dsc Order :

Collections.sort(NamAryVar, Collections.reverseOrder());

|*| Reverse the order of List :

Collections.reverse(NamAryVar);

Selecting/excluding sets of columns in pandas

Here's how to create a copy of a DataFrame excluding a list of columns:

df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
df2 = df.drop(['B', 'D'], axis=1)

But be careful! You mention views in your question, suggesting that if you changed df, you'd want df2 to change too. (Like a view would in a database.)

This method doesn't achieve that:

>>> df.loc[0, 'A'] = 999 # Change the first value in df
>>> df.head(1)
     A         B         C         D
0  999 -0.742688 -1.980673 -0.920133
>>> df2.head(1) # df2 is unchanged. It's not a view, it's a copy!
          A         C
0  0.251262 -1.980673

Note also that this is also true of @piggybox's method. (Although that method is nice and slick and Pythonic. I'm not doing it down!!)

For more on views vs. copies see this SO answer and this part of the Pandas docs which that answer refers to.

Division in Python 2.7. and 3.3

In python 2.7, the / operator is integer division if inputs are integers.

If you want float division (which is something I always prefer), just use this special import:

from __future__ import division

See it here:

>>> 7 / 2
3
>>> from __future__ import division
>>> 7 / 2
3.5
>>>

Integer division is achieved by using //, and modulo by using %

>>> 7 % 2
1
>>> 7 // 2
3
>>>

EDIT

As commented by user2357112, this import has to be done before any other normal import.

How to navigate a few folders up?

You can use ..\path to go one level up, ..\..\path to go two levels up from path.

You can use Path class too.

C# Path class

JSP : JSTL's <c:out> tag

c:out also has an attribute for assigning a default value if the value of person.name happens to be null.

Source: out (TLDDoc Generated Documentation)

Comparing two input values in a form validation with AngularJS

Here is my simple version of the custom validator directive:

angular.module('app')
  .directive('equalsTo', function () {
    return {
      require: 'ngModel',
      link:    function (scope, elm, attrs, ngModel) {
        scope.$watchGroup([attrs.equalsTo, () => ngModel.$modelValue], newVal => {
          ngModel.$setValidity('equalsTo', newVal[0] === newVal[1]);
        });
      }
    };
  })

What is the most efficient way to store a list in the Django models?

"Premature optimization is the root of all evil."

With that firmly in mind, let's do this! Once your apps hit a certain point, denormalizing data is very common. Done correctly, it can save numerous expensive database lookups at the cost of a little more housekeeping.

To return a list of friend names we'll need to create a custom Django Field class that will return a list when accessed.

David Cramer posted a guide to creating a SeperatedValueField on his blog. Here is the code:

from django.db import models

class SeparatedValuesField(models.TextField):
    __metaclass__ = models.SubfieldBase

    def __init__(self, *args, **kwargs):
        self.token = kwargs.pop('token', ',')
        super(SeparatedValuesField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        if not value: return
        if isinstance(value, list):
            return value
        return value.split(self.token)

    def get_db_prep_value(self, value):
        if not value: return
        assert(isinstance(value, list) or isinstance(value, tuple))
        return self.token.join([unicode(s) for s in value])

    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_db_prep_value(value)

The logic of this code deals with serializing and deserializing values from the database to Python and vice versa. Now you can easily import and use our custom field in the model class:

from django.db import models
from custom.fields import SeparatedValuesField 

class Person(models.Model):
    name = models.CharField(max_length=64)
    friends = SeparatedValuesField()

Can I add an image to an ASP.NET button?

.my_btn{ 
  font-family:Arial; 
  font-size:10pt; 
  font-weight:normal; 
  height:30px; 
  line-height:30px; 
  width:98px; 
  border:0px;
  background-image:url('../Images/menu_image.png'); 
  cursor:pointer;
}

<asp:Button ID="clickme" runat="server" Text="Click" CssClass="my_btn" />

ASP.NET MVC controller actions that return JSON or partial html

I think you should consider the AcceptTypes of the request. I am using it in my current project to return the correct content type as follows.

Your action on the controller can test it as on the request object

if (Request.AcceptTypes.Contains("text/html")) {
   return View();
}
else if (Request.AcceptTypes.Contains("application/json"))
{
   return Json( new { id=1, value="new" } );
}
else if (Request.AcceptTypes.Contains("application/xml") || 
         Request.AcceptTypes.Contains("text/xml"))
{
   //
}

You can then implement the aspx of the view to cater for the partial xhtml response case.

Then in jQuery you can fetch it passing the type parameter as json:

$.get(url, null, function(data, textStatus) {
        console.log('got %o with status %s', data, textStatus);
        }, "json"); // or xml, html, script, json, jsonp or text

Hope this helps James

Serializing a list to JSON

You can also use Json.NET. Just download it at http://james.newtonking.com/pages/json-net.aspx, extract the compressed file and add it as a reference.

Then just serialize the list (or whatever object you want) with the following:

using Newtonsoft.Json;

string json = JsonConvert.SerializeObject(listTop10);

Update: you can also add it to your project via the NuGet Package Manager (Tools --> NuGet Package Manager --> Package Manager Console):

PM> Install-Package Newtonsoft.Json

Documentation: Serializing Collections

Very Simple, Very Smooth, JavaScript Marquee

My text marquee for more text, and position absolute enabled

http://jsfiddle.net/zrW5q/2075/

(function($) {
$.fn.textWidth = function() {
var calc = document.createElement('span');
$(calc).text($(this).text());
$(calc).css({
  position: 'absolute',
  visibility: 'hidden',
  height: 'auto',
  width: 'auto',
  'white-space': 'nowrap'
});
$('body').append(calc);
var width = $(calc).width();
$(calc).remove();
return width;
};

$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
    offset = that.width(),
    width = offset,
    css = {
        'text-indent': that.css('text-indent'),
        'overflow': that.css('overflow'),
        'white-space': that.css('white-space')
    },
    marqueeCss = {
        'text-indent': width,
        'overflow': 'hidden',
        'white-space': 'nowrap'
    },
    args = $.extend(true, {
        count: -1,
        speed: 1e1,
        leftToRight: false
    }, args),
    i = 0,
    stop = textWidth * -1,
    dfd = $.Deferred();

function go() {
    if (that.css('overflow') != "hidden") {
        that.css('text-indent', width + 'px');
        return false;
    }
    if (!that.length) return dfd.reject();

    if (width <= stop) {
        i++;
        if (i == args.count) {
            that.css(css);
            return dfd.resolve();
        }
        if (args.leftToRight) {
            width = textWidth * -1;
        } else {
            width = offset;
        }
    }
    that.css('text-indent', width + 'px');
    if (args.leftToRight) {
        width++;
    } else {
        width--;
    }
    setTimeout(go, args.speed);
};

if (args.leftToRight) {
    width = textWidth * -1;
    width++;
    stop = offset;
} else {
    width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
// $('h1').marquee();
$("h1").marquee();
$("h1").mouseover(function () {     
    $(this).removeAttr("style");
}).mouseout(function () {
    $(this).marquee();
});
})(jQuery);

MySQL - How to parse a string value to DATETIME format inside an INSERT statement?

Use MySQL's STR_TO_DATE() function to parse the string that you're attempting to insert:

INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
  (STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))

how to change text in Android TextView

setting the text to sam textview twice is overwritting the first written text. So the second time when we use settext we just append the new string like

textview.append("Step Two: fry egg");

Jquery- Get the value of first td in table

If you need to get all td's inside tr without defining id for them, you can use the code below :

var items = new Array();

$('#TABLE_ID td:nth-child(1)').each(function () {
      items.push($(this).html());
});

The code above will add all first cells inside the Table into an Array variable.

you can change nth-child(1) which means the first cell to any cell number you need.

hope this code helps you.

Add multiple items to a list

Thanks to AddRange:

Example:

public class Person
{ 
    private string Name;
    private string FirstName;

    public Person(string name, string firstname) => (Name, FirstName) = (name, firstname);
}

To add multiple Person to a List<>:

List<Person> listofPersons = new List<Person>();
listofPersons.AddRange(new List<Person>
{
    new Person("John1", "Doe" ),
    new Person("John2", "Doe" ),
    new Person("John3", "Doe" ),
 });

How to git-cherry-pick only changes to certain files?

I would just cherry-pick everything, then do this:

git reset --soft HEAD^

Then I would revert the changes I don't want, then make a new commit.

javascript date + 7 days

In One line:

new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)

How to catch integer(0)?

another option is rlang::is_empty (useful if you're working in the tidyverse)

The rlang namespace does not seem to be attached when attaching the tidyverse via library(tidyverse) - in this case you use purrr::is_empty, which is just imported from the rlang package.

By the way, rlang::is_empty uses user Gavin's approach.

rlang::is_empty(which(1:3 == 5))
#> [1] TRUE

Serving static web resources in Spring Boot & Spring Security application

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        String[] resources = new String[]{
                "/", "/home","/pictureCheckCode","/include/**",
                "/css/**","/icons/**","/images/**","/js/**","/layer/**"
        };

        http.authorizeRequests()
                .antMatchers(resources).permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout().logoutUrl("/404")
                .permitAll();
        super.configure(http);
    }
}

self referential struct definition?

There is sort of a way around this:

struct Cell {
  bool isParent;
  struct Cell* child;
};

struct Cell;
typedef struct Cell Cell;

If you declare it like this, it properly tells the compiler that struct Cell and plain-ol'-cell are the same. So you can use Cell just like normal. Still have to use struct Cell inside of the initial declaration itself though.

PostgreSQL Error: Relation already exists

There should be no single quotes here 'A'. Single quotes are for string literals: 'some value'.
Either use double quotes to preserve the upper case spelling of "A":

CREATE TABLE "A" ...

Or don't use quotes at all:

CREATE TABLE A ...

which is identical to

CREATE TABLE a ...

because all unquoted identifiers are folded to lower case automatically in PostgreSQL.


You could avoid problems with the index name completely by using simpler syntax:

CREATE TABLE csd_relationship (
    csd_relationship_id serial PRIMARY KEY,
    type_id integer NOT NULL,
    object_id integer NOT NULL
);

Does the same as your original query, only it avoids naming conflicts automatically. It picks the next free identifier automatically. More about the serial type in the manual.

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

Something like this could be it?

HTML

 <div class="random">
        SOMETHING
 </div>

CSS

body{

    text-align: center;
}

.random{

    width: 60%;
    margin: auto;
    background-color: yellow;
    display:block;

}

DEMO: http://jsfiddle.net/t5Pp2/2/

Edit: adding display:block doesn't ruin the thing, so...

You can also set the margin to: margin: 0 auto 0 auto; just to be sure it centers only this way not from the top too.

How to convert XML to java.util.Map and vice versa

I have tried different kinds of maps and the Conversion Box worked. I have used your map and have pasted an example below with some inner maps. Hope it is helpful to you ....

import java.util.HashMap;
import java.util.Map;

import cjm.component.cb.map.ToMap;
import cjm.component.cb.xml.ToXML;

public class Testing
{
public static void main(String[] args)
{
    try
    {
        Map<String, Object> map = new HashMap<String, Object>(); // ORIGINAL MAP

        map.put("name", "chris");
        map.put("island", "faranga");

        Map<String, String> mapInner = new HashMap<String, String>(); // SAMPLE INNER MAP

        mapInner.put("a", "A");
        mapInner.put("b", "B");
        mapInner.put("c", "C");

        map.put("innerMap", mapInner);

        Map<String, Object> mapRoot = new HashMap<String, Object>(); // ROOT MAP

        mapRoot.put("ROOT", map);

        System.out.println("Map: " + mapRoot);

        System.out.println();

        ToXML toXML = new ToXML();

        String convertedXML = String.valueOf(toXML.convertToXML(mapRoot, true)); // CONVERTING ROOT MAP TO XML

        System.out.println("Converted XML: " + convertedXML);

        System.out.println();

        ToMap toMap = new ToMap();

        Map<String, Object> convertedMap = toMap.convertToMap(convertedXML); // CONVERTING CONVERTED XML BACK TO MAP

        System.out.println("Converted Map: " + convertedMap);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
}

Output:

Map: {ROOT={name=chris, innerMap={b=B, c=C, a=A}, island=faranga}}

 -------- Map Detected -------- 
 -------- XML created Successfully -------- 
Converted XML: <ROOT><name>chris</name><innerMap><b>B</b><c>C</c><a>A</a></innerMap><island>faranga</island></ROOT>

 -------- XML Detected -------- 
 -------- Map created Successfully -------- 
Converted Map: {ROOT={name=chris, innerMap={b=B, c=C, a=A}, island=faranga}}

How can I declare a Boolean parameter in SQL statement?

The same way you declare any other variable, just use the bit type:

DECLARE @MyVar bit
Set @MyVar = 1  /* True */
Set @MyVar = 0  /* False */

SELECT * FROM [MyTable] WHERE MyBitColumn = @MyVar

c# open a new form then close the current form?

//if Form1 is old form and Form2 is the current form which we want to open, then
{
Form2 f2 = new Form1();

this.Hide();// To hide old form i.e Form1
f2.Show();
}

Difference between static and shared libraries?

On top of all the other answers, one thing not mentionned yet is decoupling :

Let me speak about a real world production code,that I have been dealing with :

A very big software, made of >300 projects (with visual studio), mostly build as static lib and finally all link together in one huge executable , you end up with the following problems :

-Link time is extremely long. You might end up by more than 15min of link, for let's say 10s of compilation time -Some tools are on their knee with such a big executable , like memory check tools that must instrument the code. You might fall into reaching limits that had been seen as fools.

More problematic is the decoupling of your software : on this real world example, headers files of every project were reacheable from any others projects. As a consequence it was extremely easy for one developer to add dependencies; it was just about including the header, because link at the end will allwaws find symbols. It ends up by horrible cycling dependencies and complete mess.

With shared library, it's a bit of extra work because developer must edit the project build system to add the dependent library. I observed that shared library code tends to offer a cleaner code API.

Hiding an Excel worksheet with VBA

I would like to answer your question, as there are various methods - here I’ll talk about the code that is widely used.

So, for hiding the sheet:

Sub try()
    Worksheets("Sheet1").Visible = xlSheetHidden
End Sub

There are other methods also if you want to learn all Methods Click here

Why can't I have "public static const string S = "stuff"; in my Class?

A const member is considered static by the compiler, as well as implying constant value semantics, which means references to the constant might be compiled into the using code as the value of the constant member, instead of a reference to the member.

In other words, a const member containing the value 10, might get compiled into code that uses it as the number 10, instead of a reference to the const member.

This is different from a static readonly field, which will always be compiled as a reference to the field.

Note, this is pre-JIT. When the JIT'ter comes into play, it might compile both these into the target code as values.

How to append the output to a file?

Yeah.

command >> file to redirect just stdout of command.

command >> file 2>&1 to redirect stdout and stderr to the file (works in bash, zsh)

And if you need to use sudo, remember that just

sudo command >> /file/requiring/sudo/privileges does not work, as privilege elevation applies to command but not shell redirection part. However, simply using tee solves the problem:

command | sudo tee -a /file/requiring/sudo/privileges

Rounding up to next power of 2

I'm trying to get nearest lower power of 2 and made this function. May it help you.Just multiplied nearest lower number times 2 to get nearest upper power of 2

int nearest_upper_power(int number){
    int temp=number;
    while((number&(number-1))!=0){
        temp<<=1;
        number&=temp;
    }
    //Here number is closest lower power 
    number*=2;
    return number;
}

How do you post data with a link

If you want to pass the data using POST instead of GET, you can do it using a combination of PHP and JavaScript, like this:

function formSubmit(house_number)
{
  document.forms[0].house_number.value = house_number;
  document.forms[0].submit();
}

Then in PHP you loop through the house-numbers, and create links to the JavaScript function, like this:

<form action="house.php" method="POST">
<input type="hidden" name="house_number" value="-1">

<?php
foreach ($houses as $id => name)
{
    echo "<a href=\"javascript:formSubmit($id);\">$name</a>\n";
}
?>
</form>

That way you just have one form whose hidden variable(s) get modified according to which link you click on. Then JavasScript submits the form.

PHP Remove elements from associative array

  ...

  $array = array(
      1 => 'Awaiting for Confirmation', 
      2 => 'Asssigned', 
      3 => 'In Progress', 
      4 => 'Completed', 
      5 => 'Mark As Spam', 
  );



  return array_values($array);
  ...

Google Chrome display JSON AJAX response as tree and not as a plain text

In order for it to display the JSON message properly it has to have the "application/json" mime type and to be correctly structured.

You can check the structure here

Left Join With Where Clause

For this problem, as for many others involving non-trivial left joins such as left-joining on inner-joined tables, I find it convenient and somewhat more readable to split the query with a with clause. In your example,

with settings_for_char as (
  select setting_id, value from character_settings where character_id = 1
)
select
  settings.*,
  settings_for_char.value
from
  settings
  left join settings_for_char on settings_for_char.setting_id = settings.id;

Resizing an iframe based on content

When you want to zoom out a web page to fit it into the iframe size:

  1. You should resize the iframe to fit it with the content
  2. Then you should zoom out the whole iframe with the loaded web page content

Here is an example:

<div id="wrap">
   <IFRAME ID="frame" name="Main" src ="http://www.google.com" />
</div>

<style type="text/css">
    #wrap { width: 130px; height: 130px; padding: 0; overflow: hidden; }
    #frame { width: 900px; height: 600px; border: 1px solid black; }
    #frame { zoom:0.15; -moz-transform:scale(0.15);-moz-transform-origin: 0 0; }
</style>

Handle spring security authentication exceptions with @ExceptionHandler

Taking answers from @Nicola and @Victor Wing and adding a more standardized way:

import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UnauthorizedErrorAuthenticationEntryPoint implements AuthenticationEntryPoint, InitializingBean {

    private HttpMessageConverter messageConverter;

    @SuppressWarnings("unchecked")
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        MyGenericError error = new MyGenericError();
        error.setDescription(exception.getMessage());

        ServerHttpResponse outputMessage = new ServletServerHttpResponse(response);
        outputMessage.setStatusCode(HttpStatus.UNAUTHORIZED);

        messageConverter.write(error, null, outputMessage);
    }

    public void setMessageConverter(HttpMessageConverter messageConverter) {
        this.messageConverter = messageConverter;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

        if (messageConverter == null) {
            throw new IllegalArgumentException("Property 'messageConverter' is required");
        }
    }

}

Now, you can inject configured Jackson, Jaxb or whatever you use to convert response bodies on your MVC annotation or XML based configuration with its serializers, deserializers and so on.

Mysql: Select all data between two dates

Do you have a table that has all dates? If not, you might want to consider implementing a calendar table and left joining your data onto the calendar table.

Put content in HttpResponseMessage object?

You can create your own specialised content types. For example one for Json content and one for Xml content (then just assign them to the HttpResponseMessage.Content):

public class JsonContent : StringContent
{
    public JsonContent(string content)
        : this(content, Encoding.UTF8)
    {
    }

    public JsonContent(string content, Encoding encoding)
        : base(content, encoding, "application/json")
    {
    }
}

public class XmlContent : StringContent
{
    public XmlContent(string content) 
        : this(content, Encoding.UTF8)
    {
    }

    public XmlContent(string content, Encoding encoding)
        : base(content, encoding, "application/xml")
    {
    }
}

Python: Get the first character of the first string in a list?

Get the first character of a bare python string:

>>> mystring = "hello"
>>> print(mystring[0])
h
>>> print(mystring[:1])
h
>>> print(mystring[3])
l
>>> print(mystring[-1])
o
>>> print(mystring[2:3])
l
>>> print(mystring[2:4])
ll

Get the first character from a string in the first position of a python list:

>>> myarray = []
>>> myarray.append("blah")
>>> myarray[0][:1]
'b'
>>> myarray[0][-1]
'h'
>>> myarray[0][1:3]
'la'

Many people get tripped up here because they are mixing up operators of Python list objects and operators of Numpy ndarray objects:

Numpy operations are very different than python list operations.

Wrap your head around the two conflicting worlds of Python's "list slicing, indexing, subsetting" and then Numpy's "masking, slicing, subsetting, indexing, then numpy's enhanced fancy indexing".

These two videos cleared things up for me:

"Losing your Loops, Fast Numerical Computing with NumPy" by PyCon 2015: https://youtu.be/EEUXKG97YRw?t=22m22s

"NumPy Beginner | SciPy 2016 Tutorial" by Alexandre Chabot LeClerc: https://youtu.be/gtejJ3RCddE?t=1h24m54s

What's the difference between all the Selection Segues?

The document has moved here it seems: https://help.apple.com/xcode/mac/8.0/#/dev564169bb1

Can't copy the icons here, but here are the descriptions:

  • Show: Present the content in the detail or master area depending on the content of the screen.

    If the app is displaying a master and detail view, the content is pushed onto the detail area. If the app is only displaying the master or the detail, the content is pushed on top of the current view controller stack.

  • Show Detail: Present the content in the detail area.

    If the app is displaying a master and detail view, the new content replaces the current detail. If the app is only displaying the master or the detail, the content replaces the top of the current view controller stack.

  • Present Modally: Present the content modally.

  • Present as Popover: Present the content as a popover anchored to an existing view.

  • Custom: Create your own behaviors by using a custom segue.

How is AngularJS different from jQuery

I want to add something regarding AngularJS difference with jQuery from a developer's perspective.

In AngularJS you have to have a very structured view and approach on what you want to accomplish. It is scarcely following a linear fashion to complete a task, but rather, the exchanges between various objects take care of the requests and actions, which, then, is necessary as angular is an MVC-Based framework. It also requires an at least general blueprint of the finalized application, since coding depends much on how you want the interactions to be completed.

jQuery is like a free poetry, you write lines and keep some relations and momentum appropriate for your task to be accomplished.

Though, in Angular JS, you should follow some rules as well as keeping the momentum and relations proper, maybe it is more like classical Spencerian sonnet (a famous classical poet) whose poem is structural and tied to many rules.

Compared against AngularJS, jQuery is more like a collection of codes and functions (which is, as already mentioned, great for DOM manipulation and fast-effect achievement), while AngularJS is a real framework which gives the developer the ability to build an enterprise web-application with a lot of data-binding and exchange within a superbly organized-routing and management.

Furthermore, AngularJS has no dependency on jQuery to complete its task. It has two very superb features which are not found in jQuery in any sense:

1- Angular JS teaches you how to CODE and accomplish a goal, not just accomplish a goal by any means. Worth to mention that AngularJS fully utilizes the core and heart of Javascripts and paves the way for you to incorporate in your app, the techniques such as DI (dependency-injection). To work with angularJS you should (or must) learn more elevated techniques of coding with Javascript.

2- Angular JS is fully independent to handle directives and structure your app; you might then simply claim that jQuery can do the same (independence), but, indeed, AngularJS, as several times mentioned within the above lines, has independence in the most excellent possible structurally MVC-Based way.

A last note is that, there is no war of Names, since it is far disturbing to be biased, or subjective. jQuery's magnitude and greatness has been proved, but their usages and limitations( of any framework or software) are the concerns of the discussion and similar debates around.

Update:

Using AngularJS is decisive as it is expensive in terms of implementation, but founds a strong base for future expansion, transformation and maintenance of the application. AngularJS is for the New World of Web. It is targeted toward building applications which are characterized by their least resource consumption (loading only necessary resources from the server), fast response time and high degree of maintainability and extendability wrapped around a structured system.

How do I escape a single quote in SQL Server?

Also another thing to be careful of is whether or not it is really stored as a classic ASCII ' (ASCII 27) or Unicode 2019 (which looks similar, but not the same).

This isn't a big deal on inserts, but it can mean the world on selects and updates.
If it's the unicode value then escaping the ' in a WHERE clause (e.g where blah = 'Workers''s Comp') will return like the value you are searching for isn't there if the ' in "Worker's Comp" is actually the unicode value.

If your client application supports free-key, as well as copy and paste based input, it could be Unicode in some rows, and ASCII in others!

A simple way to confirm this is by doing some kind of open ended query that will bring back the value you are searching for, and then copy and paste that into notepad++ or some other unicode supporting editor.

The differing appearance between the ascii value and the unicode one should be obvious to the eyes, but if you lean towards the anal, it will show up as 27 (ascii) or 92 (unicode) in a hex editor.

How to parse SOAP XML?

First, we need to filter the XML so as to parse that change objects become array

//catch xml
$xmlElement = file_get_contents ('php://input');
//change become array
$Data = (array)simplexml_load_string($xmlElement);
//and see
print_r($Data);

How to pass value from <option><select> to form action

instead of trying to catch both POST and GET responses - you can have everything you want in the POST.

Your code:

<form method="POST" action="index.php?action=contact_agent&agent_id=">
  <select>
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
</form>

can easily become:

<form method="POST" action="index.php">
  <input type="hidden" name="action" value="contact_agent">
  <select name="agent_id">
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
  <button type="submit">Submit POST Data</button>
</form>

then in index.php - these values will be populated

$_POST['action'] // "contact_agent"
$_POST['agent_id'] // 1, 2 or 3 based on selection in form... 

Chrome Fullscreen API

The following test works in Chrome 16 (dev branch) on X86 and Chrome 15 on Mac OSX Lion

http://html5-demos.appspot.com/static/fullscreen.html

How can I tail a log file in Python?

All the answers that use tail -f are not pythonic.

Here is the pythonic way: ( using no external tool or library)

def follow(thefile):
     while True:
        line = thefile.readline()
        if not line or not line.endswith('\n'):
            time.sleep(0.1)
            continue
        yield line



if __name__ == '__main__':
    logfile = open("run/foo/access-log","r")
    loglines = follow(logfile)
    for line in loglines:
        print(line, end='')

PHP: get the value of TEXTBOX then pass it to a VARIABLE

Inside testing2.php you should print the $_POST array which contains all the data from the post. Also, $_POST['name'] should be available. For more info check $_POST on php.net.

How can I test an AngularJS service from the console?

First of all, a modified version of your service.

a )

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

app.factory('ExampleService',function(){
    return {
        f1 : function(world){
            return 'Hello' + world;
        }
    };
});

This returns an object, nothing to new here.

Now the way to get this from the console is

b )

var $inj = angular.injector(['app']);
var serv = $inj.get('ExampleService');
serv.f1("World");

c )

One of the things you were doing there earlier was to assume that the app.factory returns you the function itself or a new'ed version of it. Which is not the case. In order to get a constructor you would either have to do

app.factory('ExampleService',function(){
        return function(){
            this.f1 = function(world){
                return 'Hello' + world;
            }
        };
    });

This returns an ExampleService constructor which you will next have to do a 'new' on.

Or alternatively,

app.service('ExampleService',function(){
            this.f1 = function(world){
                return 'Hello' + world;
            };
    });

This returns new ExampleService() on injection.

How to generate keyboard events?

user648852's idea at least for me works great for OS X, here is the code to do it:

#!/usr/bin/env python

import time
from Quartz.CoreGraphics import CGEventCreateKeyboardEvent
from Quartz.CoreGraphics import CGEventPost

# Python releases things automatically, using CFRelease will result in a scary error
#from Quartz.CoreGraphics import CFRelease

from Quartz.CoreGraphics import kCGHIDEventTap

# From http://stackoverflow.com/questions/281133/controlling-the-mouse-from-python-in-os-x
# and from https://developer.apple.com/library/mac/documentation/Carbon/Reference/QuartzEventServicesRef/index.html#//apple_ref/c/func/CGEventCreateKeyboardEvent


def KeyDown(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
        time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
        time.sleep(0.0001)

def KeyUp(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
    time.sleep(0.0001)

def KeyPress(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
        time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
    time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
        time.sleep(0.0001)



# From http://stackoverflow.com/questions/3202629/where-can-i-find-a-list-of-mac-virtual-key-codes

def toKeyCode(c):
    shiftKey = False
    # Letter
    if c.isalpha():
        if not c.islower():
            shiftKey = True
            c = c.lower()

    if c in shiftChars:
        shiftKey = True
        c = shiftChars[c]
    if c in keyCodeMap:
        keyCode = keyCodeMap[c]
    else:
        keyCode = ord(c)
    return keyCode, shiftKey

shiftChars = {
    '~': '`',
    '!': '1',
    '@': '2',
    '#': '3',
    '$': '4',
    '%': '5',
    '^': '6',
    '&': '7',
    '*': '8',
    '(': '9',
    ')': '0',
    '_': '-',
    '+': '=',
    '{': '[',
    '}': ']',
    '|': '\\',
    ':': ';',
    '"': '\'',
    '<': ',',
    '>': '.',
    '?': '/'
}


keyCodeMap = {
    'a'                 : 0x00,
    's'                 : 0x01,
    'd'                 : 0x02,
    'f'                 : 0x03,
    'h'                 : 0x04,
    'g'                 : 0x05,
    'z'                 : 0x06,
    'x'                 : 0x07,
    'c'                 : 0x08,
    'v'                 : 0x09,
    'b'                 : 0x0B,
    'q'                 : 0x0C,
    'w'                 : 0x0D,
    'e'                 : 0x0E,
    'r'                 : 0x0F,
    'y'                 : 0x10,
    't'                 : 0x11,
    '1'                 : 0x12,
    '2'                 : 0x13,
    '3'                 : 0x14,
    '4'                 : 0x15,
    '6'                 : 0x16,
    '5'                 : 0x17,
    '='                 : 0x18,
    '9'                 : 0x19,
    '7'                 : 0x1A,
    '-'                 : 0x1B,
    '8'                 : 0x1C,
    '0'                 : 0x1D,
    ']'                 : 0x1E,
    'o'                 : 0x1F,
    'u'                 : 0x20,
    '['                 : 0x21,
    'i'                 : 0x22,
    'p'                 : 0x23,
    'l'                 : 0x25,
    'j'                 : 0x26,
    '\''                : 0x27,
    'k'                 : 0x28,
    ';'                 : 0x29,
    '\\'                : 0x2A,
    ','                 : 0x2B,
    '/'                 : 0x2C,
    'n'                 : 0x2D,
    'm'                 : 0x2E,
    '.'                 : 0x2F,
    '`'                 : 0x32,
    'k.'                : 0x41,
    'k*'                : 0x43,
    'k+'                : 0x45,
    'kclear'            : 0x47,
    'k/'                : 0x4B,
    'k\n'               : 0x4C,
    'k-'                : 0x4E,
    'k='                : 0x51,
    'k0'                : 0x52,
    'k1'                : 0x53,
    'k2'                : 0x54,
    'k3'                : 0x55,
    'k4'                : 0x56,
    'k5'                : 0x57,
    'k6'                : 0x58,
    'k7'                : 0x59,
    'k8'                : 0x5B,
    'k9'                : 0x5C,

    # keycodes for keys that are independent of keyboard layout
    '\n'                : 0x24,
    '\t'                : 0x30,
    ' '                 : 0x31,
    'del'               : 0x33,
    'delete'            : 0x33,
    'esc'               : 0x35,
    'escape'            : 0x35,
    'cmd'               : 0x37,
    'command'           : 0x37,
    'shift'             : 0x38,
    'caps lock'         : 0x39,
    'option'            : 0x3A,
    'ctrl'              : 0x3B,
    'control'           : 0x3B,
    'right shift'       : 0x3C,
    'rshift'            : 0x3C,
    'right option'      : 0x3D,
    'roption'           : 0x3D,
    'right control'     : 0x3E,
    'rcontrol'          : 0x3E,
    'fun'               : 0x3F,
    'function'          : 0x3F,
    'f17'               : 0x40,
    'volume up'         : 0x48,
    'volume down'       : 0x49,
    'mute'              : 0x4A,
    'f18'               : 0x4F,
    'f19'               : 0x50,
    'f20'               : 0x5A,
    'f5'                : 0x60,
    'f6'                : 0x61,
    'f7'                : 0x62,
    'f3'                : 0x63,
    'f8'                : 0x64,
    'f9'                : 0x65,
    'f11'               : 0x67,
    'f13'               : 0x69,
    'f16'               : 0x6A,
    'f14'               : 0x6B,
    'f10'               : 0x6D,
    'f12'               : 0x6F,
    'f15'               : 0x71,
    'help'              : 0x72,
    'home'              : 0x73,
    'pgup'              : 0x74,
    'page up'           : 0x74,
    'forward delete'    : 0x75,
    'f4'                : 0x76,
    'end'               : 0x77,
    'f2'                : 0x78,
    'page down'         : 0x79,
    'pgdn'              : 0x79,
    'f1'                : 0x7A,
    'left'              : 0x7B,
    'right'             : 0x7C,
    'down'              : 0x7D,
    'up'                : 0x7E
}

How to listen for a WebView finishing loading a URL?

@ian this is not 100% accurate. If you have several iframes in a page you will have multiple onPageFinished (and onPageStarted). And if you have several redirects it may also fail. This approach solves (almost) all the problems:

boolean loadingFinished = true;
boolean redirect = false;

mWebView.setWebViewClient(new WebViewClient() {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
        if (!loadingFinished) {
            redirect = true;
        }

        loadingFinished = false;
        webView.loadUrl(urlNewString);
        return true;
    }

    @Override
    public void onPageStarted(WebView view, String url) {
        loadingFinished = false;
        //SHOW LOADING IF IT ISNT ALREADY VISIBLE  
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        if (!redirect) {
           loadingFinished = true;
            //HIDE LOADING IT HAS FINISHED
        } else {
            redirect = false; 
        }
    }
});

UPDATE:

According to the documentation: onPageStarted will NOT be called when the contents of an embedded frame changes, i.e. clicking a link whose target is an iframe.

I found a specific case like that on Twitter where only a pageFinished was called and messed the logic a bit. To solve that I added a scheduled task to remove loading after X seconds. This is not needed in all the other cases.

UPDATE 2:

Now with current Android WebView implementation:

boolean loadingFinished = true;
boolean redirect = false;

    mWebView.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(
                WebView view, WebResourceRequest request) {
            if (!loadingFinished) {
               redirect = true;
            }

            loadingFinished = false;
            webView.loadUrl(request.getUrl().toString());
            return true;
        }

        @Override
        public void onPageStarted(
                WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            loadingFinished = false;
            //SHOW LOADING IF IT ISNT ALREADY VISIBLE  
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (!redirect) {
               loadingFinished = true;
                //HIDE LOADING IT HAS FINISHED
            } else {
                redirect = false; 
            }
        }
    });

remove kernel on jupyter notebook

If you are doing this for virtualenv, the kernels in inactive environments might not be shown with jupyter kernelspec list, as suggested above. You can delete it from directory:

~/.local/share/jupyter/kernels/

Padding characters in printf

I think this is the simplest solution. Pure shell builtins, no inline math. It borrows from previous answers.

Just substrings and the ${#...} meta-variable.

A="[>---------------------<]";

# Strip excess padding from the right
#

B="A very long header"; echo "${A:0:-${#B}} $B"
B="shrt hdr"          ; echo "${A:0:-${#B}} $B"

Produces

[>----- A very long header
[>--------------- shrt hdr


# Strip excess padding from the left
#

B="A very long header"; echo "${A:${#B}} $B"
B="shrt hdr"          ; echo "${A:${#B}} $B"

Produces

-----<] A very long header
---------------<] shrt hdr

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

just go to data directory in my case path is "wamp\bin\mysql\mysql5.6.17\data" here you will see all databases folder just delete this your database folder the db will automatically drooped :)

concat scope variables into string in angular directive expression

I've created a working CodePen example demonstrating how to do this.

Relevant HTML:

<section ng-app="app" ng-controller="MainCtrl">
  <a href="#" ng-click="doSomething('#/path/{{obj.val1}}/{{obj.val2}}')">Click Me</a><br>
  debug: {{debug.val}}
</section>

Relevant javascript:

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

app.controller('MainCtrl', function($scope) {
  $scope.obj = {
    val1: 'hello',
    val2: 'world'
  };

  $scope.debug = {
    val: ''
  };

  $scope.doSomething = function(input) {
    $scope.debug.val = input;
  };
});

Trigger event on body load complete js/jquery

Isn't

  $(document).ready(function() {

  });

what you are looking for?

How to configure PHP to send e-mail?

configure your php.ini like this

SMTP = smtp.gmail.com

[mail function]
; XAMPP: Comment out this if you want to work with an SMTP Server like Mercury

; SMTP = smtp.gmail.com

; smtp_port = 465

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = postmaster@localhost

Get value from hashmap based on key to JSTL

could you please try below code

<c:forEach var="hash" items="${map['key']}">
        <option><c:out value="${hash}"/></option>
  </c:forEach>

How to secure an ASP.NET Web API

If you want to secure your API in a server to server fashion (no redirection to website for 2 legged authentication). You can look at OAuth2 Client Credentials Grant protocol.

https://dev.twitter.com/docs/auth/application-only-auth

I have developed a library that can help you easily add this kind of support to your WebAPI. You can install it as a NuGet package:

https://nuget.org/packages/OAuth2ClientCredentialsGrant/1.0.0.0

The library targets .NET Framework 4.5.

Once you add the package to your project, it will create a readme file in the root of your project. You can look at that readme file to see how to configure/use this package.

Cheers!

Default SQL Server Port

For Http Request Default Port number is 80

For Https Default Port Number is 443

For Sql Server Default Port Number is 1433

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

This method is deprecated now from now starting with Android Q.

Try This will really help.

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {// if build version is less than Q try the old traditional method
                    if (!wifiManager.isWifiEnabled()) {
                        wifiManager.setWifiEnabled(true);
                        btnOnOff.setText("Wifi ONN");
                    } else {
                        wifiManager.setWifiEnabled(false);
                        btnOnOff.setText("Wifi OFF");
                    }
                } else {// if it is Android Q and above go for the newer way    NOTE: You can also use this code for less than android Q also
                    Intent panelIntent = new Intent(Settings.Panel.ACTION_WIFI);
                    startActivityForResult(panelIntent, 1);
                }

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

User order by with desc order:

select * from t
order by id desc
limit 1

R : how to simply repeat a command?

It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.

If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate and colMeans, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.

However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for loop.

> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 > 

So in your case, if you just wanted to print the mean of your Tandem object 5 times:

for (ii in 1:5) {     Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL)     TandemMean <- mean(Tandem)     print(TandemMean) } 

As mentioned above, replicate is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.

set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) {     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) }  tandem[1] tandem[100] tandem[20:25] 

...creates this output:

> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { +     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } >  > tandem[1] [[1]] [1] 1.511923  > tandem[100] [[1]] [1] 1.496777  > tandem[20:25] [[1]] [1] 1.500669  [[2]] [1] 1.487552  [[3]] [1] 1.503409  [[4]] [1] 1.501362  [[5]] [1] 1.499728  [[6]] [1] 1.492798  >  

Only using @JsonIgnore during serialization, but not deserialization

In my case, I have Jackson automatically (de)serializing objects that I return from a Spring MVC controller (I am using @RestController with Spring 4.1.6). I had to use com.fasterxml.jackson.annotation.JsonIgnore instead of org.codehaus.jackson.annotate.JsonIgnore, as otherwise, it simply did nothing.

Copy folder structure (without files) from one location to another

You could do something like:

find . -type d > dirs.txt

to create the list of directories, then

xargs mkdir -p < dirs.txt

to create the directories on the destination.

How to iterate over a JSONObject?

org.json.JSONObject now has a keySet() method which returns a Set<String> and can easily be looped through with a for-each.

for(String key : jsonObject.keySet())

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

I was facing the same issue while executing the command mvn -version; however, I checked I had also set the mvn options in the environment variables setting, which gave me some Heap memory issue on the command prompt. So, I removed the maven options that I had set and then it worked fine for me.

remove first element from array and return the array minus the first element

This can be done in one line with lodash _.tail:

_x000D_
_x000D_
var arr = ["item 1", "item 2", "item 3", "item 4"];_x000D_
console.log(_.tail(arr));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Determine a string's encoding in C#

Another option, very late in coming, sorry:

http://www.architectshack.com/TextFileEncodingDetector.ashx

This small C#-only class uses BOMS if present, tries to auto-detect possible unicode encodings otherwise, and falls back if none of the Unicode encodings is possible or likely.

It sounds like UTF8Checker referenced above does something similar, but I think this is slightly broader in scope - instead of just UTF8, it also checks for other possible Unicode encodings (UTF-16 LE or BE) that might be missing a BOM.

Hope this helps someone!

c# how to add byte to byte array

Simple, just use the code below, as I do:

        public void AppendSpecifiedBytes(ref byte[] dst, byte[] src)
    {
        // Get the starting length of dst
        int i = dst.Length;
        // Resize dst so it can hold the bytes in src
        Array.Resize(ref dst, dst.Length + src.Length);
        // For each element in src
        for (int j = 0; j < src.Length; j++)
        {
            // Add the element to dst
            dst[i] = src[j];
            // Increment dst index
            i++;
        }
    }

    // Appends src byte to the dst array
    public void AppendSpecifiedByte(ref byte[] dst, byte src)
    {
        // Resize dst so that it can hold src
        Array.Resize(ref dst, dst.Length + 1);
        // Add src to dst
        dst[dst.Length - 1] = src;
    }

How do I POST XML data with curl

I prefer the following command-line options:

cat req.xml | curl -X POST -H 'Content-type: text/xml' -d @- http://www.example.com

or

curl -X POST -H 'Content-type: text/xml' -d @req.xml http://www.example.com

or

curl -X POST -H 'Content-type: text/xml'  -d '<XML>data</XML>' http://www.example.com 

What is the best way to delete a component with CLI

I wrote a bash script that should automate the process written by Yakov Fain below. It can be called like ./removeComponent myComponentName This has only been tested with Angular 6

#!/bin/bash
if [ "$#" -ne 1 ]; then
    echo "Input a component to delete"
    exit 1
fi

# finds folder with component name and deletes
find . -type d -name $1 | xargs rm -rf

# removes lines referencing the component from app.module.ts
grep -v $1 app.module.ts > temp
mv temp app.module.ts

componentName=$1
componentName+="Component"

grep -v -i $componentName app.module.ts > temp
mv temp app.module.ts

Tools to generate database tables diagram with Postgresql?

PostgreSQL Autodoc has worked well for me. It is a simple command line tool. From the web page:

This is a utility which will run through PostgreSQL system tables and returns HTML, Dot, Dia and DocBook XML which describes the database.

SQL Server 2008 - Case / If statements in SELECT Clause

CASE is the answer, but you will need to have a separate case statement for each column you want returned. As long as the WHERE clause is the same, there won't be much benefit separating it out into multiple queries.

Example:

SELECT
    CASE @var
        WHEN 'xyz' THEN col1
        WHEN 'zyx' THEN col2
        ELSE col7
    END,
    CASE @var
        WHEN 'xyz' THEN col2
        WHEN 'zyx' THEN col3
        ELSE col8
    END
FROM Table
...

How to implement a simple scenario the OO way

You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.

No Such Element Exception?

I had run into the same issue while I was dealing with large dataset. One thing I've noticed was the NoSuchElementException is thrown when the Scanner reaches the endOfFile, where it is not going to affect our data.

Here, I've placed my code in try block and catch block handles the exception. You can also leave it empty, if you don't want to perform any task.

For the above question, because you are using file.next() both in the condition and in the while loop you can handle the exception as

while(!file.next().equals(treasure)){
    try{
        file.next(); //stack trace error here
       }catch(NoSuchElementException e) {  }
}

This worked perfectly for me, if there are any corner cases for my approach, do let me know through comments.

From io.Reader to string in Go

I like the bytes.Buffer struct. I see it has ReadFrom and String methods. I've used it with a []byte but not an io.Reader.

Jenkins, specifying JAVA_HOME

Upgrading from Ubuntu 10.0.4 to 12.0.4 we got wrong footed. We had a JDK installation configured (auto-configured?) pointing to /usr/lib/jvm/java-6-openjdk this no longer contained a JDK, Changing to /usr/lib/jvm/default-java fixed, and should make for a seamless java-7 upgrade.

So in answer to the question: do not specify JAVA_HOME on Ubuntu.

Redirect on Ajax Jquery Call

For ExpressJs router:

router.post('/login', async(req, res) => {
    return res.send({redirect: '/yoururl'});
})

Client-side:

    success: function (response) {
        if (response.redirect) {
            window.location = response.redirect
        }
    },

Can't access Eclipse marketplace

Here's the solution,

If you are a constant proxy changer like me for various reasons (university, home , workplace and so on..) you are mostly likely to get this error due to improper configuration of connection settings in the eclipse IDE. all you have to do it play around with the current settings and get it to working state. Here's how,,

1. GO TO

Window-> Preferences -> General -> Network Connection.

2. Change the Settings

Active Provider-> Manual-> and check---> HTTP, HTTPS and SOCKS

If your active provider is already set to Manual, try restoring the default (native)


That's all, restart Eclipse and you are good to go!


When should I use git pull --rebase?

I think it boils down to a personal preference.

Do you want to hide your silly mistakes before pushing your changes? If so, git pull --rebase is perfect. It allows you to later squash your commits to a few (or one) commits. If you have merges in your (unpushed) history, it is not so easy to do a git rebase later one.

I personally don't mind publishing all my silly mistakes, so I tend to merge instead of rebase.

How do I see if Wi-Fi is connected on Android?

ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
boolean is3g = manager.getNetworkInfo(
                  ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
boolean isWifi = manager.getNetworkInfo(
                    ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();

Log.v("", is3g + " ConnectivityManager Test " + isWifi);
if (!is3g && !isWifi) {
    Toast.makeText(
        getApplicationContext(),
        "Please make sure, your network connection is ON ",
        Toast.LENGTH_LONG).show();
}
else {
    // Put your function() to go further;
}

What's the difference between jquery.js and jquery.min.js?

jquery.js: when you have to dive into jquery's source code jquery.min.js: compressed version for saving bandwidth

There is one more option for saving more bandwidth then the compressed version which is using something like Google CDN provided: http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js

How do I use itertools.groupby()?

One useful example that I came across may be helpful:

from itertools import groupby

#user input

myinput = input()

#creating empty list to store output

myoutput = []

for k,g in groupby(myinput):

    myoutput.append((len(list(g)),int(k)))

print(*myoutput)

Sample input: 14445221

Sample output: (1,1) (3,4) (1,5) (2,2) (1,1)

Class method differences in Python: bound, unbound and static

>>> class Class(object):
...     def __init__(self):
...         self.i = 0
...     def instance_method(self):
...         self.i += 1
...         print self.i
...     c = 0
...     @classmethod
...     def class_method(cls):
...         cls.c += 1
...         print cls.c
...     @staticmethod
...     def static_method(s):
...         s += 1
...         print s
... 
>>> a = Class()
>>> a.class_method()
1
>>> Class.class_method()    # The class shares this value across instances
2
>>> a.instance_method()
1
>>> Class.instance_method() # The class cannot use an instance method
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method instance_method() must be called with Class instance as first argument (got nothing instead)
>>> Class.instance_method(a)
2
>>> b = 0
>>> a.static_method(b)
1
>>> a.static_method(a.c) # Static method does not have direct access to 
>>>                      # class or instance properties.
3
>>> Class.c        # a.c above was passed by value and not by reference.
2
>>> a.c
2
>>> a.c = 5        # The connection between the instance
>>> Class.c        # and its class is weak as seen here.
2
>>> Class.class_method()
3
>>> a.c
5