Programs & Examples On #Apk

An .apk file extension denotes an Android Package (APK) file. This file format, a variant of the JAR format, is used for distributing and installing bundled components onto the Android operating system.

How to run .APK file on emulator

Step-by-Step way to do this:

  1. Install Android SDK
  2. Start the emulator by going to $SDK_root/emulator.exe
  3. Go to command prompt and go to the directory $SDK_root/platform-tools (or else add the path to windows environment)
  4. Type in the command adb install
  5. Bingo. Your app should be up and running on the emulator

How to check programmatically if an application is installed or not in Android?

Try with this:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Add respective layout
        setContentView(R.layout.main_activity);

        // Use package name which we want to check
        boolean isAppInstalled = appInstalledOrNot("com.check.application");  

        if(isAppInstalled) {
            //This intent will help you to launch if the package is already installed
            Intent LaunchIntent = getPackageManager()
                .getLaunchIntentForPackage("com.check.application");
            startActivity(LaunchIntent);

            Log.i("Application is already installed.");       
        } else {
            // Do whatever we want to do if application not installed
            // For example, Redirect to play store

            Log.i("Application is not currently installed.");
        }
    }

    private boolean appInstalledOrNot(String uri) {
        PackageManager pm = getPackageManager();
        try {
            pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
        }

        return false;
    }

}

Android Studio: Application Installation Failed

If you do all of things above and still get stuck, just try reopening your Android Studio.

How do I get an apk file from an Android device?

Use adb. With adb pull you can copy files from your device to your system, when the device is attached with USB.

Of course you also need the right permissions to access the directory your file is in. If not, you will need to root the device first.


If you find that many of the APKs are named "base.apk" you can also use this one line command to pull all the APKs off a phone you can access while renaming any "base.apk" names to the package name. This also fixes the directory not found issue for APK paths with seemingly random characters after the name:

for i in $(adb shell pm list packages | awk -F':' '{print $2}'); do adb pull "$(adb shell pm path $i | awk -F':' '{print $2}')"; mv base.apk $i.apk 2&> /dev/null ;done

If you get "adb: error: failed to stat remote object" that indicates you don't have the needed permissions. I ran this on a NON-rooted Moto Z2 and was able to download ALL the APKs I did not uninstall (see below) except youtube.

adb shell pm uninstall --user 0 com.android.cellbroadcastreceiver   <--- kills presidential alert app!

(to view users run adb shell pm list users) This is a way to remove/uninstall (not from the phone as it comes back with factory reset) almost ANY app WITHOUT root INCLUDING system apps (hint the annoying update app that updates your phone line it or not can be found by grepping for "ccc")

How to build an APK file in Eclipse?

When you run your application, your phone should be detected and you should be given the option to run on your phone instead of on the emulator.

More instructions on getting your phone recognized: http://developer.android.com/guide/developing/device.html

When you want to export a signed version of the APK file (for uploading to the market or putting on a website), right-click on the project in Eclipse, choose export, and then choose "Export Android Application".

More details: http://developer.android.com/guide/publishing/app-signing.html#ExportWizard

How to sign an android apk file

I ran into this problem and was solved by checking the min sdk version in the manifest. It was set to 15 (ICS), but my phone was running 10(Gingerbread)

How do I get the APK of an installed app without root access?

  1. check the list of installed apk's (following command also list the path where it is installed and package name). adb shell pm list packages -f
  2. use adb pull /package_path/package name /path_in_pc (package path and package name one can get from above command 1.)

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

I think this represents a good answer.

APK Signature Scheme v2 verification

  1. Locate the APK Signing Block and verify that:
    1. Two size fields of APK Signing Block contain the same value.
    2. ZIP Central Directory is immediately followed by ZIP End of Central Directory record.
    3. ZIP End of Central Directory is not followed by more data.
  2. Locate the first APK Signature Scheme v2 Block inside the APK Signing Block. If the v2 Block if present, proceed to step 3. Otherwise, fall back to verifying the APK using v1 scheme.
  3. For each signer in the APK Signature Scheme v2 Block:
    1. Choose the strongest supported signature algorithm ID from signatures. The strength ordering is up to each implementation/platform version.
    2. Verify the corresponding signature from signatures against signed data using public key. (It is now safe to parse signed data.)
    3. Verify that the ordered list of signature algorithm IDs in digests and signatures is identical. (This is to prevent signature stripping/addition.)
    4. Compute the digest of APK contents using the same digest algorithm as the digest algorithm used by the signature algorithm.
    5. Verify that the computed digest is identical to the corresponding digest from digests.
    6. Verify that SubjectPublicKeyInfo of the first certificate of certificates is identical to public key.
  4. Verification succeeds if at least one signer was found and step 3 succeeded for each found signer.

Note: APK must not be verified using the v1 scheme if a failure occurs in step 3 or 4.

JAR-signed APK verification (v1 scheme)

The JAR-signed APK is a standard signed JAR, which must contain exactly the entries listed in META-INF/MANIFEST.MF and where all entries must be signed by the same set of signers. Its integrity is verified as follows:

  1. Each signer is represented by a META-INF/<signer>.SF and META-INF/<signer>.(RSA|DSA|EC) JAR entry.
  2. <signer>.(RSA|DSA|EC) is a PKCS #7 CMS ContentInfo with SignedData structure whose signature is verified over the <signer>.SF file.
  3. <signer>.SF file contains a whole-file digest of the META-INF/MANIFEST.MF and digests of each section of META-INF/MANIFEST.MF. The whole-file digest of the MANIFEST.MF is verified. If that fails, the digest of each MANIFEST.MF section is verified instead.
  4. META-INF/MANIFEST.MF contains, for each integrity-protected JAR entry, a correspondingly named section containing the digest of the entry’s uncompressed contents. All these digests are verified.
  5. APK verification fails if the APK contains JAR entries which are not listed in the MANIFEST.MF and are not part of JAR signature. The protection chain is thus <signer>.(RSA|DSA|EC) ? <signer>.SF ? MANIFEST.MF ? contents of each integrity-protected JAR entry.

unsigned APK can not be installed

Just follow these steps to transfer the apk onto the real device(with debugger key) and which is just for testing purpose. (Note: For proper distribution to the market you may need to sign your app with your keys and follow all the steps.)

  1. Install your app onto the emulator.
  2. Once it is installed goto DDMS, select the current running app under the devices window. This will then show all the files related to it under the file explorer.
  3. Under file explorer go to data->app and select your APK (which is the package name of the app).
  4. Select it and click on 'Pull a file from the device' button (the one with the save symbol).
  5. This copies the APK to your system. From there you can copy the file to your real device, install and test it.

Good luck !

Install Application programmatically on Android

Try this - Write on Manifest:

uses-permission android:name="android.permission.INSTALL_PACKAGES"
        tools:ignore="ProtectedPermissions"

Write the Code:

File sdCard = Environment.getExternalStorageDirectory();
String fileStr = sdCard.getAbsolutePath() + "/Download";// + "app-release.apk";
File file = new File(fileStr, "app-release.apk");
Intent promptInstall = new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(file),
                        "application/vnd.android.package-archive");

startActivity(promptInstall);

How to view AndroidManifest.xml from APK file?

Aapt2, included in the Android SDK build tools can do this - no third party tools needed.

$(ANDROID_SDK)/build-tools/28.0.3/aapt2 d --file AndroidManifest.xml app-foo-release.apk

Starting with build-tools v29 you have to add the command xmltree:

$(ANDROID_SDK)/build-tools/29.0.3/aapt2 d xmltree --file AndroidManifest.xml app-foo-release.apk

How to install APK from PC?

3 Ways to Install Applications On Android Without The Market

And don't forget to enable Unknown sources in your Android device Settings, before installing apk, else Android platform will not allow you to install apk directly

enter image description here

Apk location in New Android Studio

enter image description here

  1. open Event Log
  2. find line: Module 'app': locate or analyze the APK.
  3. click on locate link to open folder with apk file!

After all: "All built APKs are saved in project-name/module-name/build/outputs/apk/ Build your project LINK

Android - How to decode and decompile any APK file?

To decompile APK Use APKTool.
You can learn how APKTool works on http://www.decompileandroid.com/ or by reading the documentation.

Is it possible to run .APK/Android apps on iPad/iPhone devices?

There is another option not mentioned previously:

  • Pieceable Viewer has unfortunately stopped its service at December 31, 2012 but open-sourced its software. You need to compile your iOS application for the emulator and Pieceable's software will embed it in a webpage which hosts the application. This webpage can be used to run the iOS application. See Pieceable's for more details.

Read the package name of an Android APK

For Windows following worked for me:

:: // Initializing variables
SET adb="C:\Users\<User name>\AppData\Local\Android\Sdk\platform-tools\adb"
SET aapt="C:\Users\<User name>\AppData\Local\Android\Sdk\build-tools\22.0.0\aapt"
SET APKPath=C:\Users\<User name>\Desktop\APK\Instant_Instal\

CD %APKPath%

:: // Searching for apk file and storing it
FOR /F "delims=" %%f IN ('dir /S /B *.apk') DO SET "APKFullPath=%%f"
SET apk=%APKFullPath%

:: // Command adb install apk, run apk
%adb% install %apk%

:: // Fetching package name from apk
%aapt% dump badging %APKFullPath% | FIND "package: name=" > temp.txt
FOR /F "tokens=2 delims='" %%s IN (temp.txt) DO SET pkgName=%%s
del temp.txt

:: // Launching apk
%adb% shell monkey -p %pkgName% -c android.intent.category.LAUNCHER 1

pause

Note

Please edit the paths of adb, aapt, APKPath according to the paths of adb, aapt, and the apk location in your system.

Working:

  • Here I have added the apk in a folder on Desktop "\Desktop\APK\Instant_Instal\".
  • The command %adb% install %apk% installs the application if the device is connected.
  • This %aapt% dump badging %APKFullPath% | FIND "package: name=" > temp.txt fetches package name and a few other details like version etc. of the apk and stores in a temp.txt file in same location as that of the apk.
  • FOR /F "tokens=2 delims='" %%s IN (temp.txt) DO SET pkgName=%%sextracts the package name and assigns topkgName` variable
  • Finally %adb% shell monkey -p %pkgName% -c android.intent.category.LAUNCHER 1 launches the app.

In essence the above code installs the apk from given location in desktop "Desktop\APK\Instant_Instal\" to the device and launches the application.

Android Studio - local path doesn't exist

delete de out directory and .ide folder work for me

How to retrieve Key Alias and Key Password for signed APK in android studio(migrated from Eclipse)

I finally could figure the issue out.

To get the Key Alias: I copied the keytool.exe and my keystore file into C:\Program Files\Java\jdk1.7.0_71\bin folder. Then from command prompt I wrote: keytool -list -v -keystore <name>.keystore It will also ask for keystore password then. Then it will show you the key alias and Certificate fingerprints and other info.

Then I again tried to Generate Signed Apk for the project, I provided keystore, keystore password, key alias and provided the same password. Then it asks for master password, I tried with the same and it failed. With the reset option I reset the master password here.

Upload failed You need to use a different version code for your APK because you already have one with version code 2

if you are using phonegap / cordova applications, just edit your config.xml and add the android-versionCode and version in the widget.

<widget id="com.xxx.yyy" version="1.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0" android-versionCode="100001" version="1.0.1">

install / uninstall APKs programmatically (PackageManager vs Intents)

According to Froyo source code, the Intent.EXTRA_INSTALLER_PACKAGE_NAME extra key is queried for the installer package name in the PackageInstallerActivity.

How to Sign an Already Compiled Apk

Automated Process:

Use this tool (uses the new apksigner from Google):

https://github.com/patrickfav/uber-apk-signer

Disclaimer: Im the developer :)

Manual Process:

Step 1: Generate Keystore (only once)

You need to generate a keystore once and use it to sign your unsigned apk. Use the keytool provided by the JDK found in %JAVA_HOME%/bin/

keytool -genkey -v -keystore my.keystore -keyalg RSA -keysize 2048 -validity 10000 -alias app

Step 2 or 4: Zipalign

zipalign which is a tool provided by the Android SDK found in e.g. %ANDROID_HOME%/sdk/build-tools/24.0.2/ is a mandatory optimization step if you want to upload the apk to the Play Store.

zipalign -p 4 my.apk my-aligned.apk

Note: when using the old jarsigner you need to zipalign AFTER signing. When using the new apksigner method you do it BEFORE signing (confusing, I know). Invoking zipalign before apksigner works fine because apksigner preserves APK alignment and compression (unlike jarsigner).

You can verify the alignment with

zipalign -c 4 my-aligned.apk

Step 3: Sign & Verify

Using build-tools 24.0.2 and older

Use jarsigner which, like the keytool, comes with the JDK distribution found in %JAVA_HOME%/bin/ and use it like so:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my.keystore my-app.apk my_alias_name

and can be verified with

jarsigner -verify -verbose my_application.apk

Using build-tools 24.0.3 and newer

Android 7.0 introduces APK Signature Scheme v2, a new app-signing scheme that offers faster app install times and more protection against unauthorized alterations to APK files (See here and here for more details). Therefore, Google implemented their own apk signer called apksigner (duh!) The script file can be found in %ANDROID_HOME%/sdk/build-tools/24.0.3/ (the .jar is in the /lib subfolder). Use it like this

apksigner sign --ks my.keystore my-app.apk --ks-key-alias alias_name

and can be verified with

apksigner verify my-app.apk

The official documentation can be found here.

Application Installation Failed in Android Studio

·clean project——that's what I consider first, but not work

·disable instant run——no this option in latest version

·turn off MIUI optimization——I don't use MIUI emulator

·Build apk, gradle....——no no no

You know what? When I uninstall the app in my emulator, and run the code again, it works as immediately!

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

For the upgrade scenario specifically an alternative approach might be to have a web service that delivers the current version number and check that instead of downloading the entire apk just to check its version. It would save some bandwidth, be a little more performant (much faster to download than an apk if the whole apk isn't needed most of the time) and much simpler to implement.

In the simplest form you could have a simple text file on your server... http://some-place.com/current-app-version.txt

Inside of that text file have something like

3.1.4

and then download that file and check against the currently installed version.

Building a more advanced solution to that would be to implement a proper web service and have an api call at launch which could return some json, i.e. http://api.some-place.com/versionCheck:

{
    "current_version": "3.1.4"
}

Build and Install unsigned apk on device without the development server?

As of react-native 0.57, none of the previously provided answers will work anymore, as the directories in which gradle expects to find the bundle and the assets have changed.

Simple way without react-native bundle

The simplest way to build a debug build is without using the react-native bundle command at all, but by simply modifying your app/build.gradle file.

Inside the project.ext.react map in the app/build.gradle file, add the bundleInDebug: true entry. If you want it to not be a --dev build (no warnings and minified bundle) then you should also add the devDisabledInDebug: true entry to the same map.

With react-native bundle

If for some reason you need to or want to use the react-native bundle command to create the bundle and then the ./gradlew assembleDebug to create the APK with the bundle and the assets you have to make sure to put the bundle and the assets in the correct paths, where gradle can find them.

As of react-native 0.57 those paths are android/app/build/generated/assets/react/debug/index.android.js for the bundle

and android/app/build/generated/res/react/debug for the assets. So the full commands for manually bundling and building the APK with the bundle and assets are:

react-native bundle --dev false --platform android --entry-file index.js --bundle-output ./android/app/build/generated/assets/react/debug/index.android.bundle --assets-dest ./android/app/build/res/react/debug

and then

./gradlew assembleDebug

Bundle and assets path

Note that that paths where gradle looks for the bundle and the assets might be subject to change. To find out where those paths are, look at the react.gradle file in your node_modules/react-native directory. The lines starting with def jsBundleDir = and def resourcesDir = specify the directories where gradle looks for the bundle and the assets respectively.

Android error: Failed to install *.apk on device *: timeout

Reboot the phone.

Seriously! Completely power down and power up. That fixed it for me.

Build unsigned APK file with Android Studio

I solve it!

First off all, you should add these:

defaultConfig { 
 multiDexEnabled true
}

dependencies {
 implementation 'com.android.support:multidex:1.0.3'
}

After, you should click Build in top bar of Android Studio:

Build > Build Bundle(s) / APK(s) > Build APK(s)

Finally, you have an app-debug.apk file in:

app > build > outputs > apk > debug > app-debug.apk

Note: apk, debug, app-debug.apk files created automatically in outputs file by Android Studio.

How do you install an APK file in the Android emulator?

Just drag and drop your apk to emulator

Is it possible to decompile an Android .apk file?

Download this jadx tool https://sourceforge.net/projects/jadx/files/

Unzip it and than in lib folder run jadx-gui-0.6.1.jar file now browse your apk file. It's done. Automatically apk will decompile and save it by pressing save button. Hope it will work for you. Thanks

Session 'app': Error Installing APK

A bit late to the party, but be sure that you are trying to build a proper build variant. It sometimes happens to me that when I update AS, the build variants are totally messed up, so instead of building the "debug" variant I am actually building the "release" variant, which outputs apk to a different location (not to app/build directory, but to app directly) and I get the following error:

The APK file /path/to/file/app.apk does not exist on disk.
Error while Installing APK

To fix this just open the menu in left bottom corner, click on "Build Variants" and select the debug variant (it might have a different name, depending on how many modules/flavors or custom gradle build types you have).

How to deal with INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES without uninstall?

For what it is worth, I ran into this problem after adding a new plugin to my Cordova project. I had been having cordova do builds and install directly on the device via USB.

I fixed it by uninstalling the app from the device and on the next deploy there were no problems.

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

Today i faced same issue, unfortunately, i was having two aliases in my keystore file.enter image description here

The APK file does not exist on disk

I tried all of these things and none of them worked. I ended up having to do a couple of these things are the same time. Very frustrating that it took this much time.

The problem I had was related to running my unit tests following the upgrade to AS 3.1.

Here is what I did... 1.) Run / Edit Configurations / Select Tests.... 2.) Add options to "Gradle-aware Make" 3.) Select check box "Skip installation if ADK has not changed" on Misc tab

Good luck.

Where can I find the .apk file on my device, when I download any app and install?

All user installed apks are located in /data/app/, but you can only access this if you are rooted(afaik, you can try without root and if it doesn't work, rooting isn't hard. I suggest you search xda-developers for rooting instructions)

Use Root explorer or ES File Explorer to access /data/app/ (you have to keep going "up" until you reach the root directory /, kind of like C: in windows, before you can see the data directory(folder)). In ES file explorer you must also tick a checkbox in settings to allow going up to the root directory.

When you are in there you will see all your applications apks, though they might be named strangely. Just copy the wanted .apk and paste in the sd card, after that you can copy it to your computer and when you want to install it just open the .apk in a file manager (be sure to have install from unknown sources enabled in android settings). Even if you only want to send over bluetooth I would recommend copying it to the SD first.

PS Note that paid apps probably won't work being copied this way, since they usually check their licence online. PPS Installing an app this way may not link it with google play(you won't see it in my apps and it won't get updates).

Is there a way to get the source code from an APK file?

This is an alternative description - just in case someone got stuck with the description above. Follow the steps:

  1. download apktool.bat (or apktool for Linux) and apktool_<version>.jar from http://ibotpeaches.github.io/Apktool/install/
  2. rename the jar file from above to apktool.jar and put both files in the same folder

  3. open a dos box (cmd.exe) and change into that folder; verify that a Java Environment is installed (for Linux check the notes regarding required libraries as well)
  4. Start: apktool decode [apk file]

    Intermediate result: resource files, AndroidManifest.xml

  5. unzip APK file with an unpacker of your choice

    Intermediate result: classes.dex

  6. download and extract dex2jar-0.0.9.15.zip from http://code.google.com/p/dex2jar/downloads/detail?name=dex2jar-0.0.9.15.zip&can=2&q=
  7. drag and drop classes.dex onto dex2jar.bat (or enter <path_to>\dex2jar.bat classes.dex in a DOS box; for Linux use dex2jar.sh)

    Intermediate result: classes_dex2jar.jar

  8. unpack classes_dex2jar.jar (might be optional depending on used decompiler)
  9. decompile your class files (e.g. with JD-GUI or DJ Decompiler)

    Result: source code

Note: it is not allowed to decompile third party packages; this guide is intended to recover personal source code from an APK file only; finally, the resulting code will most likely be obfuscated

This version of the application is not configured for billing through Google Play

Contrary to many answers and comments on SO and other sites, you do NOT have to perform preliminary tests with an alpha/beta version of your product that has been downloaded from Google Play onto your test device (the alpha/beta publication process often eats up half a day). Neither do you have to load and re-load a signed release apk from your developer studio to your test device.

You CAN debug preliminary Google Play in app billing services using the debug app as loaded from your developer studio directly to your test device via ADB. If you are experiencing errors that prevent this, likely you have done something wrong in your code. Pay especially close attention to the CASE of your SKU's (product ids) and their format (for example, if you load your APK as com.mydomain.my_product_id, be sure your try to purchase it this way - providing the same case and domain). Also, pay especially close attention to your itemType - this should be either "inapp" or "subs" for managed/unmanaged in app purchases or subscriptions, respectively.

As suggested by Chirag Patel, provided you have your billing code properly established, perform all testing using the android.test.purchased Sku (product ID) during your preliminary tests. Check for this ID throughout your billing operations to pass it through signature, token and payload checks, since this data is not provided by the Google test system. Additionally, give one of your test products this ID to test its purchase, unlock/load and presentation all the way through your schema. To CLEAR the purchase, simply consume it, passing the same Sku AND a token string formatted this way - no other fields are relevant :

    "inapp:"+appContext.getAppContext().getPackageName()+":android.test.purchased";

Once you have completed this phase of testing, move to semi-live testing with your alpha/beta product. Create a Google group (essentially a mailing list), add your test users emails to it, and add/invite this group to test your device in this phase (performed at the "APK" portion of your app's Google developer listing). Purchases will be simulated but not actually charged - however to clear and re-test the purchases, Google indicates that you must refund them from your Google wallet. THIS is the only phase of testing that requires the time-consuming process of using alpha/beta loads and test users.

Install an apk file from command prompt?

You can build on the command line with ant. See this guide.

Then, you can install it by using adb on the command line.

adb install -r MyApp.apk

The -r flag is to replace the existing application.

ADB Install Fails With INSTALL_FAILED_TEST_ONLY

As mentioned in documentation:

Android Studio automatically adds this attribute when you click Run

So, to be able to install your apk with adb install <path to apk file> you need to assemble build from terminal: ./gradlew assembleDebug and install with adb. Or just run ./gradlew installDebug to build and install on the device simultaneously.

How to create a release signed apk file using Gradle?

if you don't want to see Cannot invoke method readLine() on null object. you need write in gradle.properties first.

KEYSTORE_PASS=*****
ALIAS_NAME=*****
ALIAS_PASS=*****

How to convert .pfx file to keystore with private key?

Justin(above) is accurate. However, keep in mind that depending on who you get the certificate from (intermediate CA, root CA involved or not) or how the pfx is created/exported, sometimes they could be missing the certificate chain. After Import, You would have a certificate of PrivateKeyEntry type, but with a chain of length of 1.

To fix this, there are several options. The easier option in my mind is to import and export the pfx file in IE(choosing the option of Including all the certificates in the chain). The import and export process of certificates in IE should be very easy and well documented elsewhere.

Once exported, import the keystore as Justin pointed above. Now, you would have a keystore with certificate of type PrivateKeyEntry and with a certificate chain length of more than 1.

Certain .Net based Web service clients error out(unable to establish trust relationship), if you don't do the above.

How do I verify that an Android apk is signed with a release certificate?

Use this command, (go to java < jdk < bin path in cmd prompt)

$ jarsigner -verify -verbose -certs my_application.apk

If you see "CN=Android Debug", this means the .apk was signed with the debug key generated by the Android SDK (means it is unsigned), otherwise you will find something for CN. For more details see: http://developer.android.com/guide/publishing/app-signing.html

Android Error Building Signed APK: keystore.jks not found for signing config 'externalOverride'

Click on choose existing and again choose the location where your jks file is located.

enter image description here

I hope this trick works for you.

APK signing error : Failed to read key from keystore

Check your keystore file for first, in you example you creating file with name my-release-key.keystore. If its correct and really present in folder Users/bournewang/Documents/Project check alias, in your example it is -alias alias_name, but in config you specified alias mike

Decompile .smali files on an APK

I second that.

Dex2jar will generate a WORKING jar, which you can add as your project source, with the xmls you got from apktool.

However, JDGUI generates .java files which have ,more often than not, errors.

It has got something to do with code obfuscation I guess.

INSTALL_FAILED_NO_MATCHING_ABIS when install apk

I faced this issue when moved from Android 7(Nougat) to Android 8(Oreo).

I have tried several ways listed above and to my bad luck nothing worked.

So i changed the .apk file to .zip file extracted it and found lib folder with which this file was there /x86_64/darwin/libscrypt.dylib so to remove this i added a code in my build.gradle module below android section (i.e.)

packagingOptions {
    exclude 'lib/x86_64/darwin/libscrypt.dylib'
    exclude 'lib/x86_64/freebsd/libscrypt.so'
    exclude 'lib/x86_64/linux/libscrypt.so'
}

Cheers issue solved

What is INSTALL_PARSE_FAILED_NO_CERTIFICATES error?

Recently I had this error while upgrading to Android Studio 4.0. The cause was that the project had V2 Signing Disabled in the signing configuration in build.gradle.

The solution was to remove v2SigningEnabled false or explicitly set it to true, which is the default value.

android {    
    signingConfigs {
        dev {
            v2SigningEnabled true
        }
     }
}

Does Android keep the .apk files? if so where?

To find an apk, download and Install the Bluetooth App Sender from Play store. Once installation completes open the Bluetooth App Sender. It will show all the apps (.apk) installed in your device, then you can easily transfer the app to your PC through Bluetooth.

How to view the contents of an Android APK file?

4 suggested ways to open apk files:

1.open apk file by Android Studio (For Photo,java code and analyze size) the best way

enter image description here

2.open by applications winRar,7zip,etc (Just to see photos and ...)

3.use website javadecompilers (For Photo and java code)

4.use APK Tools (For Photo and java code)

How to edit an Android app?

First you have to download file x-plore and installed it.. After that open it and find the thoes you want to edit.. After that just rename the file Xyz.apk to xyz.zip After that open that file and you can see some folders.. then just go and edit the app..

Checking from shell script if a directory contains files

if ls /some/dir/* >/dev/null 2>&1 ; then echo "huzzah"; fi;

java.util.Date vs java.sql.Date

The java.util.Date class in Java represents a particular moment in time (e,.g., 2013 Nov 25 16:30:45 down to milliseconds), but the DATE data type in the DB represents a date only (e.g., 2013 Nov 25). To prevent you from providing a java.util.Date object to the DB by mistake, Java doesn’t allow you to set a SQL parameter to java.util.Date directly:

PreparedStatement st = ...
java.util.Date d = ...
st.setDate(1, d); //will not work

But it still allows you to do that by force/intention (then hours and minutes will be ignored by the DB driver). This is done with the java.sql.Date class:

PreparedStatement st = ...
java.util.Date d = ...
st.setDate(1, new java.sql.Date(d.getTime())); //will work

A java.sql.Date object can store a moment in time (so that it’s easy to construct from a java.util.Date) but will throw an exception if you try to ask it for the hours (to enforce its concept of being a date only). The DB driver is expected to recognize this class and just use 0 for the hours. Try this:

public static void main(String[] args) {
  java.util.Date d1 = new java.util.Date(12345);//ms since 1970 Jan 1 midnight
  java.sql.Date d2 = new java.sql.Date(12345);
  System.out.println(d1.getHours());
  System.out.println(d2.getHours());
}

Uploading/Displaying Images in MVC 4

        <input type="file" id="picfile" name="picf" />
       <input type="text" id="txtName" style="width: 144px;" />
 $("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;

                    var file = document.getElementById("picfile").files[0];
                    formData.append("FileUpload", file);
                    formData.append("Name", Name);

$.ajax({
                    type: "POST",
                    url: '/Category_Subcategory/Save_Category',
                    data: formData,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    success: function (msg) {

                                 alert(msg);

                    },
                    error: function (error) {
                        alert("errror");
                    }
                });

});

 [HttpPost]
    public ActionResult Save_Category()
    {
      string Name=Request.Form[1]; 
      if (Request.Files.Count > 0)
        {
            HttpPostedFileBase file = Request.Files[0];
         }


    }

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

wait also (optionally) takes the PID of the process to wait for, and with $! you get the PID of the last command launched in background. Modify the loop to store the PID of each spawned sub-process into an array, and then loop again waiting on each PID.

# run processes and store pids in array
for i in $n_procs; do
    ./procs[${i}] &
    pids[${i}]=$!
done

# wait for all pids
for pid in ${pids[*]}; do
    wait $pid
done

How to remove the hash from window.location (URL) with JavaScript without page refresh?

(Too many answers are redundant and outdated.) The best solution now is this:

history.replaceState(null, null, ' ');

Google maps Marker Label with multiple characters

You can use MarkerWithLabel with SVG icons.

Update: The Google Maps Javascript API v3 now natively supports multiple characters in the MarkerLabel

proof of concept fiddle (you didn't provide your icon, so I made one up)

Note: there is an issue with labels on overlapping markers that is addressed by this fix, credit to robd who brought it up in the comments.

code snippet:

_x000D_
_x000D_
function initMap() {_x000D_
  var latLng = new google.maps.LatLng(49.47805, -123.84716);_x000D_
  var homeLatLng = new google.maps.LatLng(49.47805, -123.84716);_x000D_
_x000D_
  var map = new google.maps.Map(document.getElementById('map_canvas'), {_x000D_
    zoom: 12,_x000D_
    center: latLng,_x000D_
    mapTypeId: google.maps.MapTypeId.ROADMAP_x000D_
  });_x000D_
_x000D_
  var marker = new MarkerWithLabel({_x000D_
    position: homeLatLng,_x000D_
    map: map,_x000D_
    draggable: true,_x000D_
    raiseOnDrag: true,_x000D_
    labelContent: "ABCD",_x000D_
    labelAnchor: new google.maps.Point(15, 65),_x000D_
    labelClass: "labels", // the CSS class for the label_x000D_
    labelInBackground: false,_x000D_
    icon: pinSymbol('red')_x000D_
  });_x000D_
_x000D_
  var iw = new google.maps.InfoWindow({_x000D_
    content: "Home For Sale"_x000D_
  });_x000D_
  google.maps.event.addListener(marker, "click", function(e) {_x000D_
    iw.open(map, this);_x000D_
  });_x000D_
}_x000D_
_x000D_
function pinSymbol(color) {_x000D_
  return {_x000D_
    path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',_x000D_
    fillColor: color,_x000D_
    fillOpacity: 1,_x000D_
    strokeColor: '#000',_x000D_
    strokeWeight: 2,_x000D_
    scale: 2_x000D_
  };_x000D_
}_x000D_
google.maps.event.addDomListener(window, 'load', initMap);
_x000D_
html,_x000D_
body,_x000D_
#map_canvas {_x000D_
  height: 500px;_x000D_
  width: 500px;_x000D_
  margin: 0px;_x000D_
  padding: 0px_x000D_
}_x000D_
.labels {_x000D_
  color: white;_x000D_
  background-color: red;_x000D_
  font-family: "Lucida Grande", "Arial", sans-serif;_x000D_
  font-size: 10px;_x000D_
  text-align: center;_x000D_
  width: 30px;_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places&ext=.js"></script>_x000D_
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerwithlabel/src/markerwithlabel.js"></script>_x000D_
<div id="map_canvas" style="height: 400px; width: 100%;"></div>
_x000D_
_x000D_
_x000D_

Using custom fonts using CSS?

First of all, you can't prevent people from downloading fonts except if it is yours and that usually takes months. And it makes no sense to prevent people from using fonts. A lot of fonts that you see on websites can be found on free platforms like the one I mentioned below.

But if you want to implement a font into your website read this: There is a pretty simple and free way to implement fonts into your website. I would recommend Google fonts because it is free and easy to use. For example, I'll use the Bangers font from Google.(https://fonts.google.com/specimen/Bangers?query=bangers&sidebar.open&selection.family=Bangers) This is how it would look like: HTML

<head>
<link href="https://fonts.googleapis.com/css2?family=Bangers&display=swap" rel="stylesheet">
</head>

CSS

body {
font-family: 'Bangers', cursive;
}

How to restart counting from 1 after erasing table in MS Access?

I always use below approach. I've created one table in database as Table1 with only one column i.e. Row_Id Number (Long Integer) and its value is 0

enter image description here

INSERT INTO <TABLE_NAME_TO_RESET>
SELECT Row_Id AS <COLUMN_NAME_TO_RESET>
FROM Table1;

This will insert one row with 0 value in AutoNumber column, later delete that row.

Set adb vendor keys

I tried almost anything but no help...

Everytime was just this

?  ~ adb devices    
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
aeef5e4e    unauthorized

However I've managed to connect device!

There is tutor, step by step.

  1. Remove existing adb keys on PC:

$ rm -v .android/adbkey* .android/adbkey .android/adbkey.pub

  1. Remove existing authorized adb keys on device, path is /data/misc/adb/adb_keys

  2. Now create new adb keypair

? ~ adb keygen .android/adbkey adb I 47453 711886 adb_auth_host.cpp:220] generate_key '.android/adbkey' adb I 47453 711886 adb_auth_host.cpp:173] Writing public key to '.android/adbkey.pub'

  1. Manually copy from PC .android/adbkey.pub (pubkic key) to Device on path /data/misc/adb/adb_keys

  2. Reboot device and check adb devices :

? ~ adb devices List of devices attached aeef5e4e device

Permissions of /data/misc/adb/adb_keys are (766/-rwxrw-rw-) on my device

Where are static methods and static variables stored in Java?

When we create a static variable or method it is stored in the special area on heap: PermGen(Permanent Generation), where it lays down with all the data applying to classes(non-instance data). Starting from Java 8 the PermGen became - Metaspace. The difference is that Metaspace is auto-growing space, while PermGen has a fixed Max size, and this space is shared among all of the instances. Plus the Metaspace is a part of a Native Memory and not JVM Memory.

You can look into this for more details.

Jenkins / Hudson environment variables

Couldn't you just add it as an environment variable in Jenkins settings:

Manage Jenkins -> Global properties > Environment variables: And then click "Add" to add a property PATH and its value to what you need.

What is the difference between i++ & ++i in a for loop?

They both increment the number. ++i is equivalent to i = i + 1.

i++ and ++i are very similar but not exactly the same. Both increment the number, but ++i increments the number before the current expression is evaluted, whereas i++ increments the number after the expression is evaluated.

int i = 3;
int a = i++; // a = 3, i = 4
int b = ++a; // b = 4, a = 4

JavaScript Chart Library

If you're using jQuery I've found flot to be very good - try out the examples to see if they suit your needs, but I've found them to do most of what I need for my current project.

Additionally ExtJS 4.0 has introduced a great set of charts - very powerful, and is designed to work with live data.

Most concise way to test string equality (not object equality) for Ruby strings or symbols?

Your code sample didn't expand on part of your topic, namely symbols, and so that part of the question went unanswered.

If you have two strings, foo and bar, and both can be either a string or a symbol, you can test equality with

foo.to_s == bar.to_s

It's a little more efficient to skip the string conversions on operands with known type. So if foo is always a string

foo == bar.to_s

But the efficiency gain is almost certainly not worth demanding any extra work on behalf of the caller.

Prior to Ruby 2.2, avoid interning uncontrolled input strings for the purpose of comparison (with strings or symbols), because symbols are not garbage collected, and so you can open yourself to denial of service through resource exhaustion. Limit your use of symbols to values you control, i.e. literals in your code, and trusted configuration properties.

Ruby 2.2 introduced garbage collection of symbols.

How to use terminal commands with Github?

git add myfile.h
git commit -m "your commit message"
git push -u origin master

if you don't remember all the files you need to update, use

git status

'numpy.ndarray' object is not callable error

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

In [16]: import numpy as np

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

TypeError: 'numpy.ndarray' object is not callable

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

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

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

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

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

TypeError: 'numpy.ndarray' object is not callable

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


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

MySQL maximum memory usage

in /etc/my.cnf:

[mysqld]
...

performance_schema = 0

table_cache = 0
table_definition_cache = 0
max-connect-errors = 10000

query_cache_size = 0
query_cache_limit = 0

...

Good work on server with 256MB Memory.

How to convert Nonetype to int or string?

That TypeError only appears when you try to pass int() None (which is the only NoneType value, as far as I know). I would say that your real goal should not be to convert NoneType to int or str, but to figure out where/why you're getting None instead of a number as expected, and either fix it or handle the None properly.

Can an html element have multiple ids?

No, you should use nested DIVs if you want to head down that path. Besides, even if you could, imagine the confusion it would cause when you run document.getElementByID(). What ID is it going to grab if there are multiple ones?

On a slightly related topic, you can add multiple classes to a DIV. See Eric Myers discussion at,

http://meyerweb.com/eric/articles/webrev/199802a.html

How to stop app that node.js express 'npm start'

When I tried the suggested solution I realized that my app name was truncated. I read up on process.title in the nodejs documentation (https://nodejs.org/docs/latest/api/process.html#process_process_title) and it says

On Linux and OS X, it's limited to the size of the binary name plus the length of the command line arguments because it overwrites the argv memory.

My app does not use any arguments, so I can add this line of code to my app.js

process.title = process.argv[2];

and then add these few lines to my package.json file

  "scripts": {
    "start": "node app.js this-name-can-be-as-long-as-it-needs-to-be",
    "stop": "killall -SIGINT this-name-can-be-as-long-as-it-needs-to-be"
  },

to use really long process names. npm start and npm stop work, of course npm stop will always terminate all running processes, but that is ok for me.

How to execute two mysql queries as one in PHP/MYSQL?

Yes it is possible without using MySQLi extension.

Simply use CLIENT_MULTI_STATEMENTS in mysql_connect's 5th argument.

Refer to the comments below Husni's post for more information.

Best way to retrieve variable values from a text file?

Suppose that you have a file Called "test.txt" with:

a=1.251
b=2.65415
c=3.54
d=549.5645
e=4684.65489

And you want to find a variable (a,b,c,d or e):

ffile=open('test.txt','r').read()

variable=raw_input('Wich is the variable you are looking for?\n')

ini=ffile.find(variable)+(len(variable)+1)
rest=ffile[ini:]
search_enter=rest.find('\n')
number=float(rest[:search_enter])

print "value:",number

Unable to execute dex: Multiple dex files define

This problem occurs when a same library is added into your project multiple times. If you haven't added the library multiple times intentionaly, check out the dependency/private libraries of the libraries you have added in your project, most probably they have already included a library which is causing this conflict.

How to stick text to the bottom of the page?

Try this

 <head>
 <style type ="text/css" >
   .footer{ 
       position: fixed;     
       text-align: center;    
       bottom: 0px; 
       width: 100%;
   }  
</style>
</head>
<body>
    <div class="footer">All Rights Reserved</div>
</body>

When should you use a class vs a struct in C++?

The only time I use a struct instead of a class is when declaring a functor right before using it in a function call and want to minimize syntax for the sake of clarity. e.g.:

struct Compare { bool operator() { ... } };
std::sort(collection.begin(), collection.end(), Compare()); 

Going to a specific line number using Less in Unix

You can use sed for this too -

sed -n '320123'p filename 

This will print line number 320123.

If you want a range then you can do -

sed -n '320123,320150'p filename 

If you want from a particular line to the very end then -

sed -n '320123,$'p filename 

Resizing UITableView to fit content

based on fl034's answer

SWift 5

var tableViewHeight: NSLayoutConstraint?

    tableViewHeight = NSLayoutConstraint(item: servicesTableView, 
    attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute,
    multiplier: 0.0, constant: 10)
    tableViewHeight?.isActive = true


  func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    tableViewHeight?.constant = tableView.contentSize.height
    tableView.layoutIfNeeded()
}

Nested classes' scope?

All explanations can be found in Python Documentation The Python Tutorial

For your first error <type 'exceptions.NameError'>: name 'outer_var' is not defined. The explanation is:

There is no shorthand for referencing data attributes (or other methods!) from within methods. I find that this actually increases the readability of methods: there is no chance of confusing local variables and instance variables when glancing through a method.

quoted from The Python Tutorial 9.4

For your second error <type 'exceptions.NameError'>: name 'OuterClass' is not defined

When a class definition is left normally (via the end), a class object is created.

quoted from The Python Tutorial 9.3.1

So when you try inner_var = Outerclass.outer_var, the Quterclass hasn't been created yet, that's why name 'OuterClass' is not defined

A more detailed but tedious explanation for your first error:

Although classes have access to enclosing functions’ scopes, though, they do not act as enclosing scopes to code nested within the class: Python searches enclosing functions for referenced names, but never any enclosing classes. That is, a class is a local scope and has access to enclosing local scopes, but it does not serve as an enclosing local scope to further nested code.

quoted from Learning.Python(5th).Mark.Lutz

Uncaught TypeError: Cannot read property 'split' of undefined

og_date = "2012-10-01";
console.log(og_date); // => "2012-10-01"

console.log(og_date.split('-')); // => [ '2012', '10', '01' ]

og_date.value would only work if the date were stored as a property on the og_date object. Such as: var og_date = {}; og_date.value="2012-10-01"; In that case, your original console.log would work.

Re-assign host access permission to MySQL user

Similar issue where I was getting permissions failed. On my setup, I SSH in only. So What I did to correct the issue was

sudo MySQL
SELECT User, Host FROM mysql.user WHERE Host <> '%';
MariaDB [(none)]> SELECT User, Host FROM mysql.user WHERE Host <> '%';
+-------+-------------+
| User  | Host        |
+-------+-------------+
| root  | 169.254.0.% |
| foo   | 192.168.0.% |
| bar   | 192.168.0.% |
+-------+-------------+
4 rows in set (0.00 sec)

I need these users moved to 'localhost'. So I issued the following:

UPDATE mysql.user SET host = 'localhost' WHERE user = 'foo';
UPDATE mysql.user SET host = 'localhost' WHERE user = 'bar';

Run SELECT User, Host FROM mysql.user WHERE Host <> '%'; again and we see:

MariaDB [(none)]> SELECT User, Host FROM mysql.user WHERE Host <> '%';
+-------+-------------+
| User  | Host        |
+-------+-------------+
| root  | 169.254.0.% |
| foo   | localhost   |
| bar   | localhost   |
+-------+-------------+
4 rows in set (0.00 sec)

And then I was able to work normally again. Hope that helps someone.

$ mysql -u foo -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 74
Server version: 10.1.23-MariaDB-9+deb9u1 Raspbian 9.0

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

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

MariaDB [(none)]>

php stdClass to array

Here is the best Object to Array function I have - works recursively:

function object_to_array($obj, &$arr){

    if(!is_object($obj) && !is_array($obj)){
        $arr = $obj;
        return $arr;
    }

    foreach ($obj as $key => $value)
    {
        if (!empty($value))
        {
            $arr[$key] = array();
            object_to_array_v2($value, $arr[$key]);
        }
        else
        {
            $arr[$key] = $value;
        }
    }
    return $arr;
}

$clean_array = object_to_array($object_data_here);

jQuery exclude elements with certain class in selector

use this..

$(".content_box a:not('.button')")

How to execute only one test spec with angular-cli

This is working for me in Angular 7. It is based on the --main option of the ng command. I am not sure if this option is undocumented and possibly subject to change, but it works for me. I put a line in my package.json file in scripts section. There using the --main option of with the ng test command, I specify the path to the .spec.ts file I want to execute. For example

"test 1": "ng test --main E:/WebRxAngularClient/src/app/test/shared/my-date-utils.spec.ts",

You can run the script as you run any such script. I run it in Webstorm by clicking on "test 1" in the npm section.

Android charting libraries

You can use MPAndroidChart.

It's native, free, easy to use, fast and reliable.

Core features, benefits:

  • LineChart, BarChart (vertical, horizontal, stacked, grouped), PieChart, ScatterChart, CandleStickChart (for financial data), RadarChart (spider web chart), BubbleChart
  • Combined Charts (e.g. lines and bars in one)
  • Scaling on both axes (with touch-gesture, axes separately or pinch-zoom)
  • Dragging / Panning (with touch-gesture)
  • Separate (dual) y-axes
  • Highlighting values (with customizeable popup-views)
  • Save chart to SD-Card (as image)
  • Predefined color templates
  • Legends (generated automatically, customizeable)
  • Customizeable Axes (both x- and y-axis)
  • Animations (build up animations, on both x- and y-axis)
  • Limit lines (providing additional information, maximums, ...)
  • Listeners for touch, gesture & selection callbacks
  • Fully customizeable (paints, typefaces, legends, colors, background, dashed lines, ...)
  • Realm.io mobile database support via MPAndroidChart-Realm library
  • Smooth rendering for up to 10.000 data points in Line- and BarChart
  • Lightweight (method count ~1.4K)
  • Available as .jar file (only 500kb in size)
  • Available as gradle dependency and via maven
  • Good documentation
  • Example Project (code for demo-application)
  • Google-PlayStore Demo Application
  • Widely used, great support on both GitHub and stackoverflow - mpandroidchart
  • Also available for iOS: Charts (API works the same way)
  • Also available for Xamarin: MPAndroidChart.Xamarin

Drawbacks:

Disclaimer: I am the developer of this library.

Empty brackets '[]' appearing when using .where

A good bet is to utilize Rails' Arel SQL manager, which explicitly supports case-insensitive ActiveRecord queries:

t = Guide.arel_table Guide.where(t[:title].matches('%attack')) 

Here's an interesting blog post regarding the portability of case-insensitive queries using Arel. It's worth a read to understand the implications of utilizing Arel across databases.

What is the difference between a token and a lexeme?

CS researchers, as those from Math, are fond of creating "new" terms. The answers above are all nice but apparently, there is no such a great need to distinguish tokens and lexemes IMHO. They are like two ways to represent the same thing. A lexeme is concrete -- here a set of char; a token, on the other hand, is abstract -- usually referring to the type of a lexeme together with its semantic value if that makes sense. Just my two cents.

How do I get time of a Python program's execution?

Even better for Linux: time

$ time -v python rhtest2.py

    Command being timed: "python rhtest2.py"
    User time (seconds): 4.13
    System time (seconds): 0.07
    Percent of CPU this job got: 91%
    Elapsed (wall clock) time (h:mm:ss or m:ss): 0:04.58
    Average shared text size (kbytes): 0
    Average unshared data size (kbytes): 0
    Average stack size (kbytes): 0
    Average total size (kbytes): 0
    Maximum resident set size (kbytes): 0
    Average resident set size (kbytes): 0
    Major (requiring I/O) page faults: 15
    Minor (reclaiming a frame) page faults: 5095
    Voluntary context switches: 27
    Involuntary context switches: 279
    Swaps: 0
    File system inputs: 0
    File system outputs: 0
    Socket messages sent: 0
    Socket messages received: 0
    Signals delivered: 0
    Page size (bytes): 4096
    Exit status: 0

How to get access token from FB.login method in javascript SDK

If you are already connected, simply type this in the javascript console:

FB.getAuthResponse()['accessToken']

Why am I getting a FileNotFoundError?

You might need to change your path by:

import os
path=os.chdir(str('Here should be the path to your file')) #This command changes directory

This is what worked for me at least! Hope it works for you too!

IPython Notebook save location

If you're using IPython 4.x/Jupyter, run

$ jupyter notebook --generate-config

This will create a file jupyter_notebook_config.py in ~/.jupyter. This file already has a line starting with # c.NotebookApp.notebook_dir=u''.

All you need to do is to uncomment this line and change the value to your desired location, e.g., c.NotebookApp.notebook_dir=u'/home/alice/my_ipython_notebooks'

How to get IntPtr from byte[] in C#

You could use Marshal.UnsafeAddrOfPinnedArrayElement to get a memory pointer to the array (or to a specific element in the array). Keep in mind that the array must be pinned first as per the API documentation:

The array must be pinned using a GCHandle before it is passed to this method. For maximum performance, this method does not validate the array passed to it; this can result in unexpected behavior.

An efficient way to transpose a file in Bash

Have a look at GNU datamash which can be used like datamash transpose. A future version will also support cross tabulation (pivot tables)

Here is how you would do it with space separated columns:

datamash transpose -t ' ' < file > transposed_file

How do I set a fixed background image for a PHP file?

Your question doesn't have anything to do with PHP... just CSS.

Your CSS is correct, but your browser won't typically be able to open what you have put in for a URL. At a minimum, you'll need a file: path. It would be best to reference the file by its relative path.

How to programmatically get iOS status bar height

Here is a Swift way to get screen status bar height:

var screenStatusBarHeight: CGFloat {
    return UIApplication.sharedApplication().statusBarFrame.height
}

These are included as a standard function in a project of mine: https://github.com/goktugyil/EZSwiftExtensions

Convert javascript array to string

Four methods to convert an array to a string.

Coercing to a string

var arr = ['a', 'b', 'c'] + [];  // "a,b,c"

var arr = ['a', 'b', 'c'] + '';  // "a,b,c"

Calling .toString()

var arr = ['a', 'b', 'c'].toString();  // "a,b,c"

Explicitly joining using .join()

var arr = ['a', 'b', 'c'].join();  // "a,b,c" (Defaults to ',' seperator)

var arr = ['a', 'b', 'c'].join(',');  // "a,b,c"

You can use other separators, for example, ', '

var arr = ['a', 'b', 'c'].join(', ');  // "a, b, c"

Using JSON.stringify()

This is cleaner, as it quotes strings inside of the array and handles nested arrays properly.

var arr = JSON.stringify(['a', 'b', 'c']);  // '["a","b","c"]'

Count distinct value pairs in multiple columns in SQL

You can also do something like:

SELECT COUNT(DISTINCT id + name + address) FROM mytable

JQUERY: Uncaught Error: Syntax error, unrecognized expression

If you're using jQuery 2.1.4 or above, try this:

$("#" + this.d);

Or, you can define var before using it. It makes your code simpler.

var d = this.d
$("#" + d);

Word wrap for a label in Windows Forms

Not sure it will fit all use-cases but I often use a simple trick to get the wrapping behaviour: put your Label with AutoSize=false inside a 1x1 TableLayoutPanel which will take care of the Label's size.

How to transfer some data to another Fragment?

Your input fragment

public class SecondFragment extends Fragment  {


    EditText etext;
    Button btn;
    String etex;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.secondfragment, container, false);
        etext = (EditText) v.findViewById(R.id.editText4);
        btn = (Button) v.findViewById(R.id.button);
        btn.setOnClickListener(mClickListener);
        return v;
    }

    View.OnClickListener mClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            etex = etext.getText().toString();
            FragmentTransaction transection = getFragmentManager().beginTransaction();
            Viewfragment mfragment = new Viewfragment();
            //using Bundle to send data
            Bundle bundle = new Bundle();
            bundle.putString("textbox", etex);
            mfragment.setArguments(bundle); //data being send to SecondFragment
            transection.replace(R.id.frame, mfragment);
            transection.isAddToBackStackAllowed();
            transection.addToBackStack(null);
            transection.commit();

        }
    };



}

your view fragment

public class Viewfragment extends Fragment {

    TextView txtv;
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.viewfrag,container,false);
        txtv = (TextView)  v.findViewById(R.id.textView4);
        Bundle bundle=getArguments();
        txtv.setText(String.valueOf(bundle.getString("textbox")));
        return v;
    }


}

How to get current time and date in Android

tl;dr

Instant.now()  // Current moment in UTC.

…or…

ZonedDateTime.now( ZoneId.of( "America/Montreal" ) )  // In a particular time zone

Details

The other Answers, while correct, are outdated. The old date-time classes have proven to be poorly designed, confusing, and troublesome.

java.time

Those old classes have been supplanted by the java.time framework.

These new classes are inspired by the highly successful Joda-Time project, defined by JSR 310, and extended by the ThreeTen-Extra project.

See the Oracle Tutorial.

Instant

An Instant is a moment on the timeline in UTC with resolution up to nanoseconds.

 Instant instant = Instant.now(); // Current moment in UTC.

Time Zone

Apply a time zone (ZoneId) to get a ZonedDateTime. If you omit the time zone your JVM’s current default time zone is implicitly applied. Better to specify explicitly the desired/expected time zone.

Use proper time zone names in the format of continent/region such as America/Montreal, Europe/Brussels, or Asia/Kolkata. Never use the 3-4 letter abbreviations such as EST or IST as they are neither standardized nor unique.

ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata", "Europe/Paris", and so on.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

Table of date-time types in Java, both modern and legacy

Generating Strings

You can easily generate a String as a textual representation of the date-time value. You can go with a standard format, your own custom format, or an automatically localized format.

ISO 8601

You can call the toString methods to get text formatted using the common and sensible ISO 8601 standard.

String output = instant.toString();

2016-03-23T03:09:01.613Z

Note that for ZonedDateTime, the toString method extends the ISO 8601 standard by appending the name of the time zone in square brackets. Extremely useful and important information, but not standard.

2016-03-22T20:09:01.613-08:00[America/Los_Angeles]

Custom format

Or specify your own particular formatting pattern with the DateTimeFormatter class.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy hh:mm a" );

Specify a Locale for a human language (English, French, etc.) to use in translating the name of day/month and also in defining cultural norms such as the order of year and month and date. Note that Locale has nothing to do with time zone.

formatter = formatter.withLocale( Locale.US ); // Or Locale.CANADA_FRENCH or such.
String output = zdt.format( formatter );

Localizing

Better yet, let java.time do the work of localizing automatically.

DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM );
String output = zdt.format( formatter.withLocale( Locale.US ) );  // Or Locale.CANADA_FRENCH and so on.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table listing which implementation of the *java.time* technology to use on which versions of Java and Android.

Linq filter List<string> where it contains a string value from another List<string>

Try the following:

var filteredFileSet = fileList.Where(item => filterList.Contains(item));

When you iterate over filteredFileSet (See LINQ Execution) it will consist of a set of IEnumberable values. This is based on the Where Operator checking to ensure that items within the fileList data set are contained within the filterList set.

As fileList is an IEnumerable set of string values, you can pass the 'item' value directly into the Contains method.

failed to load ad : 3

I had the same error in my app. I was launching the app in debug configuration. The problem was solved as soon as I run the release version of my app on the same device. In Android Studio just go to Build -> Generate Signed APK and choose the release configuration. Then install release .apk on your device. In debug configuration you can also check whether your test ads appears by adding AdRequest.Builder.addTestDevice("YOUR TEST DEVICE"). If it's ok with ads appearing, it means you just need release configuration.

How to strip HTML tags from string in JavaScript?

Using the browser's parser is the probably the best bet in current browsers. The following will work, with the following caveats:

  • Your HTML is valid within a <div> element. HTML contained within <body> or <html> or <head> tags is not valid within a <div> and may therefore not be parsed correctly.
  • textContent (the DOM standard property) and innerText (non-standard) properties are not identical. For example, textContent will include text within a <script> element while innerText will not (in most browsers). This only affects IE <=8, which is the only major browser not to support textContent.
  • The HTML does not contain <script> elements.
  • The HTML is not null
  • The HTML comes from a trusted source. Using this with arbitrary HTML allows arbitrary untrusted JavaScript to be executed. This example is from a comment by Mike Samuel on the duplicate question: <img onerror='alert(\"could run arbitrary JS here\")' src=bogus>

Code:

var html = "<p>Some HTML</p>";
var div = document.createElement("div");
div.innerHTML = html;
var text = div.textContent || div.innerText || "";

What's the difference between ASCII and Unicode?

ASCII has 128 code positions, allocated to graphic characters and control characters (control codes).

Unicode has 1,114,112 code positions. About 100,000 of them have currently been allocated to characters, and many code points have been made permanently noncharacters (i.e. not used to encode any character ever), and most code points are not yet assigned.

The only things that ASCII and Unicode have in common are: 1) They are character codes. 2) The 128 first code positions of Unicode have been defined to have the same meanings as in ASCII, except that the code positions of ASCII control characters are just defined as denoting control characters, with names corresponding to their ASCII names, but their meanings are not defined in Unicode.

Sometimes, however, Unicode is characterized (even in the Unicode standard!) as “wide ASCII”. This is a slogan that mainly tries to convey the idea that Unicode is meant to be a universal character code the same way as ASCII once was (though the character repertoire of ASCII was hopelessly insufficient for universal use), as opposite to using different codes in different systems and applications and for different languages.

Unicode as such defines only the “logical size” of characters: Each character has a code number in a specific range. These code numbers can be presented using different transfer encodings, and internally, in memory, Unicode characters are usually represented using one or two 16-bit quantities per character, depending on character range, sometimes using one 32-bit quantity per character.

AngularJS - Does $destroy remove event listeners?

Event listeners

First off it's important to understand that there are two kinds of "event listeners":

  1. Scope event listeners registered via $on:

    $scope.$on('anEvent', function (event, data) {
      ...
    });
    
  2. Event handlers attached to elements via for example on or bind:

    element.on('click', function (event) {
      ...
    });
    

$scope.$destroy()

When $scope.$destroy() is executed it will remove all listeners registered via $on on that $scope.

It will not remove DOM elements or any attached event handlers of the second kind.

This means that calling $scope.$destroy() manually from example within a directive's link function will not remove a handler attached via for example element.on, nor the DOM element itself.


element.remove()

Note that remove is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.

When element.remove() is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on.

It will not destroy the $scope associated with the element.

To make it more confusing there is also a jQuery event called $destroy. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:

element.on('$destroy', function () {
  scope.$destroy();
});

What to do when a directive is "destroyed"

This depends on how the directive is "destroyed".

A normal case is that a directive is destroyed because ng-view changes the current view. When this happens the ng-view directive will destroy the associated $scope, sever all the references to its parent scope and call remove() on the element.

This means that if that view contains a directive with this in its link function when it's destroyed by ng-view:

scope.$on('anEvent', function () {
 ...
});

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

Both event listeners will be removed automatically.

However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references.

Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.

For example if you have registered a listener on $rootScope:

var unregisterFn = $rootScope.$on('anEvent', function () {});

scope.$on('$destroy', unregisterFn);

This is needed since $rootScope is never destroyed during the lifetime of the application.

The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.

Another situation would be to cancel $interval/$timeout:

var promise = $interval(function () {}, 1000);

scope.$on('$destroy', function () {
  $interval.cancel(promise);
});

If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:

var windowClick = function () {
   ...
};

angular.element(window).on('click', windowClick);

scope.$on('$destroy', function () {
  angular.element(window).off('click', windowClick);
});

These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view or ng-if.

If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.

Loop over html table and get checked checkboxes (JQuery)

use .filter(':has(:checkbox:checked)' ie:

$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
 $('#out').append(this.id);
});

android TextView: setting the background color dynamically doesn't work

Well I had situation when web service returned a color in hex format like "#CC2233" and I wanted to put this color on textView by using setBackGroundColor(), so I used android Color class to get int value of hex string and passed it to mentioned function. Everything worked. This is example:

String myHexColor = "#CC2233";
TextView myView = (TextView) findViewById(R.id.myTextView);
myView.setBackGroundColor(Color.pasrsehexString(myHexColor));

P.S. posted this answer because other solutions didn't work for me. I hope this will help someone:)

Cluster analysis in R: determine the optimal number of clusters

In order to determine optimal k-cluster in clustering methods. I usually using Elbow method accompany by Parallel processing to avoid time-comsuming. This code can sample like this:

Elbow method

elbow.k <- function(mydata){
dist.obj <- dist(mydata)
hclust.obj <- hclust(dist.obj)
css.obj <- css.hclust(dist.obj,hclust.obj)
elbow.obj <- elbow.batch(css.obj)
k <- elbow.obj$k
return(k)
}

Running Elbow parallel

no_cores <- detectCores()
    cl<-makeCluster(no_cores)
    clusterEvalQ(cl, library(GMD))
    clusterExport(cl, list("data.clustering", "data.convert", "elbow.k", "clustering.kmeans"))
 start.time <- Sys.time()
 elbow.k.handle(data.clustering))
 k.clusters <- parSapply(cl, 1, function(x) elbow.k(data.clustering))
    end.time <- Sys.time()
    cat('Time to find k using Elbow method is',(end.time - start.time),'seconds with k value:', k.clusters)

It works well.

GitHub - failed to connect to github 443 windows/ Failed to connect to gitHub - No Error

If your country or working environment blocks sites like Github.

Then you can build a proxy, e.g. use xxnet, which is free & based on Google's GAE, and available for Windows / Linux / Mac.

Then set proxy address for git, e.g:

git config --global http.proxy 127.0.0.1:8087

How to connect to SQL Server from command prompt with Windows authentication

Try This :

--Default Instance

SQLCMD -S SERVERNAME -E

--OR
--Named Instance

SQLCMD -S SERVERNAME\INSTANCENAME -E

--OR

SQLCMD -S SERVERNAME\INSTANCENAME,1919 -E

More details can be found here

PHP PDO with foreach and fetch

This is because you are reading a cursor, not an array. This means that you are reading sequentially through the results and when you get to the end you would need to reset the cursor to the beginning of the results to read them again.

If you did want to read over the results multiple times, you could use fetchAll to read the results into a true array and then it would work as you are expecting.

What's the best way to override a user agent CSS stylesheet rule that gives unordered-lists a 1em margin?

Everything you write in your own stylesheet is overwriting the user agent styles - that's the point of writing your own stylesheet.

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

  1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.

  2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.

  3. first() returns the first record found in the database. If no matching model exist, it returns null.

  4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.

  5. get() returns a collection of models matching the query.

  6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.

  7. toArray() converts the model/collection into a simple PHP array.


Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

If you ever want to get a plain array from a collection, call its all() method.


1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

Getting the text from a drop-down box

var selectoption = document.getElementById("dropdown");
var optionText = selectoption.options[selectoption.selectedIndex].text;

Iterate keys in a C++ map

If you need an iterator that just returns the keys you need to wrap map's iterator in your own class that provides the desired interface. You can declare a new iterator class from scratch like here, of use existing helper constructs. This answer shows how to use Boost's transform_iterator to wrap the iterator in one that only returns the values/keys.

How to make a Qt Widget grow with the window size?

The accepted answer (its image) is wrong, at least now in QT5. Instead you should assign a layout to the root object/widget (pointing to the aforementioned image, it should be the MainWindow instead of centralWidget). Also note that you must have at least one QObject created beneath it for this to work. Do this and your ui will become responsive to window resizing.

Error: Cannot access file bin/Debug/... because it is being used by another process

I understand this is an old question. Unfortunately I was facing the same issue with my .net core 2.0 application in visual studio 2017. So, I thought of sharing the solution which worked for me. Before this solution I had tried the below steps.

  1. Restarted visual studio
  2. Closed all the application
  3. Clean my solution and rebuild

None of the above steps didn't fix the issue.

And then I opened my Task Manager and selected dotnet process and then clicked End task button. Later I opened my Visual Studio and everything was working fine.

enter image description here

ORA-06508: PL/SQL: could not find program unit being called

I recompiled the package specification, even though the change was only in the package body. This resolved my issue

Can jQuery read/write cookies to a browser?

A new jQuery plugin for cookie retrieval and manipulation with binding for forms, etc: http://plugins.jquery.com/project/cookies

How to fix Invalid byte 1 of 1-byte UTF-8 sequence

I happened to run into this problem because of an Ant build.

That Ant build took files and applied filterchain expandproperties to it. During this file filtering, my Windows machine's implicit default non-UTF-8 character encoding was used to generate the filtered files - therefore characters outside of its character set could not be mapped correctly.

One solution was to provide Ant with an explicit environment variable for UTF-8. In Cygwin, before launching Ant: export ANT_OPTS="-Dfile.encoding=UTF-8".

Convert System.Drawing.Color to RGB and Hex Value

You could keep it simple and use the native color translator:

Color red = ColorTranslator.FromHtml("#FF0000");
string redHex = ColorTranslator.ToHtml(red);

Then break the three color pairs into integer form:

int value = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

How to use wget in php?

You can use curl in order to both fetch the data, and be identified (for both "basic" and "digest" auth), without requiring extended permissions (like exec or allow_url_fopen).

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/file.xml");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "user:pass");
$result = curl_exec($ch);
curl_close($ch);

Your result will then be stored in the $result variable.

pandas get column average/mean

Do note that it needs to be in the numeric data type in the first place.

 import pandas as pd
 df['column'] = pd.to_numeric(df['column'], errors='coerce')

Next find the mean on one column or for all numeric columns using describe().

df['column'].mean()
df.describe()

Example of result from describe:

          column 
count    62.000000 
mean     84.678548 
std     216.694615 
min      13.100000 
25%      27.012500 
50%      41.220000 
75%      70.817500 
max    1666.860000

jquery how to catch enter key and change event to tab

Here is what I've been using:

$("[tabindex]").addClass("TabOnEnter");
$(document).on("keypress", ".TabOnEnter", function (e) {
 //Only do something when the user presses enter
     if (e.keyCode == 13) {
          var nextElement = $('[tabindex="' + (this.tabIndex + 1) + '"]');
          console.log(this, nextElement);
           if (nextElement.length)
                nextElement.focus()
           else
                $('[tabindex="1"]').focus();
      }
});

Pays attention to the tabindex and is not specific to the form but to the whole page.

Note live has been obsoleted by jQuery, now you should be using on

How to get all enum values in Java?

Enums are just like Classes in that they are typed. Your current code just checks if it is an Enum without specifying what type of Enum it is a part of.

Because you haven't specified the type of the enum, you will have to use reflection to find out what the list of enum values is.

You can do it like so:

enumValue.getDeclaringClass().getEnumConstants() 

This will return an array of Enum objects, with each being one of the available options.

How do I add more members to my ENUM-type column in MySQL?

The discussion I had with Asaph may be unclear to follow as we went back and forth quite a bit.

I thought that I might clarify the upshot of our discourse for others who might face similar situations in the future to benefit from:

ENUM-type columns are very difficult beasts to manipulate. I wanted to add two countries (Malaysia & Sweden) to the existing set of countries in my ENUM.

It seems that MySQL 5.1 (which is what I am running) can only update the ENUM by redefining the existing set in addition to what I want:

This did not work:

ALTER TABLE carmake CHANGE country country ENUM('Sweden','Malaysia') DEFAULT NULL;

The reason was that the MySQL statement was replacing the existing ENUM with another containing the entries 'Malaysia' and 'Sweden' only. MySQL threw up an error because the carmake table already had values like 'England' and 'USA' which were not part of the new ENUM's definition.

Surprisingly, the following did not work either:

ALTER TABLE carmake CHANGE country country ENUM('Australia','England','USA'...'Sweden','Malaysia') DEFAULT NULL;

It turns out that even the order of elements of the existing ENUM needs to be preserved while adding new members to it. So if my existing ENUM looks something like ENUM('England','USA'), then my new ENUM has to be defined as ENUM('England','USA','Sweden','Malaysia') and not ENUM('USA','England','Sweden','Malaysia'). This problem only becomes manifest when there are records in the existing table that use 'USA' or 'England' values.

BOTTOM LINE:

Only use ENUMs when you do not expect your set of members to change once defined. Otherwise, lookup tables are much easier to update and modify.

What is __pycache__?

The python interpreter compiles the *.py script file and saves the results of the compilation to the __pycache__ directory.

When the project is executed again, if the interpreter identifies that the *.py script has not been modified, it skips the compile step and runs the previously generated *.pyc file stored in the __pycache__ folder.

When the project is complex, you can make the preparation time before the project is run shorter. If the program is too small, you can ignore that by using python -B abc.py with the B option.

Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

Not tested, but something like this:

var now = new Date();
var str = now.getUTCFullYear().toString() + "/" +
          (now.getUTCMonth() + 1).toString() +
          "/" + now.getUTCDate() + " " + now.getUTCHours() +
          ":" + now.getUTCMinutes() + ":" + now.getUTCSeconds();

Of course, you'll need to pad the hours, minutes, and seconds to two digits or you'll sometimes get weird looking times like "2011/12/2 19:2:8."

How to SSH to a VirtualBox guest externally through a host?

On secure networks setting your network to bridge might not work. Administrators could only allow one mac address per port or even worse block the port should the switches detect multiple macs on one port.

The best solution in my opinion is to set up additional network interfaces to handle additional services you would like to run on your machines. So I have a bridge interface to allow for bridging when I take my laptop home and can SSH into it from other devices on my network as well as a host only adapter when I would like to SSH into my VM from my laptop when I am connected to the eduroam wifi network on campus.

How to break a while loop from an if condition inside the while loop?

An "if" is not a loop. Just use the break inside the "if" and it will break out of the "while".

If you ever need to use genuine nested loops, Java has the concept of a labeled break. You can put a label before a loop, and then use the name of the label is the argument to break. It will break outside of the labeled loop.

multiple ways of calling parent method in php

Unless I am misunderstanding the question, I would almost always use $this->get_species because the subclass (in this case dog) could overwrite that method since it does extend it. If the class dog doesn't redefine the method then both ways are functionally equivalent but if at some point in the future you decide you want the get_species method in dog should print "dog" then you would have to go back through all the code and change it.

When you use $this it is actually part of the object which you created and so will always be the most up-to-date as well (if the property being used has changed somehow in the lifetime of the object) whereas using the parent class is calling the static class method.

How can I find the number of days between two Date objects in Ruby?

Try this:

num_days = later_date - earlier_date

how to call service method from ng-change of select in angularjs?

You have at least two issues in your code:

  • ng-change="getScoreData(Score)

    Angular doesn't see getScoreData method that refers to defined service

  • getScoreData: function (Score, callback)

    We don't need to use callback since GET returns promise. Use then instead.

Here is a working example (I used random address only for simulation):

HTML

<select ng-model="score"
        ng-change="getScoreData(score)" 
        ng-options="score as score.name for score in  scores"></select>
    <pre>{{ScoreData|json}}</pre> 

JS

var fessmodule = angular.module('myModule', ['ngResource']);

fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {

    $scope.scores = [{
        name: 'Bukit Batok Street 1',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
    }, {
        name: 'London 8',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
    }];

    $scope.getScoreData = function(score) {
        ScoreDataService.getScoreData(score).then(function(result) {
            $scope.ScoreData = result;
        }, function(result) {
            alert("Error: No data returned");
        });
    };

});

fessmodule.$inject = ['$scope', 'ScoreDataService'];

fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {

    var factory = {
        getScoreData: function(score) {
            console.log(score);
            var data = $http({
                method: 'GET',
                url: score.URL
            });


            return data;
        }
    }
    return factory;
}]);

Demo Fiddle

Use multiple css stylesheets in the same html page

You can't. The last stylesheet you specify will be the one html page will use. Think of it as a big single .css document.

Flutter- wrapping text

You Can Wrap your widget with Flexible Widget and than you can set property of Text using overflow property of Text Widget. you have to set TextOverflow.clip for example:-

Flexible
(child: new Text("This is Dummy Long Text",
 style: TextStyle(
 fontFamily: "Roboto",
 color: Colors.black,
 fontSize: 10.0,
 fontWeight: FontWeight.bold),
 overflow: TextOverflow.clip,),)

hope this help someone :)

React PropTypes : Allow different types of PropTypes for one prop

This might work for you:

height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

How to check not in array element

you can check using php in_array() built in function

<?php
  $os = array("Mac", "NT", "Irix", "Linux");
  if (in_array("Irix", $os)) {
    echo "Got Irix";
 }
 if (in_array("mac", $os)) {
  echo "Got mac";
}
?>

and you can also check using this

<?php
  $search_array = array('first' => 1, 'second' => 4);
  if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
   }
   ?>

in_array() is fine if you're only checking but if you need to check that a value exists and return the associated key, array_search is a better option.

$data = array(
0 => 'Key1',
1 => 'Key2'
);

$key = array_search('Key2', $data);

if ($key) {
 echo 'Key is ' . $key;
} else {
 echo 'Key not found';
}

for more details http://php.net/manual/en/function.in-array.php

Algorithm: efficient way to remove duplicate integers from an array

The return value of the function should be the number of unique elements and they are all stored at the front of the array. Without this additional information, you won't even know if there were any duplicates.

Each iteration of the outer loop processes one element of the array. If it is unique, it stays in the front of the array and if it is a duplicate, it is overwritten by the last unprocessed element in the array. This solution runs in O(n^2) time.

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

size_t rmdup(int *arr, size_t len)
{
  size_t prev = 0;
  size_t curr = 1;
  size_t last = len - 1;
  while (curr <= last) {
    for (prev = 0; prev < curr && arr[curr] != arr[prev]; ++prev);
    if (prev == curr) {
      ++curr;
    } else {
      arr[curr] = arr[last];
      --last;
    }
  }
  return curr;
}

void print_array(int *arr, size_t len)
{
  printf("{");
  size_t curr = 0;
  for (curr = 0; curr < len; ++curr) {
    if (curr > 0) printf(", ");
    printf("%d", arr[curr]);
  }
  printf("}");
}

int main()
{
  int arr[] = {4, 8, 4, 1, 1, 2, 9};
  printf("Before: ");
  size_t len = sizeof (arr) / sizeof (arr[0]);
  print_array(arr, len);
  len = rmdup(arr, len);
  printf("\nAfter: ");
  print_array(arr, len);
  printf("\n");
  return 0;
}

gradle build fails on lint task

if abortOnError false will not resolve your problem, you can try this.

lintOptions {
    checkReleaseBuilds false
}

Get url parameters from a string in .NET

You can use the following workaround for it to work with the first parameter too:

var param1 =
    HttpUtility.ParseQueryString(url.Substring(
        new []{0, url.IndexOf('?')}.Max()
    )).Get("param1");

Search all tables, all columns for a specific value SQL Server

I've just updated my blog post to correct the error in the script that you were having Jeff, you can see the updated script here: Search all fields in SQL Server Database

As requested, here's the script in case you want it but I'd recommend reviewing the blog post as I do update it from time to time

DECLARE @SearchStr nvarchar(100)
SET @SearchStr = '## YOUR STRING HERE ##'
 
 
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Updated and tested by Tim Gaunt
-- http://www.thesitedoctor.co.uk
-- http://blogs.thesitedoctor.co.uk/tim/2010/02/19/Search+Every+Table+And+Field+In+A+SQL+Server+Database+Updated.aspx
-- Tested on: SQL Server 7.0, SQL Server 2000, SQL Server 2005 and SQL Server 2010
-- Date modified: 03rd March 2011 19:00 GMT
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
 
SET NOCOUNT ON
 
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
 
WHILE @TableName IS NOT NULL
 
BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM     INFORMATION_SCHEMA.TABLES
        WHERE         TABLE_TYPE = 'BASE TABLE'
            AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND    OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )
 
    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
         
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM     INFORMATION_SCHEMA.COLUMNS
            WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                AND    QUOTENAME(COLUMN_NAME) > @ColumnName
        )
 
        IF @ColumnName IS NOT NULL
         
        BEGIN
            INSERT INTO #Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END   
END
 
SELECT ColumnName, ColumnValue FROM #Results
 
DROP TABLE #Results

Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape?

Your code is working when i click out side the modal, but if i use html input field inside modal-body then focus your cursor on that input then press esc key the modal has closed. Click here

Flask raises TemplateNotFound error even though template file exists

(Please note that the above accepted Answer provided for file/project structure is absolutely correct.)

Also..

In addition to properly setting up the project file structure, we have to tell flask to look in the appropriate level of the directory hierarchy.

for example..

    app = Flask(__name__, template_folder='../templates')
    app = Flask(__name__, template_folder='../templates', static_folder='../static')

Starting with ../ moves one directory backwards and starts there.

Starting with ../../ moves two directories backwards and starts there (and so on...).

Hope this helps

How can I find an element by CSS class with XPath?

This selector should work but will be more efficient if you replace it with your suited markup:

//*[contains(@class, 'Test')]

Or, since we know the sought element is a div:

//div[contains(@class, 'Test')]

But since this will also match cases like class="Testvalue" or class="newTest", @Tomalak's version provided in the comments is better:

//div[contains(concat(' ', @class, ' '), ' Test ')]

If you wished to be really certain that it will match correctly, you could also use the normalize-space function to clean up stray whitespace characters around the class name (as mentioned by @Terry):

//div[contains(concat(' ', normalize-space(@class), ' '), ' Test ')]

Note that in all these versions, the * should best be replaced by whatever element name you actually wish to match, unless you wish to search each and every element in the document for the given condition.

Get Selected Item Using Checkbox in Listview

I had similar problem. Provided xml sample is put as single ListViewItem, and i couldn't click on Item itself, but checkbox was workng.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="50dp"
    android:id="@+id/source_container"
    >
    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:id="@+id/menu_source_icon"
        android:background="@drawable/bla"
        android:layout_margin="5dp"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/menu_source_name"
        android:text="Test"
        android:textScaleX="1.5"
        android:textSize="20dp"
        android:padding="8dp"
        android:layout_weight="1"
        android:layout_gravity="center_vertical"
        android:textColor="@color/source_text_color"/>
    <CheckBox
        android:layout_width="40dp"
        android:layout_height="match_parent"
        android:id="@+id/menu_source_check_box"/>

</LinearLayout>

Solution: add attribute

android:focusable="false"

to CheckBox control.

How to set maximum fullscreen in vmware?

Go to view and press "Switch to scale mode" which will adjust the virtual screen when you adjust the application.

What is the correct way to restore a deleted file from SVN?

Use the Tortoise SVN copy functionality to revert commited changes:

  1. Right click the parent folder that contains the deleted files/folder
  2. Select the "show log"
  3. Select and right click on the version before which the changes/deleted was done
  4. Select the "browse repository"
  5. Select the file/folder which needs to be restored and right click
  6. Select "copy to" which will copy the files/folders to the head revision

Hope that helps

Decompile .smali files on an APK

My recommendation is Virtuous Ten Studio. The tool is free but they suggest a donation. It combines all the necessary steps (unpacking APK, baksmaliing, decompiling, etc.) into one easy-to-use UI-based import process. Within five minutes you should have Java source code, less than it takes to figure out the command line options of one of the above mentioned tools.

Decompiling smali to Java is an inexact process, especially if the smali artifacts went through an obfuscator. You can find several decompilers on the web but only some of them are still maintained. Some will give you better decompiled code than others. Read "better" as in "more understandable" than others. Don't expect that the reverse-engineered Java code will compile out of the box. Virtuous Ten Studio comes with multiple free Java decompilers built-in so you can easily try out different decompilers (the "Generate Java source" step) to see which one gives you the best results, saving you the time to find those decompilers yourself and figure out how to use them. Amongst them is CFR, which is one of the few free and still maintained decompilers.

As output you receive, amongst other things, a folder structure that contains all the decompiled Java source code. You can then import this into IntelliJ IDEA or Eclipse for further editing, analysis (e.g. Go to definition, Find usages), etc.

MySQL delete multiple rows in one query conditions unique to each row

A slight extension to the answer given, so, hopefully useful to the asker and anyone else looking.

You can also SELECT the values you want to delete. But watch out for the Error 1093 - You can't specify the target table for update in FROM clause.

DELETE FROM
    orders_products_history
WHERE
    (branchID, action) IN (
    SELECT
        branchID,
        action
    FROM
        (
        SELECT
            branchID,
            action
        FROM
            orders_products_history
        GROUP BY
            branchID,
            action
        HAVING
            COUNT(*) > 10000
        ) a
    );

I wanted to delete all history records where the number of history records for a single action/branch exceed 10,000. And thanks to this question and chosen answer, I can.

Hope this is of use.

Richard.

Could not load type 'XXX.Global'

Ensure compiled dll of your project placed in proper bin folder.

In my case, when i have changed the compiled directory of our subproject to bin folder of our main project, it worked.

I am not able launch JNLP applications using "Java Web Start"?

Try Java Web Launcher, rather than Java Web Start Launcher. It worked for me.

Pointer to incomplete class type is not allowed

An "incomplete class" is one declared but not defined. E.g.

class Wielrenner;

as opposed to

class Wielrenner
{
    /* class members */
};

You need to #include "wielrenner.h" in dokter.ccp

Create a 3D matrix

If you want to define a 3D matrix containing all zeros, you write

A = zeros(8,4,20);

All ones uses ones, all NaN's uses NaN, all false uses false instead of zeros.

If you have an existing 2D matrix, you can assign an element in the "3rd dimension" and the matrix is augmented to contain the new element. All other new matrix elements that have to be added to do that are set to zero.

For example

B = magic(3); %# creates a 3x3 magic square
B(2,1,2) = 1; %# and you have a 3x3x2 array

Compare two Byte Arrays? (Java)

You can use both Arrays.equals() and MessageDigest.isEqual(). These two methods have some differences though.

MessageDigest.isEqual() is a time-constant comparison method and Arrays.equals() is non time-constant and it may bring some security issues if you use it in a security application.

The details for the difference can be read at Arrays.equals() vs MessageDigest.isEqual()

What do &lt; and &gt; stand for?

  • &lt; stands for the less-than sign: <
  • &gt; stands for the greater-than sign: >
  • &le; stands for the less-than or equals sign: =
  • &ge; stands for the greater-than or equals sign: =

show icon in actionbar/toolbar with AppCompat-v7 21

toolbar.setLogo(resize(logo, (int) Float.parseFloat(mContext.getResources().getDimension(R.dimen._120sdp) + ""), (int) Float.parseFloat(mContext.getResources().getDimension(R.dimen._35sdp) + "")));


public Drawable resize(Drawable image, int width, int height)
{
    Bitmap b = ((BitmapDrawable) image).getBitmap();
    Bitmap bitmapResized = Bitmap.createScaledBitmap(b, width, height, false);
    return new BitmapDrawable(getResources(), bitmapResized);
}

How to select an option from drop down using Selenium WebDriver C#?

This is how it works for me (selecting control by ID and option by text):

protected void clickOptionInList(string listControlId, string optionText)
{
     driver.FindElement(By.XPath("//select[@id='"+ listControlId + "']/option[contains(.,'"+ optionText +"')]")).Click();
}

use:

clickOptionInList("ctl00_ContentPlaceHolder_lbxAllRoles", "Tester");

Open popup and refresh parent page on close popup

In my case I opened a pop up window on click on linkbutton in parent page. To refresh parent on closing child using

window.opener.location.reload();

in child window caused re open the child window (Might be because of View State I guess. Correct me If I m wrong). So I decided not to reload page in parent and load the the page again assigning same url to it.

To avoid popup opening again after closing pop up window this might help,

window.onunload = function(){
    window.opener.location = window.opener.location;};

Set maxlength in Html Textarea

resize:none; This property fix your text area and bound it. you use this css property id your textarea.gave text area an id and on the behalf of that id you can use this css property.

How to start/stop/restart a thread in Java?

You can't restart a thread so your best option is to save the current state of the object at the time the thread was stopped and when operations need to continue on that object you can recreate that object using the saved and then start the new thread.

These two articles Swing Worker and Concurrency may help you determine the best solution for your problem.

How to save a Python interactive session?

After installing Ipython, and opening an Ipython session by running the command:

ipython

from your command line, just run the following Ipython 'magic' command to automatically log your entire Ipython session:

%logstart

This will create a uniquely named .py file and store your session for later use as an interactive Ipython session or for use in the script(s) of your choosing.

Converting Symbols, Accent Letters to English Alphabet

I'm late to the party, but after facing this issue today, I found this answer to be very good:

String asciiName = Normalizer.normalize(unicodeName, Normalizer.Form.NFD)
    .replaceAll("[^\\p{ASCII}]", "");

Reference: https://stackoverflow.com/a/16283863

Process.start: how to get the output?

You can log process output using below code:

ProcessStartInfo pinfo = new ProcessStartInfo(item);
pinfo.CreateNoWindow = false;
pinfo.UseShellExecute = true;
pinfo.RedirectStandardOutput = true;
pinfo.RedirectStandardInput = true;
pinfo.RedirectStandardError = true;
pinfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
var p = Process.Start(pinfo);
p.WaitForExit();
Process process = Process.Start(new ProcessStartInfo((item + '>' + item + ".txt"))
{
    UseShellExecute = false,
    RedirectStandardOutput = true
});
process.WaitForExit();
string output = process.StandardOutput.ReadToEnd();
if (process.ExitCode != 0) { 
}

No content to map due to end-of-input jackson parser

The problem for me was that I read the response twice as follows:

System.out.println(response.body().string());
getSucherResponse = objectMapper.readValue(response.body().string(), GetSucherResponse.class);

However, the response can only be read once as it is a stream.

pthread function from a class

You'll have to give pthread_create a function that matches the signature it's looking for. What you're passing won't work.

You can implement whatever static function you like to do this, and it can reference an instance of c and execute what you want in the thread. pthread_create is designed to take not only a function pointer, but a pointer to "context". In this case you just pass it a pointer to an instance of c.

For instance:

static void* execute_print(void* ctx) {
    c* cptr = (c*)ctx;
    cptr->print();
    return NULL;
}


void func() {

    ...

    pthread_create(&t1, NULL, execute_print, &c[0]);

    ...
}

How to convert a string to a date in sybase

Several ways to accomplish that but be aware that your DB date_format option & date_order option settings could affect the incoming format:

Select 
   cast('2008-09-16' as date)
   convert(date,'16/09/2008',103)
   date('2008-09-16')
from dummy;

How do you read CSS rule values with JavaScript?

This version will go through all of the stylesheets on a page. For my needs, the styles were usually in the 2nd to last of the 20+ stylesheets, so I check them backwards.

    var getStyle = function(className){
        var x, sheets,classes;
        for( sheets=document.styleSheets.length-1; sheets>=0; sheets-- ){
            classes = document.styleSheets[sheets].rules || document.styleSheets[sheets].cssRules;
            for(x=0;x<classes.length;x++) {
                if(classes[x].selectorText===className) {
                    return  (classes[x].cssText ? classes[x].cssText : classes[x].style.cssText);
                }
            }
        }
        return false;
    };

How to insert newline in string literal?

If I understand the question: Couple "\r\n" to get that new line below in a textbox. My example worked -

   string s1 = comboBox1.Text;     // s1 is the variable assigned to box 1, etc.
   string s2 = comboBox2.Text;

   string both = s1 + "\r\n" + s2;
   textBox1.Text = both;

A typical answer could be s1 s2 in the text box using defined type style.

Concatenation of strings in Lua

As other answers have said, the string concatenation operator in Lua is two dots.

Your simple example would be written like this:

filename = "checkbook"
filename = filename .. ".tmp"

However, there is a caveat to be aware of. Since strings in Lua are immutable, each concatenation creates a new string object and copies the data from the source strings to it. That makes successive concatenations to a single string have very poor performance.

The Lua idiom for this case is something like this:

function listvalues(s)
    local t = { }
    for k,v in ipairs(s) do
        t[#t+1] = tostring(v)
    end
    return table.concat(t,"\n")
end

By collecting the strings to be concatenated in an array t, the standard library routine table.concat can be used to concatenate them all up (along with a separator string between each pair) without unnecessary string copying.

Update: I just noticed that I originally wrote the code snippet above using pairs() instead of ipairs().

As originally written, the function listvalues() would indeed produce every value from the table passed in, but not in a stable or predictable order. On the other hand, it would include values who's keys were not positive integers in the span of 1 to #s. That is what pairs() does: it produces every single (key,value) pair stored in the table.

In most cases where you would be using something like listvaluas() you would be interested in preserving their order. So a call written as listvalues{13, 42, 17, 4} would produce a string containing those value in that order. However, pairs() won't do that, it will itemize them in some order that depends on the underlying implementation of the table data structure. It is known that the order not only depends on the keys, but also on the order in which the keys were inserted and other keys removed.

Of course ipairs() isn't a perfect answer either. It only enumerates those values of the table that form a "sequence". That is, those values who's keys form an unbroken block spanning from 1 to some upper bound, which is (usually) also the value returned by the # operator. (In many cases, the function ipairs() itself is better replaced by a simpler for loop that just counts from 1 to #s. This is the recommended practice in Lua 5.2 and in LuaJIT where the simpler for loop can be more efficiently implemented than the ipairs() iterator.)

If pairs() really is the right approach, then it is usually the case that you want to print both the key and the value. This reduces the concerns about order by making the data self-describing. Of course, since any Lua type (except nil and the floating point NaN) can be used as a key (and NaN can also be stored as a value) finding a string representation is left as an exercise for the student. And don't forget about trees and more complex structures of tables.

How to print object array in JavaScript?

Emm... Why not to use something like this?

_x000D_
_x000D_
function displayArrayObjects(arrayObjects) {_x000D_
        var len = arrayObjects.length, text = "";_x000D_
_x000D_
        for (var i = 0; i < len; i++) {_x000D_
            var myObject = arrayObjects[i];_x000D_
            _x000D_
            for (var x in myObject) {_x000D_
                text += ( x + ": " + myObject[x] + " ");_x000D_
            }_x000D_
            text += "<br/>";_x000D_
        }_x000D_
_x000D_
        document.getElementById("message").innerHTML = text;_x000D_
    }_x000D_
            _x000D_
            _x000D_
            var lineChartData = [{_x000D_
                date: new Date(2009, 10, 2),_x000D_
                value: 5_x000D_
            }, {_x000D_
                date: new Date(2009, 10, 25),_x000D_
                value: 30_x000D_
            }, {_x000D_
                date: new Date(2009, 10, 26),_x000D_
                value: 72,_x000D_
                customBullet: "images/redstar.png"_x000D_
            }];_x000D_
_x000D_
            displayArrayObjects(lineChartData);
_x000D_
<h4 id="message"></h4>
_x000D_
_x000D_
_x000D_

result:

date: Mon Nov 02 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 5 
date: Wed Nov 25 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 30 
date: Thu Nov 26 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 72 customBullet: images/redstar.png 

jsfiddle

How can one pull the (private) data of one's own Android app?

I had the same problem but solved it running following:

$ adb shell
$ run-as {app-package-name}
$ cd /data/data/{app-package-name}
$ chmod 777 {file}
$ cp {file} /mnt/sdcard/

After this you can run

$ adb pull /mnt/sdcard/{file}

Check if a file exists or not in Windows PowerShell?

cls

$exactadminfile = "C:\temp\files\admin" #First folder to check the file

$userfile = "C:\temp\files\user" #Second folder to check the file

$filenames=Get-Content "C:\temp\files\files-to-watch.txt" #Reading the names of the files to test the existance in one of the above locations

foreach ($filename in $filenames) {
  if (!(Test-Path $exactadminfile\$filename) -and !(Test-Path $userfile\$filename)) { #if the file is not there in either of the folder
    Write-Warning "$filename absent from both locations"
  } else {
    Write-Host " $filename  File is there in one or both Locations" #if file exists there at both locations or at least in one location
  }
}

"Input string was not in a correct format."

The error means that the string you're trying to parse an integer from doesn't actually contain a valid integer.

It's extremely unlikely that the text boxes will contain a valid integer immediately when the form is created - which is where you're getting the integer values. It would make much more sense to update a and b in the button click events (in the same way that you are in the constructor). Also, check out the Int.TryParse method - it's much easier to use if the string might not actually contain an integer - it doesn't throw an exception so it's easier to recover from.

How to save RecyclerView's scroll position using RecyclerView.State?

I Set variables in onCreate(), save scroll position in onPause() and set scroll position in onResume()

public static int index = -1;
public static int top = -1;
LinearLayoutManager mLayoutManager;

@Override
public void onCreate(Bundle savedInstanceState)
{
    //Set Variables
    super.onCreate(savedInstanceState);
    cRecyclerView = ( RecyclerView )findViewById(R.id.conv_recycler);
    mLayoutManager = new LinearLayoutManager(this);
    cRecyclerView.setHasFixedSize(true);
    cRecyclerView.setLayoutManager(mLayoutManager);

}

@Override
public void onPause()
{
    super.onPause();
    //read current recyclerview position
    index = mLayoutManager.findFirstVisibleItemPosition();
    View v = cRecyclerView.getChildAt(0);
    top = (v == null) ? 0 : (v.getTop() - cRecyclerView.getPaddingTop());
}

@Override
public void onResume()
{
    super.onResume();
    //set recyclerview position
    if(index != -1)
    {
        mLayoutManager.scrollToPositionWithOffset( index, top);
    }
}

What is the difference between Forking and Cloning on GitHub?

When you say you are Forking a repository you are basically creating a copy of the repository under your GitHub ID. The main point to note here is that any changes made to the original repository will be reflected back to your forked repositories(you need to fetch and rebase). However, if you make any changes to your forked repository you will have to explicitly create a pull request to the original repository. If your pull request is approved by the administrator of the original repository, then your changes will be committed/merged with the existing original code-base. Until then, your changes will be reflected only in the copy you forked.

In short:

The Fork & Pull Model lets anyone fork an existing repository and push changes to their personal fork without requiring access be granted to the source repository. The changes must then be pulled into the source repository by the project maintainer.

Note that after forking you can clone your repository (the one under your name) locally on your machine. Make changes in it and push it to your forked repository. However, to reflect your changes in the original repository your pull request must be approved.

Couple of other interesting dicussions -

Are git forks actually git clones?

How do I update a GitHub forked repository?

How to install 2 Anacondas (Python 2 and 3) on Mac OS

This may be helpful if you have more than one python versions installed and dont know how to tell your ide's to use a specific version.

  1. Install anaconda. Latest version can be found here
  2. Open the navigator by typing anaconda-navigator in terminal
  3. Open environments. Click on create and then choose your python version in that.
  4. Now new environment will be created for your python version and you can install the IDE's(which are listed there) just by clicking install in that.
  5. Launch the IDE in your environment so that that IDE will use the specified version for that environment.

Hope it helps!!

Match groups in Python

Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), we can now capture the condition value re.search(pattern, statement) in a variable (let's all it match) in order to both check if it's not None and then re-use it within the body of the condition:

if match := re.search('I love (\w+)', statement):
  print(f'He loves {match.group(1)}')
elif match := re.search("Ich liebe (\w+)", statement):
  print(f'Er liebt {match.group(1)}')
elif match := re.search("Je t'aime (\w+)", statement):
  print(f'Il aime {match.group(1)}')

T-SQL CASE Clause: How to specify WHEN NULL

The problem is that null is not considered equal to itself, hence the clause never matches.

You need to check for null explicitly:

SELECT CASE WHEN last_name is NULL THEN first_name ELSE first_name + ' ' + last_name

Scala: what is the best way to append an element to an Array?

The easiest might be:

Array(1, 2, 3) :+ 4

Actually, Array can be implcitly transformed in a WrappedArray

How to add external fonts to android application

To implement you need use Typeface go through with sample below

Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Roboto/Roboto-Regular.ttf");
for (View view : allViews)
{
   if (view instanceof TextView) 
   {
      TextView textView = (TextView) view;
      textView.setTypeface(typeface);
      }
   }
}

What is a serialVersionUID and why should I use it?

As for an example where the missing serialVersionUID might cause a problem:

I'm working on this Java EE application that is composed of a Web module that uses an EJB module. The web module calls the EJB module remotely and passes a POJO that implements Serializable as an argument.

This POJO's class was packaged inside the EJB jar and inside it's own jar in the WEB-INF/lib of the web module. They're actually the same class, but when I package the EJB module I unpack this POJO's jar to pack it together with the EJB module.

The call to the EJB was failing with the Exception below because I hadn't declared its serialVersionUID:

Caused by: java.io.IOException: Mismatched serialization UIDs : Source
 (Rep.
 IDRMI:com.hordine.pedra.softbudget.domain.Budget:5CF7CE11E6810A36:04A3FEBED5DA4588)
 = 04A3FEBED5DA4588 whereas Target (Rep. ID RMI:com.hordine.pedra.softbudget.domain.Budget:7AF5ED7A7CFDFF31:6227F23FA74A9A52)
 = 6227F23FA74A9A52

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

Higher ranked answers have a few inherent issues including the use of legacy javascript, incorrect ordering or with only support for 2 duplicated items.

Here's a modern solution which fixes those problems:

const arrayNonUniq = array => {
    if (!Array.isArray(array)) {
        throw new TypeError("An array must be provided!")
    }

    return array.filter((value, index) => array.indexOf(value) === index && array.lastIndexOf(value) !== index)
}

arrayNonUniq([1, 1, 2, 3, 3])
//=> [1, 3]

arrayNonUniq(["foo", "foo", "bar", "foo"])
//=> ['foo']

You can also use the npm package array-non-uniq.

Push Notifications in Android Platform

You can use Pusher

It's a hosted service that makes it super-easy to add real-time data and functionality to web and mobile applications.
Pusher offers libraries to integrate into all the main runtimes and frameworks.

PHP, Ruby, Python, Java, .NET, Go and Node on the server
JavaScript, Objective-C (iOS) and Java (Android) on the client.

What is the difference between vmalloc and kmalloc?

On a 32-bit system, kmalloc() returns the kernel logical address (its a virtual address though) which has the direct mapping (actually with constant offset) to physical address. This direct mapping ensures that we get a contiguous physical chunk of RAM. Suited for DMA where we give only the initial pointer and expect a contiguous physical mapping thereafter for our operation.

vmalloc() returns the kernel virtual address which in turn might not be having a contiguous mapping on physical RAM. Useful for large memory allocation and in cases where we don't care about that the memory allocated to our process is continuous also in Physical RAM.

Pure CSS scroll animation

You can use my script from CodePen by just wrapping all the content within a .levit-container DIV.

~function  () {
    function Smooth () {
        this.$container = document.querySelector('.levit-container');
        this.$placeholder = document.createElement('div');
    }

    Smooth.prototype.init = function () {
        var instance = this;

        setContainer.call(instance);
        setPlaceholder.call(instance);
        bindEvents.call(instance);
    }

    function bindEvents () {
        window.addEventListener('scroll', handleScroll.bind(this), false);
    }

    function setContainer () {
        var style = this.$container.style;

        style.position = 'fixed';
        style.width = '100%';
        style.top = '0';
        style.left = '0';
        style.transition = '0.5s ease-out';
    }

    function setPlaceholder () {
        var instance = this,
                $container = instance.$container,
                $placeholder = instance.$placeholder;

        $placeholder.setAttribute('class', 'levit-placeholder');
        $placeholder.style.height = $container.offsetHeight + 'px';
        document.body.insertBefore($placeholder, $container);
    }

    function handleScroll () {
        this.$container.style.transform = 'translateZ(0) translateY(' + (window.scrollY * (- 1)) + 'px)';
    }

    var smooth = new Smooth();
    smooth.init();
}();

https://codepen.io/acauamontiel/pen/zxxebb?editors=0010

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

In the first example, you are reassigning the variable a, while in the second one you are modifying the data in-place, using the += operator.

See the section about 7.2.1. Augmented assignment statements :

An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

+= operator calls __iadd__. This function makes the change in-place, and only after its execution, the result is set back to the object you are "applying" the += on.

__add__ on the other hand takes the parameters and returns their sum (without modifying them).

Circular gradient in android

You can also do it in code if you need more control, for example multiple colors and positioning. Here is my Kotlin snippet to create a drawable radial gradient:

object ShaderUtils {
    private class RadialShaderFactory(private val colors: IntArray, val positionX: Float,
                                      val positionY: Float, val size: Float): ShapeDrawable.ShaderFactory() {

        override fun resize(width: Int, height: Int): Shader {
            return RadialGradient(
                    width * positionX,
                    height * positionY,
                    minOf(width, height) * size,
                    colors,
                    null,
                    Shader.TileMode.CLAMP)
        }
    }

    fun radialGradientBackground(vararg colors: Int, positionX: Float = 0.5f, positionY: Float = 0.5f,
                                 size: Float = 1.0f): PaintDrawable {
        val radialGradientBackground = PaintDrawable()
        radialGradientBackground.shape = RectShape()
        radialGradientBackground.shaderFactory = RadialShaderFactory(colors, positionX, positionY, size)
        return radialGradientBackground
    }
}

Basic usage (but feel free to adjust with additional params):

view.background = ShaderUtils.radialGradientBackground(Color.TRANSPARENT, BLACK)

Convert serial.read() into a useable string using Arduino?

I was asking the same question myself and after some research I found something like that.

It works like a charm for me. I use it to remote control my Arduino.

// Buffer to store incoming commands from serial port
String inData;
    
void setup() {
    Serial.begin(9600);
    Serial.println("Serial conection started, waiting for instructions...");
}
    
void loop() {
    while (Serial.available() > 0)
    {
        char recieved = Serial.read();
        inData += recieved; 
    
        // Process message when new line character is recieved
        if (recieved == '\n')
        {
            Serial.print("Arduino Received: ");
            Serial.print(inData);
                
            // You can put some if and else here to process the message juste like that:

            if(inData == "+++\n"){ // DON'T forget to add "\n" at the end of the string.
              Serial.println("OK. Press h for help.");
            }   

    
            inData = ""; // Clear recieved buffer
        }
    }
}

Generating a random hex color code with PHP

$color = sprintf("#%06x",rand(0,16777215));

How can I format bytes a cell in Excel as KB, MB, GB etc?

Paste this next to your values(bytes) and this will automatically change it to whatever your size of value is.

=IF(G10>=1099511627776,CONCATENATE(ROUND((G10/1024/1024/1024/1024),1)," TB"),IF(G10>=1073741824,CONCATENATE(ROUND((G10/1024/1024/1024),1)," GB"),IF(G10>=1048576,CONCATENATE(ROUND((G10/1024/1024),1)," MB"),IF(G10>=1024,CONCATENATE(ROUND((G10/1024),1)," KB"),IF(G10>=1,CONCATENATE((G10)," BYTES"),0)))))

Get Max value from List<myType>

Simplest is actually just Age.Max(), you don't need any more code.

Trying to use fetch and pass in mode: no-cors

Very easy solution (2 min to config) is to use local-ssl-proxy package from npm

The usage is straight pretty forward:
1. Install the package: npm install -g local-ssl-proxy
2. While running your local-server mask it with the local-ssl-proxy --source 9001 --target 9000

P.S: Replace --target 9000 with the -- "number of your port" and --source 9001 with --source "number of your port +1"

What is the difference between a cer, pvk, and pfx file?

I actually came across something like this not too long ago... check it out over on msdn (see the first answer)

in summary:

.cer - certificate stored in the X.509 standard format. This certificate contains information about the certificate's owner... along with public and private keys.

.pvk - files are used to store private keys for code signing. You can also create a certificate based on .pvk private key file.

.pfx - stands for personal exchange format. It is used to exchange public and private objects in a single file. A pfx file can be created from .cer file. Can also be used to create a Software Publisher Certificate.

I summarized the info from the page based on the suggestion from the comments.

git visual diff between branches

If you use the excellent WebStorm editor, you can compare with any branch you'd like:

Webstorm git compare

Create an array with random values

Refer below :-

let arr = Array.apply(null, {length: 1000}).map(Function.call, Math.random)
/* will create array with 1000 elements */

What happens when a duplicate key is put into a HashMap?

The prior value for the key is dropped and replaced with the new one.

If you'd like to keep all the values a key is given, you might consider implementing something like this:

import org.apache.commons.collections.MultiHashMap;
import java.util.Set;
import java.util.Map;
import java.util.Iterator;
import java.util.List;
public class MultiMapExample {

   public static void main(String[] args) {
      MultiHashMap mp=new MultiHashMap();
      mp.put("a", 10);
      mp.put("a", 11);
      mp.put("a", 12);
      mp.put("b", 13);
      mp.put("c", 14);
      mp.put("e", 15);
      List list = null;

      Set set = mp.entrySet();
      Iterator i = set.iterator();
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         list=(List)mp.get(me.getKey());

         for(int j=0;j<list.size();j++)
         {
          System.out.println(me.getKey()+": value :"+list.get(j));
         }
      }
   }
}

Convert INT to VARCHAR SQL

You can use CAST function:

SELECT CAST(your_column_name AS varchar(10)) FROM your_table_name

Sending data back to the Main Activity in Android

Sending Data Back

It helps me to see things in context. Here is a complete simple project for sending data back. Rather than providing the xml layout files, here is an image.

enter image description here

Main Activity

  • Start the Second Activity with startActivityForResult, providing it an arbitrary result code.
  • Override onActivityResult. This is called when the Second Activity finishes. You can make sure that it is actually the Second Activity by checking the request code. (This is useful when you are starting multiple different activities from the same main activity.)
  • Extract the data you got from the return Intent. The data is extracted using a key-value pair.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private static final int SECOND_ACTIVITY_REQUEST_CODE = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // "Go to Second Activity" button click
    public void onButtonClick(View view) {

        // Start the SecondActivity
        Intent intent = new Intent(this, SecondActivity.class);
        startActivityForResult(intent, SECOND_ACTIVITY_REQUEST_CODE);
    }

    // This method is called when the second activity finishes
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Check that it is the SecondActivity with an OK result
        if (requestCode == SECOND_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {

                // Get String data from Intent
                String returnString = data.getStringExtra("keyName");

                // Set text view with string
                TextView textView = (TextView) findViewById(R.id.textView);
                textView.setText(returnString);
            }
        }
    }
}

Second Activity

  • Put the data that you want to send back to the previous activity into an Intent. The data is stored in the Intent using a key-value pair.
  • Set the result to RESULT_OK and add the intent holding your data.
  • Call finish() to close the Second Activity.

SecondActivity.java

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }

    // "Send text back" button click
    public void onButtonClick(View view) {

        // Get the text from the EditText
        EditText editText = (EditText) findViewById(R.id.editText);
        String stringToPassBack = editText.getText().toString();

        // Put the String to pass back into an Intent and close this activity
        Intent intent = new Intent();
        intent.putExtra("keyName", stringToPassBack);
        setResult(RESULT_OK, intent);
        finish();
    }
}

Other notes

  • If you are in a Fragment it won't know the meaning of RESULT_OK. Just use the full name: Activity.RESULT_OK.

See also

How to read large text file on windows?

Definitely EditPad Lite !

It's extremely fast not just while opening files, but also functions like "Replace All", trimming of leading/trailing whitespaces or converting content to lowercase are very fast.

And it is also very similar to Notepad++ ;)

Generate random numbers following a normal distribution in C/C++

1) Graphically intuitive way you can generate Gaussian random numbers is by using something similar to the Monte Carlo method. You would generate a random point in a box around the Gaussian curve using your pseudo-random number generator in C. You can calculate if that point is inside or underneath the Gaussian distribution using the equation of the distribution. If that point is inside the Gaussian distribution, then you have got your Gaussian random number as the x value of the point.

This method isn't perfect because technically the Gaussian curve goes on towards infinity, and you couldn't create a box that approaches infinity in the x dimension. But the Guassian curve approaches 0 in the y dimension pretty fast so I wouldn't worry about that. The constraint of the size of your variables in C may be more of a limiting factor to your accuracy.

2) Another way would be to use the Central Limit Theorem which states that when independent random variables are added, they form a normal distribution. Keeping this theorem in mind, you can approximate a Gaussian random number by adding a large amount of independent random variables.

These methods aren't the most practical, but that is to be expected when you don't want to use a preexisting library. Keep in mind this answer is coming from someone with little or no calculus or statistics experience.

How to properly compare two Integers in Java?

No, == between Integer, Long etc will check for reference equality - i.e.

Integer x = ...;
Integer y = ...;

System.out.println(x == y);

this will check whether x and y refer to the same object rather than equal objects.

So

Integer x = new Integer(10);
Integer y = new Integer(10);

System.out.println(x == y);

is guaranteed to print false. Interning of "small" autoboxed values can lead to tricky results:

Integer x = 10;
Integer y = 10;

System.out.println(x == y);

This will print true, due to the rules of boxing (JLS section 5.1.7). It's still reference equality being used, but the references genuinely are equal.

If the value p being boxed is an integer literal of type int between -128 and 127 inclusive (§3.10.1), or the boolean literal true or false (§3.10.3), or a character literal between '\u0000' and '\u007f' inclusive (§3.10.4), then let a and b be the results of any two boxing conversions of p. It is always the case that a == b.

Personally I'd use:

if (x.intValue() == y.intValue())

or

if (x.equals(y))

As you say, for any comparison between a wrapper type (Integer, Long etc) and a numeric type (int, long etc) the wrapper type value is unboxed and the test is applied to the primitive values involved.

This occurs as part of binary numeric promotion (JLS section 5.6.2). Look at each individual operator's documentation to see whether it's applied. For example, from the docs for == and != (JLS 15.21.1):

If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).

and for <, <=, > and >= (JLS 15.20.1)

The type of each of the operands of a numerical comparison operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs. Binary numeric promotion is performed on the operands (§5.6.2). If the promoted type of the operands is int or long, then signed integer comparison is performed; if this promoted type is float or double, then floating-point comparison is performed.

Note how none of this is considered as part of the situation where neither type is a numeric type.

AngularJS passing data to $http.get request

Solution for those who are interested in sending params and headers in GET request

$http.get('https://www.your-website.com/api/users.json', {
        params:  {page: 1, limit: 100, sort: 'name', direction: 'desc'},
        headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
    }
)
.then(function(response) {
    // Request completed successfully
}, function(x) {
    // Request error
});

Complete service example will look like this

var mainApp = angular.module("mainApp", []);

mainApp.service('UserService', function($http, $q){

   this.getUsers = function(page = 1, limit = 100, sort = 'id', direction = 'desc') {

        var dfrd = $q.defer();
        $http.get('https://www.your-website.com/api/users.json', 
            {
                params:{page: page, limit: limit, sort: sort, direction: direction},
                headers: {Authorization: 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
            }
        )
        .then(function(response) {
            if ( response.data.success == true ) { 

            } else {

            }
        }, function(x) {

            dfrd.reject(true);
        });
        return dfrd.promise;
   }

});

How to encode URL to avoid special characters in Java?

I also spent quite some time with this issue, so that's my solution:

String urlString2Decode = "http://www.test.com/äüö/path with blanks/";
String decodedURL = URLDecoder.decode(urlString2Decode, "UTF-8");
URL url = new URL(decodedURL);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
String decodedURLAsString = uri.toASCIIString();

Mean filter for smoothing images in Matlab

I = imread('peppers.png');
H = fspecial('average', [5 5]);
I = imfilter(I, H);
imshow(I)

Note that filters can be applied to intensity images (2D matrices) using filter2, while on multi-dimensional images (RGB images or 3D matrices) imfilter is used.

Also on Intel processors, imfilter can use the Intel Integrated Performance Primitives (IPP) library to accelerate execution.

Compare dates with javascript

Because of your date format, you can use this code:

if(parseInt(first.replace(/-/g,""),10) > parseInt(second.replace(/-/g,""),10)){
   //...
}

It will check whether 20121121 number is bigger than 20121103 or not.

Postgresql 9.2 pg_dump version mismatch

Macs have a builtin /usr/bin/pg_dump command that is used as default.

With the postgresql install you get another binary at /Library/PostgreSQL/<version>/bin/pg_dump

Getting fb.me URL

Facebook uses Bit.ly's services to shorten links from their site. While pages that have a username turns into "fb.me/<username>", other links associated with Facebook turns into "on.fb.me/*****". To you use the on.fb.me service, just use your Bit.ly account. Note that if you change the default link shortener on your Bit.ly account to j.mp from bit.ly this service won't work.

Pandas: Return Hour from Datetime Column Directly

You can use a lambda expression, e.g:

sales['time_hour'] = sales.timestamp.apply(lambda x: x.hour)

What are some examples of commonly used practices for naming git branches?

Why does it take three branches/merges for every task? Can you explain more about that?

If you use a bug tracking system you can use the bug number as part of the branch name. This will keep the branch names unique, and you can prefix them with a short and descriptive word or two to keep them human readable, like "ResizeWindow-43523". It also helps make things easier when you go to clean up branches, since you can look up the associated bug. This is how I usually name my branches.

Since these branches are eventually getting merged back into master, you should be safe deleting them after you merge. Unless you're merging with --squash, the entire history of the branch will still exist should you ever need it.

When to use 'raise NotImplementedError'?

You might want to you use the @property decorator,

>>> class Foo():
...     @property
...     def todo(self):
...             raise NotImplementedError("To be implemented")
... 
>>> f = Foo()
>>> f.todo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in todo
NotImplementedError: To be implemented

Filter by process/PID in Wireshark

Use strace is more suitable for this situation.

strace -f -e trace=network -s 10000 -p <PID>;

options -f to also trace all forked processes, -e trace=netwrok to only filter network system-call and -s to display string length up to 10000 char.

You can also only trace certain calls like send,recv, read operations.

strace -f -e trace=send,recv,read -s 10000 -p <PID>;

Converting Columns into rows with their respective data in sql server

Sound like you want to UNPIVOT

Sample from books online:

--Create the table and insert values as portrayed in the previous example.
CREATE TABLE pvt (VendorID int, Emp1 int, Emp2 int,
    Emp3 int, Emp4 int, Emp5 int);
GO
INSERT INTO pvt VALUES (1,4,3,5,4,4);
INSERT INTO pvt VALUES (2,4,1,5,5,5);
INSERT INTO pvt VALUES (3,4,3,5,4,4);
INSERT INTO pvt VALUES (4,4,2,5,5,4);
INSERT INTO pvt VALUES (5,5,1,5,5,5);
GO
--Unpivot the table.
SELECT VendorID, Employee, Orders
FROM 
   (SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5
   FROM pvt) p
UNPIVOT
   (Orders FOR Employee IN 
      (Emp1, Emp2, Emp3, Emp4, Emp5)
)AS unpvt;
GO

Returns:

VendorID   Employee   Orders
---------- ---------- ------
1          Emp1       4
1          Emp2       3
1          Emp3       5
1          Emp4       4
1          Emp5       4
2          Emp1       4
2          Emp2       1
2          Emp3       5
2          Emp4       5
2          Emp5       5

see also: Unpivot SQL thingie and the unpivot tag

How do you strip a character out of a column in SQL Server?

Take a look at the following function - REPLACE():

select replace(DataColumn, StringToReplace, NewStringValue)

//example to replace the s in test with the number 1
select replace('test', 's', '1')
//yields te1t

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

EDIT
If you want to remove a string, simple use the replace function with an empty string as the third parameter like:

select replace(DataColumn, 'StringToRemove', '')

Reference an Element in a List of Tuples

Here's a quick example:

termList = []
termList.append(('term1', [1,2,3,4]))
termList.append(('term2', [5,6,7,8]))
termList.append(('term3', [9,10,11,12]))

result = [x[1] for x in termList if x[0] == 'term3']

print(result)

Open two instances of a file in a single Visual Studio session

You can use the Windows ? New Window option to duplicate the current window. See more at: Why I like Visual Studio 2010? Undock Windows

How do I tell a Python script to use a particular version

Perhaps not exactly what you asked, but I find this to be useful to put at the start of my programs:

import sys

if sys.version_info[0] < 3:
    raise Exception("Python 3 or a more recent version is required.")

How to programmatically disable page scrolling with jQuery

I just provide a little tuning to the solution by tfe. In particular, I added some additional control to ensure that there is no shifting of the page content (aka page shift) when the scrollbar is set to hidden.

Two Javascript functions lockScroll() and unlockScroll() can be defined, respectively, to lock and unlock the page scroll.

function lockScroll(){
    $html = $('html'); 
    $body = $('body'); 
    var initWidth = $body.outerWidth();
    var initHeight = $body.outerHeight();

    var scrollPosition = [
        self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
        self.pageYOffset || document.documentElement.scrollTop  || document.body.scrollTop
    ];
    $html.data('scroll-position', scrollPosition);
    $html.data('previous-overflow', $html.css('overflow'));
    $html.css('overflow', 'hidden');
    window.scrollTo(scrollPosition[0], scrollPosition[1]);   

    var marginR = $body.outerWidth()-initWidth;
    var marginB = $body.outerHeight()-initHeight; 
    $body.css({'margin-right': marginR,'margin-bottom': marginB});
} 

function unlockScroll(){
    $html = $('html');
    $body = $('body');
    $html.css('overflow', $html.data('previous-overflow'));
    var scrollPosition = $html.data('scroll-position');
    window.scrollTo(scrollPosition[0], scrollPosition[1]);    

    $body.css({'margin-right': 0, 'margin-bottom': 0});
}

where I assumed that the <body> has no initial margin.

Notice that, while the above solution works in most of the practical cases, it is not definitive since it needs some further customization for pages that include, for instance, an header with position:fixed. Let's go into this special case with an example. Suppose to have

<body>
<div id="header">My fixedheader</div>
<!--- OTHER CONTENT -->
</body>

with

#header{position:fixed; padding:0; margin:0; width:100%}

Then, one should add the following in functions lockScroll() and unlockScroll():

function lockScroll(){
    //Omissis   


    $('#header').css('margin-right', marginR);
} 

function unlockScroll(){
    //Omissis   

    $('#header').css('margin-right', 0);
}

Finally, take care of some possible initial value for the margins or paddings.

What is the difference between a static and a non-static initialization code block

The static code block can be used to instantiate or initialize class variables (as opposed to object variables). So declaring "a" static means that is only one shared by all Test objects, and the static code block initializes "a" only once, when the Test class is first loaded, no matter how many Test objects are created.

Function vs. Stored Procedure in SQL Server

Start with functions that return a single value. The nice thing is you can put frequently used code into a function and return them as a column in a result set.

Then, you might use a function for a parameterized list of cities. dbo.GetCitiesIn("NY") That returns a table that can be used as a join.

It's a way of organizing code. Knowing when something is reusable and when it is a waste of time is something only gained through trial and error and experience.

Also, functions are a good idea in SQL Server. They are faster and can be quite powerful. Inline and direct selects. Careful not to overuse.

How to concatenate columns in a Postgres SELECT?

The problem was in nulls in the values; then the concatenation does not work with nulls. The solution is as follows:

SELECT coalesce(a, '') || coalesce(b, '') FROM foo;

Why does multiplication repeats the number several times?

It's the difference between strings and integers. See:

>>> "1" * 9
'111111111'

>>> 1 * 9
9

Returning Arrays in Java

It is returning the array, but all returning something (including an Array) does is just what it sounds like: returns the value. In your case, you are getting the value of numbers(), which happens to be an array (it could be anything and you would still have this issue), and just letting it sit there.

When a function returns anything, it is essentially replacing the line in which it is called (in your case: numbers();) with the return value. So, what your main method is really executing is essentially the following:

public static void main(String[] args) {
    {1,2,3};
}

Which, of course, will appear to do nothing. If you wanted to do something with the return value, you could do something like this:

public static void main(String[] args){
    int[] result = numbers();
    for (int i=0; i<result.length; i++) {
        System.out.print(result[i]+" ");
    }
}

random.seed(): What does it do?

# Simple Python program to understand random.seed() importance

import random

random.seed(10)

for i in range(5):    
    print(random.randint(1, 100))

Execute the above program multiple times...

1st attempt: prints 5 random integers in the range of 1 - 100

2nd attempt: prints same 5 random numbers appeared in the above execution.

3rd attempt: same

.....So on

Explanation: Every time we are running the above program we are setting seed to 10, then random generator takes this as a reference variable. And then by doing some predefined formula, it generates a random number.

Hence setting seed to 10 in the next execution again sets reference number to 10 and again the same behavior starts...

As soon as we reset the seed value it gives the same plants.

Note: Change the seed value and run the program, you'll see a different random sequence than the previous one.

How do I know the script file name in a Bash script?

this="$(dirname "$(realpath "$BASH_SOURCE")")"

This resolves symbolic links (realpath does that), handles spaces (double quotes do this), and will find the current script name even when sourced (. ./myscript) or called by other scripts ($BASH_SOURCE handles that). After all that, it is good to save this in a environment variable for re-use or for easy copy elsewhere (this=)...

Pause Console in C++ program

This works for me.

void pause()
{
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    std::string dummy;
    std::cout << "Press any key to continue . . .";
    std::getline(std::cin, dummy);
}

How do I drop a function if it already exists?

If you want to use the SQL ISO standard INFORMATION_SCHEMA and not the SQL Server-specific sysobjects, you can do this:

IF EXISTS (
    SELECT ROUTINE_NAME FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_NAME = N'FunctionName'
)
   DROP FUNCTION [dbo].[FunctionName]
GO

Are multiple `.gitignore`s frowned on?

There are many scenarios where you want to commit a directory to your Git repo but without the files in it, for example the logs, cache, uploads directories etc.

So what I always do is to add a .gitignore file in those directories with the following content:

*
!.gitignore

With this .gitignore file, Git will not track any files in those directories yet still allow me to add the .gitignore file and hence the directory itself to the repo.

How can I give the Intellij compiler more heap space?

Current version:

Settings (Preferences on Mac) | Build, Execution, Deployment | Compiler | Build process heap size.

Older versions:

Settings (Preferences on Mac) | Compiler | Java Compiler | Maximum heap size.

Compiler runs in a separate JVM by default so IDEA heap settings that you set in idea.vmoptions have no effect on the compiler.

JBoss vs Tomcat again

I'd certainly look to TomEE since the idea behind is to keep Tomcat bringing all the JavaEE 6 integration missing by default. That's a kind of very good compromise

What is "android:allowBackup"?

This is not explicitly mentioned, but based on the following docs, I think it is implied that an app needs to declare and implement a BackupAgent in order for data backup to work, even in the case when allowBackup is set to true (which is the default value).

http://developer.android.com/reference/android/R.attr.html#allowBackup http://developer.android.com/reference/android/app/backup/BackupManager.html http://developer.android.com/guide/topics/data/backup.html

Access files stored on Amazon S3 through web browser

I had the same problem and I fixed it by using the

  1. new context menu "Make Public".
  2. Go to https://console.aws.amazon.com/s3/home,
  3. select the bucket and then for each Folder or File (or multiple selects) right click and
  4. "make public"

If Browser is Internet Explorer: run an alternative script instead

You can do something like this to include IE-specific javascript:

<!--[IF IE]>
    <script type="text/javascript">
        // IE stuff
    </script>
<![endif]-->

Logging best practices

I have to join the chorus recommending log4net, in my case coming from a platform flexibility (desktop .Net/Compact Framework, 32/64-bit) point of view.

However, wrapping it in a private-label API is a major anti-pattern. log4net.ILogger is the .Net counterpart of the Commons Logging wrapper API already, so coupling is already minimized for you, and since it is also an Apache library, that's usually not even a concern because you're not giving up any control: fork it if you must.

Most house wrapper libraries I've seen also commit one or more of a litany of faults:

  1. Using a global singleton logger (or equivalently a static entry point) which loses the fine resolution of the recommended logger-per-class pattern for no other selectivity gain.
  2. Failing to expose the optional Exception argument, leading to multiple problems:
    • It makes an exception logging policy even more difficult to maintain, so nothing is done consistently with exceptions.
    • Even with a consistent policy, formatting the exception away into a string loses data prematurely. I've written a custom ILayout decorator that performs detailed drill-down on an exception to determine the chain of events.
  3. Failing to expose the IsLevelEnabled properties, which discards the ability to skip formatting code when areas or levels of logging are turned off.

Is there any simple way to convert .xls file to .csv file? (Excel)

I need to do the same thing. I ended up with something similar to Kman

       static void ExcelToCSVCoversion(string sourceFile,  string targetFile)
    {
        Application rawData = new Application();

        try
        {
            Workbook workbook = rawData.Workbooks.Open(sourceFile);
            Worksheet ws = (Worksheet) workbook.Sheets[1];
            ws.SaveAs(targetFile, XlFileFormat.xlCSV);
            Marshal.ReleaseComObject(ws);
        }

        finally
        {
            rawData.DisplayAlerts = false;
            rawData.Quit();
            Marshal.ReleaseComObject(rawData);
        }


        Console.WriteLine();
        Console.WriteLine($"The excel file {sourceFile} has been converted into {targetFile} (CSV format).");
        Console.WriteLine();
    }

If there are multiple sheets this is lost in the conversion but you could loop over the number of sheets and save each one as csv.

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

There are two problems in your code:

  • The property is called visibility and not visiblity.
  • It is not a property of the element itself but of its .style property.

It's easy to fix. Simple replace this:

document.getElementById("remember").visiblity

with this:

document.getElementById("remember").style.visibility

grep a tab in UNIX

On ksh I used

grep "[^I]" testfile

Git: Find the most recent common ancestor of two branches

You are looking for git merge-base. Usage:

$ git merge-base branch2 branch3
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

The server encountered an internal error or misconfiguration and was unable to complete your request

Check your servers error log, typically /var/log/apache2/error.log.

How to import a SQL Server .bak file into MySQL?

In this problem, the answer is not updated in a timely. So it's happy to say that in 2020 Migrating to MsSQL into MySQL is that much easy. An online converter like RebaseData will do your job with one click. You can just upload your .bak file which is from MsSQL and convert it into .sql format which is readable to MySQL.

Additional note: This can not only convert your .bak files but also this site is for all types of Database migrations that you want.

JavaScript Infinitely Looping slideshow with delays?

You can infinitely loop easily enough via recursion.

function it_keeps_going_and_going_and_going() {
  it_keeps_going_and_going_and_going();
}

it_keeps_going_and_going_and_going()

$date + 1 year?

I prefer the OO approach:

$date = new \DateTimeImmutable('today'); //'today' gives midnight, leave blank for current time.
$futureDate = $date->add(\DateInterval::createFromDateString('+1 Year'))

Use DateTimeImmutable otherwise you will modify the original date too! more on DateTimeImmutable: http://php.net/manual/en/class.datetimeimmutable.php


If you just want from todays date then you can always do:

new \DateTimeImmutable('-1 Month');

How to use http.client in Node.js if there is basic authorization

var http = require("http");
var url = "http://api.example.com/api/v1/?param1=1&param2=2";

var options = {
    host: "http://api.example.com",
    port: 80,
    method: "GET",
    path: url,//I don't know for some reason i have to use full url as a path
    auth: username + ':' + password
};

http.get(options, function(rs) {
    var result = "";
    rs.on('data', function(data) {
        result += data;
    });
    rs.on('end', function() {
        console.log(result);
    });
});

I want to align the text in a <td> to the top

https://developer.mozilla.org/en/CSS/vertical-align

<table style="height: 275px; width: 188px">
    <tr>
        <td style="width: 259px; vertical-align:top">
            main page
        </td>
    </tr>
</table>

?

Linux: copy and create destination dir if it does not exist

Shell function that does what you want, calling it a "bury" copy because it digs a hole for the file to live in:

bury_copy() { mkdir -p `dirname $2` && cp "$1" "$2"; }

How to update a claim in ASP.NET Identity?

    if (HttpContext.User.Identity is ClaimsIdentity identity)
        {
            identity.RemoveClaim(identity.FindFirst("userId"));
            identity.AddClaim(new Claim("userId", userInfo?.id.ToString()));
            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(HttpContext.User.Identity));
        }

Why are #ifndef and #define used in C++ header files?

#ifndef <token>
/* code */
#else
/* code to include if the token is defined */
#endif

#ifndef checks whether the given token has been #defined earlier in the file or in an included file; if not, it includes the code between it and the closing #else or, if no #else is present, #endif statement. #ifndef is often used to make header files idempotent by defining a token once the file has been included and checking that the token was not set at the top of that file.

#ifndef _INCL_GUARD
#define _INCL_GUARD
#endif

How to kill an application with all its activities?

My understanding of the Android application framework is that this is specifically not permitted. An application is closed automatically when it contains no more current activities. Trying to create a "kill" button is apparently contrary to the intended design of the application system.

To get the sort of effect you want, you could initiate your various activities with startActivityForResult(), and have the exit button send back a result which tells the parent activity to finish(). That activity could then send the same result as part of its onDestroy(), which would cascade back to the main activity and result in no running activities, which should cause the app to close.

Contain an image within a div?

#container img{
 height:100%;
 width:100%;   
}