Programs & Examples On #Instrumentation

The process of inserting extra diagnostic code during compilation of a given source code.

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

if I remove this row from application gradle:

apply plugin: 'io.fabric'

error will not appear anymore.

Reference link github

Can I use library that used android support with Androidx projects.

Comment This Line in gradle.properties

android.useAndroidX=true

Android design support library for API 28 (P) not working

Try this:

implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'

Failed to resolve: com.google.firebase:firebase-core:16.0.1

Just add below code and update all firebase versions that will work

 implementation 'com.google.firebase:firebase-core:17.2.0'

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

Go to the directory where you put additional libraries and delete duplicated libraries.

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.dev.khamsat"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "2.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

I have resolved this issue after selecting the "Target Compatibility" to 1.8 Java version. File -> Project Structure -> Modules.

Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project

this work for me. add configurations.all in app/build.gradle

android {
    configurations.all {
        resolutionStrategy.force 'com.android.support:support-annotations:27.1.1'
    }
}

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:

multiDexEnabled true

And it worked!

Example

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.1'
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

And clean the project.

Android Studio 3.0 Execution failed for task: unable to merge dex

I Have Done and fixed this issue by just doing this jobs in my code

Open ->build.gradle Change value from

compile 'com.google.code.gson:gson:2.6.1'

to

compile 'com.google.code.gson:gson:2.8.2'

Unable to merge dex

In my case the following works

implementation 'com.google.android.gms:play-services-ads:17.2.0'
implementation 'com.google.firebase:firebase-core:16.0.9'
implementation 'com.google.firebase:firebase-analytics:16.5.0'
implementation 'com.google.firebase:firebase-messaging:18.0.0'

In my app module. The problem was they firebase-analytics latest library, it is not working properly with the other latest libraries.

More than one file was found with OS independent path 'META-INF/LICENSE'

I'm having same problem and I tried this

Error: More than one file was found with OS independent path 'META-INF/library_release.kotlin_module'

Solution:

android {
    packagingOptions {
    exclude 'META-INF/library_release.kotlin_module'
    }
}

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

Another possible recent solution is changing gradle version to:

classpath 'com.android.tools.build:gradle:3.0.0-rc2'

and updating build tool

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

About Android Studio Gradle plugin version and Required Gradle version, you can see more detailed answer here: What is real Android Studio Gradle Version?

For each version of this Gradle plugin, it requires a minimum Gradle version as listed on below table

(Reference page:gradle-plugin#updating-gradle).

enter image description here

When you update Android Studio, you may receive a prompt to also update Gradle to the latest available version.

For example, Android Gradle Plugin version 3.1.0+ requires a minimal gradle version 4.4.

You can be configured via Android Studio File -> Project Structure -> Project. See below:

enter image description here

Or you can manually modify the file gradle/wrapper/gradle-wrapper.properties. For example:

distributionUrl = https\://services.gradle.org/distributions/gradle-4.6-all.zip

Error:Cause: unable to find valid certification path to requested target

The error is is because of your network restriction that does not allow to sync the project from "http://jcenter.bintray.com", No need play with the IDE (Android Studio).

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

  1. The accepted answer is one way of fixing the issue, because it will just apply some strategy for the problematic dependency (com.google.code.findbugs:jsr305) and it will resolve the problem around the project, using some version of this dependency. Basically it will align the versions of this library inside the whole project.

  2. There is an answer from @Santhosh (and couple of other people) who suggests to exclude the same dependency for espresso, which should work by the same way, but if the project has some other dependencies who depend on the same library (com.google.code.findbugs:jsr305), again we will have the same issue. So in order to use this approach you will need to exclude the same group from all project dependencies, who depend on com.google.code.findbugs:jsr305. I personally found that Espresso Contrib and Espresso Intents also use com.google.code.findbugs:jsr305.

I hope this thoughts will help somebody to realise what exactly is happening here and how things work (not just copy paste some code) :).

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

The problem is not in your dependencies.... you should open detail error on this path

Please refer to D:\Masters\thesis related papers and tools\junitcategorizer\junitcategorizer.instrument\target\surefire-reports for the individual test results.

the detail error's in there, maybe your service class or serviceImpl class or something missing like @anotation or else... i got error same with you,...u should try

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Check out this solution. It worked for me..... Check the id of the button for which the error is raised...it may be the same in any one of the other page in your app. If yes, then change the id of them and then the app runs perfectly.

I was having two same button id's in two different XML codes....I changed the id. Now it runs perfectly!! Hope it works

How to open a different activity on recyclerView item onclick

you can implement your adapter's onClickListener:

  public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder>implements View.OnClickListener

and use interface with method in it

public interface mClickListener {
    public void mClick(View v, int position);
}

and in your onClick method call the method in the interface and pass it the view and position

in your main activity implement that interface

public class MainActivity extends ActionBarActivity implements AdapterClass.mClickListener

and override that method

@Override
public void onCommentsClick(View v, int position) {
    final Intent intent = new Intent(this, OtherActivity.class);
}

as its better to manage your activity transition by the activity not other classes

Android Error [Attempt to invoke virtual method 'void android.app.ActionBar' on a null object reference]

If you are using android.app.ActionBar and android.app.Activity you should change the app theme in application tag:

< application
     android:theme="@android:style/Theme.Holo.Light">

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

The exception occurs due to this statement,

called_from.equalsIgnoreCase("add")

It seem that the previous statement

String called_from = getIntent().getStringExtra("called");

returned a null reference.

You can check whether the intent to start this activity contains such a key "called".

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

Error inflating class android.support.v7.widget.Toolbar?

If you are using new androidx implementations, when typing Toolbar, the Studio will autocomplete it to android.support.v7.widget.Toolbar, but you should use androidx.appcompat.widget.Toolbar instead, otherwise you will get this error.

This Activity already has an action bar supplied by the window decor

Add this two line in your app theme located in style.xml:-

 <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    //Add this two line will fix your problem
    <item name="windowNoTitle">true</item>   <--1(this applies after 22.0.1 support library i think 
    <item name="windowActionBar">true</item> <--2

Parcelable encountered IOException writing serializable object getactivity()

In my case I had to implement MainActivity as Serializable too. Cause I needed to start a service from my MainActivity :

public class MainActivity extends AppCompatActivity implements Serializable {
    ...
    musicCover = new MusicCover(); // A Serializable Object
    ...
    sIntent = new Intent(MainActivity.this, MusicPlayerService.class);
    sIntent.setAction(MusicPlayerService.ACTION_INITIALIZE_COVER);
    sIntent.putExtra(MusicPlayerService.EXTRA_COVER, musicCover);
    startService(sIntent);
}

Output PowerShell variables to a text file

I was lead here in my Google searching. In a show of good faith I have included what I pieced together from parts of this code and other code I've gathered along the way.

_x000D_
_x000D_
# This script is useful if you have attributes or properties that span across several commandlets_x000D_
# and you wish to export a certain data set but all of the properties you wish to export are not_x000D_
# included in only one commandlet so you must use more than one to export the data set you want_x000D_
#_x000D_
# Created: Joshua Biddle 08/24/2017_x000D_
# Edited: Joshua Biddle 08/24/2017_x000D_
#_x000D_
_x000D_
$A = Get-ADGroupMember "YourGroupName"_x000D_
_x000D_
# Construct an out-array to use for data export_x000D_
$Results = @()_x000D_
_x000D_
foreach ($B in $A)_x000D_
    {_x000D_
  # Construct an object_x000D_
        $myobj = Get-ADuser $B.samAccountName -Properties ScriptPath,Office_x000D_
  _x000D_
  # Fill the object_x000D_
  $Properties = @{_x000D_
  samAccountName = $myobj.samAccountName_x000D_
  Name = $myobj.Name _x000D_
  Office = $myobj.Office _x000D_
  ScriptPath = $myobj.ScriptPath_x000D_
  }_x000D_
_x000D_
        # Add the object to the out-array_x000D_
        $Results += New-Object psobject -Property $Properties_x000D_
        _x000D_
  # Wipe the object just to be sure_x000D_
        $myobj = $null_x000D_
    }_x000D_
_x000D_
# After the loop, export the array to CSV_x000D_
$Results | Select "samAccountName", "Name", "Office", "ScriptPath" | Export-CSV "C:\Temp\YourData.csv"
_x000D_
_x000D_
_x000D_

Cheers

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

I had this issue while testing software. Drivers were not signed.

Tip for me was: in cmd line: (administrator) bcdedit /set TESTSIGNING ON and reboot the machine (shutdown -r -t 5)

Android - java.lang.SecurityException: Permission Denial: starting Intent

In my case, this error was due to incorrect paths used to specify intents in my preferences xml file after I renamed the project. For instance, where I had:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <Preference
        android:key="pref_edit_recipe_key"
        android:title="Add/Edit Recipe">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.ssimon.olddirectory"
            android:targetClass="com.ssimon.olddirectory.RecipeEditActivity"/>
    </Preference>
</PreferenceScreen> 

I needed the following instead:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <Preference
        android:key="pref_edit_recipe_key"
        android:title="Add/Edit Recipe">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.ssimon.newdirectory"
            android:targetClass="com.ssimon.newdirectory.RecipeEditActivity"/>
</Preference>

Correcting the path names fixed the problem.

Android ClassNotFoundException: Didn't find class on path

If you are using Multidex on Android 4.4 and prior, your issue might be that your activity class is located in the second dex file and therefore not found by the android system.

To keep your activity class in the main dex file, see this page:

https://developer.android.com/studio/build/multidex.html#keep


To find which classes are located in a dex file use Android Studio.

Simply drag n drop your apk into Android Studio. You should be able to see your dex files in the apk explorer.

Then select the dex file to see what classes are inside.


another alternative is dexdump:

You can check the content of your dex files contained in your apk by using the command dexdump which can be found in

android-sdk/build-tools/27.0.3/dexdump

For windows users see this tool I made to ease the process

The specified child already has a parent. You must call removeView() on the child's parent first

in ActivitySaludo, this line,

    setContentView(txtCambiado);

you must set the content view for the activity only once.

Integrate ZXing in Android Studio

Anybody facing the same issues, follow the simple steps:

Import the project android from downloaded zxing-master zip file using option Import project (Eclipse ADT, Gradle, etc.) and add the dollowing 2 lines of codes in your app level build.gradle file and and you are ready to run.

So simple, yahh...

dependencies {
        // https://mvnrepository.com/artifact/com.google.zxing/core
        compile group: 'com.google.zxing', name: 'core', version: '3.2.1'
        // https://mvnrepository.com/artifact/com.google.zxing/android-core
        compile group: 'com.google.zxing', name: 'android-core', version: '3.2.0'

    }

You can always find latest version core and android core from below links:

https://mvnrepository.com/artifact/com.google.zxing/core/3.2.1 https://mvnrepository.com/artifact/com.google.zxing/android-core/3.2.0

UPDATE (29.05.2019)

Add these dependencies instead:

dependencies {
    implementation 'com.google.zxing:core:3.4.0'
    implementation 'com.google.zxing:android-core:3.3.0'
}

ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat

If you are extending ActionBarActivity in your MainActivity, you will have to change the parent theme in values-v11 also.
So the style.xml in values-v11 will be -

 <!-- res/values-v11/themes.xml -->
 <?xml version="1.0" encoding="utf-8"?>
 <resources>
    <style name="QueryTheme" parent="@style/Theme.AppCompat">
    <!-- Any customizations for your app running on devices with Theme.Holo here -->
    </style>
 </resources>

EDIT: I would recommend you stop using ActionBar and start using the AppBar layout included in the Android Design Support Library

How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA

As an update to Austyn Mahoney's answer, configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.

It will be removed at the end of 2018. For more information see here.

Android open pdf file

Kotlin version below (Updated version of @paul-burke response:

fun openPDFDocument(context: Context, filename: String) {
    //Create PDF Intent
    val pdfFile = File(Environment.getExternalStorageDirectory().absolutePath + "/" + filename)
    val pdfIntent = Intent(Intent.ACTION_VIEW)
    pdfIntent.setDataAndType(Uri.fromFile(pdfFile), "application/pdf")
    pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)

    //Create Viewer Intent
    val viewerIntent = Intent.createChooser(pdfIntent, "Open PDF")
    context.startActivity(viewerIntent)
}

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

Add this permission to your project's AndroidManifest.xml file, in the manifest tag (which should be the top level tag).

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

How to pass values between Fragments

Kotlin way

Use a SharedViewModel proposed at the official ViewModel documentation

It's very common that two or more fragments in an activity need to communicate with each other. Imagine a common case of master-detail fragments, where you have a fragment in which the user selects an item from a list and another fragment that displays the contents of the selected item. This case is never trivial as both fragments need to define some interface description, and the owner activity must bind the two together. In addition, both fragments must handle the scenario where the other fragment is not yet created or visible.

This common pain point can be addressed by using ViewModel objects. These fragments can share a ViewModel using their activity scope to handle this communication

First implement fragment-ktx to instantiate your viewmodel more easily

dependencies {
    implementation "androidx.fragment:fragment-ktx:1.2.2"
} 

Then, you just need to put inside the viewmodel the data you will be sharing with the other fragment

class SharedViewModel : ViewModel() {
    val selected = MutableLiveData<Item>()

    fun select(item: Item) {
        selected.value = item
    }
}

Then, to finish up, just instantiate your viewModel in each fragment, and set the value of selected from the fragment you want to set the data

Fragment A

class MasterFragment : Fragment() {

    private val model: SharedViewModel by activityViewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        itemSelector.setOnClickListener { item ->
        model.select(item)
      }

    }
}

And then, just listen for this value at your Fragment destination

Fragment B

 class DetailFragment : Fragment() {

        private val model: SharedViewModel by activityViewModels()

        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            model.selected.observe(viewLifecycleOwner, Observer<Item> { item ->
                // Update the UI
            })
        }
    }

You can also do it in the opposite way

Android - How to download a file from a webserver

Simple kotlin version

fun download(link: String, path: String) {
    URL(link).openStream().use { input ->
        FileOutputStream(File(path)).use { output ->
            input.copyTo(output)
        }
    }
}

EDIT

or as extension

fun String.saveTo(path: String) {
    URL(this).openStream().use { input ->
        FileOutputStream(File(path)).use { output ->
            input.copyTo(output)
        }
    }
}

// ...

"http://example.site/document".saveTo("some/path/file")

An Authentication object was not found in the SecurityContext - Spring 3.2.2

The security's authorization check part gets the authenticated object from SecurityContext, which will be set when a request gets through the spring security filter. My assumption here is that soon after the login this is not being set. You probably can use a hack as given below to set the value.

try {
    SecurityContext ctx = SecurityContextHolder.createEmptyContext();
    SecurityContextHolder.setContext(ctx);
    ctx.setAuthentication(event.getAuthentication());

    //Do what ever you want to do

} finally {
    SecurityContextHolder.clearContext();
}

Update:

Also you can have a look at the InteractiveAuthenticationSuccessEvent which will be called once the SecurityContext is set.

Start an activity from a fragment

I use this in my fragment.

Button btn1 = (Button) thisLayout
            .findViewById(R.id.btnDb1);

    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(getActivity(), otherActivity.class);
            ((MainActivity) getActivity()).startActivity(intent);

        }
    });

    return thisLayout;
}

android.content.res.Resources$NotFoundException: String resource ID Fatal Exception in Main

You are trying to set int value to TextView so you are getting this issue. To solve this try below one option

option 1:

tv.setText(no+"");

Option2:

tv.setText(String.valueOf(no));

Unable instantiate android.gms.maps.MapFragment

In IntelliJ IDEA (updated for IntelliJ 12):

  1. Create a file ~/android-sdk/extras/google/google_play_services/libproject/google-play-services_lib/src/dummy.java containing class dummy {}.
  2. File->Import Module-> ~/android-sdk/extras/google/google_play_services/libproject/google-play-services_lib
  3. Create Module from Existing Sources
  4. Next->Next->Next->Next->Finish
  5. File->Project Structure->Modules->YourApp
  6. +->Module Dependency->Google-play-services_lib (The + button is in the top right corner of the dialog.)
  7. +->Jars or directories->~/android-sdk/extras/google/google_play_services/libproject/google-play-services_lib/libs/google-play-services.jar
  8. Use the up/down arrows to move <Module source> to the bottom of the list.

You can delete dummy.java if you like.

Edit: After using this for a while I've found that there is a small flaw/bug. IDEA will sometimes complain about not being able to open a .iml project file in the google-play-services_lib directory, despite the fact that you never told it there was a project there. If that happens, rebuilding the project solves the problem, at least until it comes back.

Google Maps Android API v2 Authorization failure

"java.lang.NoClassDefFoundError: com.google.android.gms.R$styleable"

A had this error too, you need to: File -> import -> Existing Android Code Into Workspace -> Browse -> Android sdks -> extras -> google -> google_play_services -> lib_project -> google_play_services_lib and OK. Check the project and Finish.

The project goes to Package Explorer. Now go to your project (with error) -> properties -> Android and in Library click Add... the google_play_services_lib should be there! add and try again :)

This app won't run unless you update Google Play Services (via Bazaar)

According to a discussion with Android Developers on Google+, running the new Map API on the emulator is not possible at the moment.

(The comment is from Zhelyazko Atanasov yesterday at 23:18, I don't know how to link directly to it)

Also, you don't see the "(via Bazaar)" part when running from an actual device, and the update button open the Play Store. I am assuming Bazaar is meant to provide Google Play Services on the Android emulator, but it is not ready yet...

Set View Width Programmatically

The first parameter to LayoutParams is the width and the second is the height. So if you want the width to be FILL_PARENT, but the width to be, say, 20px, then use something new LayoutParams(FILL_PARENT, 20). Of course you should never use actual pixels in your code; you'll need to conver that to density-independent pixels, but you get the idea. Also, you need to make sure your parent LinearLayout has the right width and height that you're looking for. Seems to be you want the LinearLayout to fill the parent width-wise and then have the adview fill that linearlayout witdh-wise as well, so you probably need to specify android:layout_width:"fill_parent" and android:layout_height:"wrap_content" in your linear layout's xml.

How to make Sonar ignore some classes for codeCoverage metric?

For me this worked (basically pom.xml level global properties):

<properties>
    <sonar.exclusions>**/Name*.java</sonar.exclusions>
</properties>

According to: http://docs.sonarqube.org/display/SONAR/Narrowing+the+Focus#NarrowingtheFocus-Patterns

It appears you can either end it with ".java" or possibly "*"

to get the java classes you're interested in.

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

Please try this Way And Let me know :

Context mContext;
@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.neterrorlayout);

   mContext=NetErrorPage.this;
   Button reload=(Button)findViewById(R.id.btnReload);
   reload.setOnClickListener(this);    
   showInfoMessageDialog("Please check your network connection","Network Alert"); 
}
public void showInfoMessageDialog(String message,String title)
{
   new AlertDialog.Builder(mContext)
   .setTitle("Network Alert");
   .setMessage(message);
   .setButton("OK",new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog,int which) 
       {   
          dialog.cancel();
       }
   })
   .show();
}

Android Error - Open Failed ENOENT

With sdk, you can't write to the root of internal storage. This cause your error.

Edit :

Based on your code, to use internal storage with sdk:

final File dir = new File(context.getFilesDir() + "/nfs/guille/groce/users/nicholsk/workspace3/SQLTest");
dir.mkdirs(); //create folders where write files
final File file = new File(dir, "BlockForTest.txt");

java.lang.RuntimeException: Unable to start activity ComponentInfo

Your Manifest Must Change like this Activity name must Specified like ".YourActivityname"

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.th.mybook"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
     android:minSdkVersion="8" android:targetSdkVersion="8" />

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

Android java.lang.NoClassDefFoundError

I fixed the issue by just adding private libraries of the main project to export here:

Project Properties->Java Build Path->Order And Export

And make sure Android Private Libraries are checked.

Screenshot:

enter image description here

Make sure google-play-services_lib.jar and google-play-services.jar are checked. Clean the project and re-run and the classNotfound exception goes away.

Getting android.content.res.Resources$NotFoundException: exception even when the resource is present in android

I got this error when I was trying to access Bundle data from One Intent by using getInt("ID").

I solved it by using getString("ID").

From Activity1 i had

Intent intent=new Intent(this,ActivityB.class);
intent.putExtra("data",data)// 
startActivity(intent);

On Activity B,

Bundle bundle=getIntent().getExtras();
if(extras!=null){
// int x=extras.getInt("Data"); This Line gave me error int 
x=Integer.parseInt(extras.getString("Data")); // This solved the problem.
}

PopupWindow $BadTokenException: Unable to add window -- token null is not valid

  @Override
protected void onCreate(Bundle savedInstanceState) {
    View view = LayoutInflater.from(mContext).inflate(R.layout.popup_window_layout, new LinearLayout(mContext), true);
    popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    popupWindow.setContentView(view);
}

   @Override
public void onWindowFocusChanged(boolean hasFocus) {
    if (hasFocus) {
        popupWindow.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
    }
}

the correct way is popupwindow.show() at onWindowFocusChanged().

NoClassDefFoundError for code in an Java library on Android

I encountered this NoClassDefFoundError when I used java.nio.charset.StandardCharsets.

The reason is that StandardCharsets has not existed until JRE 1.7. If I make the java compile version set to 1.7, Eclipse complained that "Android requires compiler compliance level 5.0 or 6.0". So, I fixed it by right-click the project name->Android Tools->Fix Project Properties. It is compiled with JRE1.6.

However, because StandardCharsets has not existed until 1.7. It reported NoClassDefFoundError when I ran it.

I has not come to realize this until after trying a lot of other methods including reinstalling JDK. The real reason is clearly told by the meaning of NoClassDefFoundError: The class cannot be found at run time although it passed compilation.

General conclusion is that as long as Android does not work with JRE 1.7, if you use any new feature provided since 1.7, you will encounter this error.

My solution is that I copied those source code into my code!

Android app unable to start activity componentinfo

Your null pointer exception seems to be on this line:

String url = intent.getExtras().getString("userurl");

because intent.getExtras() returns null when the intent doesn't have any extras.

You have to realize that this piece of code:

Intent Main = new Intent(this, ToClass.class);
Main.putExtra("userurl", url);
startActivity(Main);

doesn't start the activity you wrote in Main.java, it will attempt to start an activity called ToClass and if that doesn't exist, your app crashes.

Also, there is no such thing as "android.intent.action.start" so the manifest should look more like:

<activity android:name=".start" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity android:name= ".Main">
</activity>

I hope this fixes some of the issues you are encountering but I strongly suggest you check out some "getting started" tutorials for android development and build up from there.

Error inflating class fragment

The exception android.view.InflateException: Binary XML file line: #... Error inflating class fragment might happen if you manipulate with getActivity() inside your fragment before onActivityCreated() get called. In such case you receive a wrong activity reference and can't rely on that.

For instance the next pattern is wrong:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
        Bundle savedInstanceState) 
{
    final View view = inflater.inflate(R.layout..., container, false);

    Button button = getActivity().findViewById(R.id...);
    button.setOnClickListener(...); - another problem: button is null

    return view;
}

Correct pattern #1

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
        Bundle savedInstanceState) 
{
    final View view = inflater.inflate(R.layout..., container, false);

    Button button = view.findViewById(R.id...);
    button.setOnClickListener(...);

    return view;
}

Correct pattern #2

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Button button = getActivity().findViewById(R.id...);
    button.setOnClickListener(...);
}

Create the perfect JPA entity

My 2 cents addition to the answers here are:

  1. With reference to Field or Property access (away from performance considerations) both are legitimately accessed by means of getters and setters, thus, my model logic can set/get them in the same manner. The difference comes to play when the persistence runtime provider (Hibernate, EclipseLink or else) needs to persist/set some record in Table A which has a foreign key referring to some column in Table B. In case of a Property access type, the persistence runtime system uses my coded setter method to assign the cell in Table B column a new value. In case of a Field access type, the persistence runtime system sets the cell in Table B column directly. This difference is not of importance in the context of a uni-directional relationship, yet it is a MUST to use my own coded setter method (Property access type) for a bi-directional relationship provided the setter method is well designed to account for consistency. Consistency is a critical issue for bi-directional relationships refer to this link for a simple example for a well-designed setter.

  2. With reference to Equals/hashCode: It is impossible to use the Eclipse auto-generated Equals/hashCode methods for entities participating in a bi-directional relationship, otherwise they will have a circular reference resulting in a stackoverflow Exception. Once you try a bidirectional relationship (say OneToOne) and auto-generate Equals() or hashCode() or even toString() you will get caught in this stackoverflow exception.

No Activity found to handle Intent : android.intent.action.VIEW

I had this same issue, so I was looking at the intent which is logged in LogCat. When viewing the video from the Gallery, it called the same Intent.View intent, but set the Type to "audio/*", which fixed my issue, and doesn't require importing MimeTypeMap. Example:

Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
Uri data = Uri.parse(path);
intent.setDataAndType(data, "audio/*");
startActivity(intent);

incompatible character encodings: ASCII-8BIT and UTF-8

i had a similiar problem and the gem string-scrub automagically fixed it for me. https://github.com/hsbt/string-scrub If the given string contains an invalid byte sequence then that invalid byte sequence is replaced with the unicode replacement character (?) and a new string is returned.

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

My problem was missing package declaration in the beginning of the activity source file:

package com.my.package

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

I had the same error on Kitkat which was because i had android:tint on one of the imageViews. It would work fine on Lollipop but crash on Kikkat with Error Inflating class .

Fixed it by using app:tint on the AppCompatImageView which i was dealing with.

Get startup type of Windows service using PowerShell

You can use also:

(Get-Service 'winmgmt').StartType

It returns just the startup type, for example, disabled.

How to make a phone call using intent in Android?

Every thing is fine.

i just placed call permissions tag before application tag in manifest file

and now every thing is working fine.

Android: java.lang.SecurityException: Permission Denial: start Intent

It's easy maybe you have error in the configuration.

For Example: Manifest.xml

enter image description here

But in my configuration have for default Activity .Splash

enter image description here

you need check this configuration and the file Manifest.xml

Good Luck

java.lang.ClassNotFoundException on working app

Something like this happened when I changed the build target to 3.2. After digging around I found that a had named the jar lib folder "lib" instead of "libs". I just renamed it to libs and updated the references on the Java build path and everything was working again. Maybe this will help someone...

Activity has leaked window that was originally added

Generally this issue occurs due to progress dialog : you can solve this by using any one of the following method in your activity:

 // 1):
          @Override
                protected void onPause() {
                    super.onPause();
                    if ( yourProgressDialog!=null && yourProgressDialog.isShowing() )
                  {
                        yourProgressDialog.cancel();
                    }
                }

       // 2) :
         @Override
            protected void onDestroy() {
                super.onDestroy();
                if ( yourProgressDialog!=null && yourProgressDialog.isShowing()
               {
                    yourProgressDialog.cancel();
                }
            }

Java: recommended solution for deep cloning/copying an instance

Use XStream toXML/fromXML in memory. Extremely fast and has been around for a long time and is going strong. Objects don't need to be Serializable and you don't have use reflection (although XStream does). XStream can discern variables that point to the same object and not accidentally make two full copies of the instance. A lot of details like that have been hammered out over the years. I've used it for a number of years and it is a go to. It's about as easy to use as you can imagine.

new XStream().toXML(myObj)

or

new XStream().fromXML(myXML)

To clone,

new XStream().fromXML(new XStream().toXML(myObj))

More succinctly:

XStream x = new XStream();
Object myClone = x.fromXML(x.toXML(myObj));

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

You haven't provided any of your code from LightFactoryRemote, so this is only a presumption, but it looks like the kind of problem you'd be seeing if you were using the bindService method on it's own.

To ensure a service is kept running, even after the activity that started it has had its onDestroy method called, you should first use startService.

The android docs for startService state:

Using startService() overrides the default service lifetime that is managed by bindService(Intent, ServiceConnection, int): it requires the service to remain running until stopService(Intent) is called, regardless of whether any clients are connected to it.

Whereas for bindService:

The service will be considered required by the system only for as long as the calling context exists. For example, if this Context is an Activity that is stopped, the service will not be required to continue running until the Activity is resumed.


So what's happened is the activity that bound (and therefore started) the service, has been stopped and thus the system thinks the service is no longer required and causes that error (and then probably stops the service).


Example

In this example the service should be kept running regardless of whether the calling activity is running.

ComponentName myService = startService(new Intent(this, myClass.class));
bindService(new Intent(this, myClass.class), myServiceConn, BIND_AUTO_CREATE);

The first line starts the service, and the second binds it to the activity.

Android: ProgressDialog.show() crashes with getApplicationContext

For Activities shown within TabActivities use getParent()

final AlertDialog.Builder builder = new AlertDialog.Builder(getParent());

instead of

final AlertDialog.Builder builder = new AlertDialog.Builder(this);

Using OR in SQLAlchemy

This has been really helpful. Here is my implementation for any given table:

def sql_replace(self, tableobject, dictargs):

    #missing check of table object is valid
    primarykeys = [key.name for key in inspect(tableobject).primary_key]

    filterargs = []
    for primkeys in primarykeys:
        if dictargs[primkeys] is not None:
            filterargs.append(getattr(db.RT_eqmtvsdata, primkeys) == dictargs[primkeys])
        else:
            return

    query = select([db.RT_eqmtvsdata]).where(and_(*filterargs))

    if self.r_ExecuteAndErrorChk2(query)[primarykeys[0]] is not None:
        # update
        filter = and_(*filterargs)
        query = tableobject.__table__.update().values(dictargs).where(filter)
        return self.w_ExecuteAndErrorChk2(query)

    else:
        query = tableobject.__table__.insert().values(dictargs)
        return self.w_ExecuteAndErrorChk2(query)

# example usage
inrow = {'eqmtvs_id': eqmtvsid, 'datetime': dtime, 'param_id': paramid}

self.sql_replace(tableobject=db.RT_eqmtvsdata, dictargs=inrow)

Remove trailing zeros from decimal in SQL Server

I had a similar issue, but was also required to remove the decimal point where no decimal was present, here was my solution which splits the decimal into its components, and bases the number of characters it takes from the decimal point string on the length of the fraction component (without using CASE). To make matters even more interesting, my number was stored as a float without its decimals.

DECLARE @MyNum FLOAT
SET @MyNum = 700000
SELECT CAST(PARSENAME(CONVERT(NUMERIC(15,2),@MyNum/10000),2) AS VARCHAR(10)) 
+ SUBSTRING('.',1,LEN(REPLACE(RTRIM(REPLACE(CAST(PARSENAME(CONVERT(NUMERIC(15,2),@MyNum/10000),1) AS VARCHAR(2)),'0',' ')),' ','0'))) 
+ REPLACE(RTRIM(REPLACE(CAST(PARSENAME(CONVERT(NUMERIC(15,2),@MyNum/10000),1) AS VARCHAR(2)),'0',' ')),' ','0') 

The result is painful, I know, but I got there, with much help from the answers above.

Importing text file into excel sheet

I think my answer to my own question here is the simplest solution to what you are trying to do:

  1. Select the cell where the first line of text from the file should be.

  2. Use the Data/Get External Data/From File dialog to select the text file to import.

  3. Format the imported text as required.

  4. In the Import Data dialog that opens, click on Properties...

  5. Uncheck the Prompt for file name on refresh box.

  6. Whenever the external file changes, click the Data/Get External Data/Refresh All button.

Note: in your case, you should probably want to skip step #5.

How can I prevent the backspace key from navigating back?

This code solves the problem in all browsers:

onKeydown:function(e)
{
    if (e.keyCode == 8) 
    {
      var d = e.srcElement || e.target;
      if (!((d.tagName.toUpperCase() == 'BODY') || (d.tagName.toUpperCase() == 'HTML'))) 
      {
         doPrevent = false;
      }
       else
      {
         doPrevent = true;
      }
    }
    else
    {
       doPrevent = false;
    }
      if (doPrevent)
      {
         e.preventDefault();
       }

  }

HTTP get with headers using RestTemplate

Take a look at the JavaDoc for RestTemplate.

There is the corresponding getForObject methods that are the HTTP GET equivalents of postForObject, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.

Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange methods allow you to provide an HttpEntity object representing the details of the request (including headers). The execute methods allow you to specify a RequestCallback from which you can add the headers upon its invocation.

When to use references vs. pointers

Use reference wherever you can, pointers wherever you must.

Avoid pointers until you can't.

The reason is that pointers make things harder to follow/read, less safe and far more dangerous manipulations than any other constructs.

So the rule of thumb is to use pointers only if there is no other choice.

For example, returning a pointer to an object is a valid option when the function can return nullptr in some cases and it is assumed it will. That said, a better option would be to use something similar to std::optional (requires C++17; before that, there's boost::optional).

Another example is to use pointers to raw memory for specific memory manipulations. That should be hidden and localized in very narrow parts of the code, to help limit the dangerous parts of the whole code base.

In your example, there is no point in using a pointer as argument because:

  1. if you provide nullptr as the argument, you're going in undefined-behaviour-land;
  2. the reference attribute version doesn't allow (without easy to spot tricks) the problem with 1.
  3. the reference attribute version is simpler to understand for the user: you have to provide a valid object, not something that could be null.

If the behaviour of the function would have to work with or without a given object, then using a pointer as attribute suggests that you can pass nullptr as the argument and it is fine for the function. That's kind of a contract between the user and the implementation.

Generate class from database table

slightly modified from top reply:

declare @TableName sysname = 'HistoricCommand'

declare @Result varchar(max) = '[System.Data.Linq.Mapping.Table(Name = "' + @TableName + '")]
public class Dbo' + @TableName + '
{'

select @Result = @Result + '
    [System.Data.Linq.Mapping.Column(Name = "' + t.ColumnName + '", IsPrimaryKey = ' + pkk.ISPK + ')]
    public ' + ColumnType + NullableSign + ' ' + t.ColumnName + ' { get; set; }
'
from
(
    select 
        replace(col.name, ' ', '_') ColumnName,
        column_id ColumnId,
        case typ.name 
            when 'bigint' then 'long'
            when 'binary' then 'byte[]'
            when 'bit' then 'bool'
            when 'char' then 'string'
            when 'date' then 'DateTime'
            when 'datetime' then 'DateTime'
            when 'datetime2' then 'DateTime'
            when 'datetimeoffset' then 'DateTimeOffset'
            when 'decimal' then 'decimal'
            when 'float' then 'float'
            when 'image' then 'byte[]'
            when 'int' then 'int'
            when 'money' then 'decimal'
            when 'nchar' then 'string'
            when 'ntext' then 'string'
            when 'numeric' then 'decimal'
            when 'nvarchar' then 'string'
            when 'real' then 'double'
            when 'smalldatetime' then 'DateTime'
            when 'smallint' then 'short'
            when 'smallmoney' then 'decimal'
            when 'text' then 'string'
            when 'time' then 'TimeSpan'
            when 'timestamp' then 'DateTime'
            when 'tinyint' then 'byte'
            when 'uniqueidentifier' then 'Guid'
            when 'varbinary' then 'byte[]'
            when 'varchar' then 'string'
            else 'UNKNOWN_' + typ.name
        end ColumnType,
        case 
            when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier') 
            then '?' 
            else '' 
        end NullableSign
    from sys.columns col
        join sys.types typ on
            col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id         
    where object_id = object_id(@TableName) 
) t, 
(
                SELECT c.name  AS 'ColumnName', CASE WHEN dd.pk IS NULL THEN 'false' ELSE 'true' END ISPK           
                FROM        sys.columns c
                    JOIN    sys.tables  t   ON c.object_id = t.object_id    
                    LEFT JOIN (SELECT   K.COLUMN_NAME , C.CONSTRAINT_TYPE as pk  
                        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K 
                            LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
                        ON K.TABLE_NAME = C.TABLE_NAME
                            AND K.CONSTRAINT_NAME = C.CONSTRAINT_NAME
                            AND K.CONSTRAINT_CATALOG = C.CONSTRAINT_CATALOG
                            AND K.CONSTRAINT_SCHEMA = C.CONSTRAINT_SCHEMA            
                        WHERE K.TABLE_NAME = @TableName) as dd
                     ON dd.COLUMN_NAME = c.name
                 WHERE       t.name = @TableName            
            ) pkk
where pkk.ColumnName = t.ColumnName
order by ColumnId

set @Result = @Result  + '
}'

print @Result

which makes output needed for full LINQ in C# declaration

[System.Data.Linq.Mapping.Table(Name = "HistoricCommand")]
public class DboHistoricCommand
{
    [System.Data.Linq.Mapping.Column(Name = "HistoricCommandId", IsPrimaryKey = true)]
    public int HistoricCommandId { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "PHCloudSoftwareInstanceId", IsPrimaryKey = true)]
    public int PHCloudSoftwareInstanceId { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "CommandType", IsPrimaryKey = false)]
    public int CommandType { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "InitiatedDateTime", IsPrimaryKey = false)]
    public DateTime InitiatedDateTime { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "CompletedDateTime", IsPrimaryKey = false)]
    public DateTime CompletedDateTime { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "WasSuccessful", IsPrimaryKey = false)]
    public bool WasSuccessful { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "Message", IsPrimaryKey = false)]
    public string Message { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "ResponseData", IsPrimaryKey = false)]
    public string ResponseData { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "Message_orig", IsPrimaryKey = false)]
    public string Message_orig { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "Message_XX", IsPrimaryKey = false)]
    public string Message_XX { get; set; }

}

How can I control the width of a label tag?

Inline elements (like SPAN, LABEL, etc.) are displayed so that their height and width are calculated by the browser based on their content. If you want to control height and width you have to change those elements' blocks.

display: block; makes the element displayed as a solid block (like DIV tags) which means that there is a line break after the element (it's not inline). Although you can use display: inline-block to fix the issue of line break, this solution does not work in IE6 because IE6 doesn't recognize inline-block. If you want it to be cross-browser compatible then look at this article: http://webjazz.blogspot.com/2008/01/getting-inline-block-working-across.html

Is there a "do ... while" loop in Ruby?

This works correctly now:

begin
    # statment
end until <condition>

But, it may be remove in the future, because the begin statement is counterintuitive. See: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/6745

Matz (Ruby’s Creator) recommended doing it this way:

loop do
    # ...
    break if <condition>
end

What does "static" mean in C?

I hate to answer an old question, but I don't think anybody has mentioned how K&R explain it in section A4.1 of "The C Programming Language".

In short, the word static is used with two meanings:

  1. Static is one of the two storage classes (the other being automatic). A static object keeps its value between invocations. The objects declared outside all blocks are always static and cannot be made automatic.
  2. But, when the static keyword (big emphasis on it being used in code as a keyword) is used with a declaration, it gives that object internal linkage so it can only be used within that translation unit. But if the keyword is used in a function, it changes the storage class of the object (the object would only be visible within that function anyway). The opposite of static is the extern keyword, which gives an object external linkage.

Peter Van Der Linden gives these two meanings in "Expert C Programming":

  • Inside a function, retains its value between calls.
  • At the function level, visible only in this file.

Java Replace Line In Text File

If replacement is of different length:

  1. Read file until you find the string you want to replace.
  2. Read into memory the part after text you want to replace, all of it.
  3. Truncate the file at start of the part you want to replace.
  4. Write replacement.
  5. Write rest of the file from step 2.

If replacement is of same length:

  1. Read file until you find the string you want to replace.
  2. Set file position to start of the part you want to replace.
  3. Write replacement, overwriting part of file.

This is the best you can get, with constraints of your question. However, at least the example in question is replacing string of same length, So the second way should work.

Also be aware: Java strings are Unicode text, while text files are bytes with some encoding. If encoding is UTF8, and your text is not Latin1 (or plain 7-bit ASCII), you have to check length of encoded byte array, not length of Java string.

How to get a variable name as a string in PHP?

Adapted from answers above for many variables, with good performance, just one $GLOBALS scan for many

function compact_assoc(&$v1='__undefined__', &$v2='__undefined__',&$v3='__undefined__',&$v4='__undefined__',&$v5='__undefined__',&$v6='__undefined__',&$v7='__undefined__',&$v8='__undefined__',&$v9='__undefined__',&$v10='__undefined__',&$v11='__undefined__',&$v12='__undefined__',&$v13='__undefined__',&$v14='__undefined__',&$v15='__undefined__',&$v16='__undefined__',&$v17='__undefined__',&$v18='__undefined__',&$v19='__undefined__'
) {
    $defined_vars=get_defined_vars();

    $result=Array();
    $reverse_key=Array();
    $original_value=Array();
    foreach( $defined_vars as $source_key => $source_value){
        if($source_value==='__undefined__') break;
        $original_value[$source_key]=$$source_key;
        $new_test_value="PREFIX".rand()."SUFIX";
        $reverse_key[$new_test_value]=$source_key;
        $$source_key=$new_test_value;

    }
    foreach($GLOBALS as $key => &$value){
        if( is_string($value) && isset($reverse_key[$value])  ) {
            $result[$key]=&$value;
        }
    }
    foreach( $original_value as $source_key => $original_value){
        $$source_key=$original_value;
    }
    return $result;
}


$a = 'A';
$b = 'B';
$c = '999';
$myArray=Array ('id'=>'id123','name'=>'Foo');
print_r(compact_assoc($a,$b,$c,$myArray) );

//print
Array
(
    [a] => A
    [b] => B
    [c] => 999
    [myArray] => Array
        (
            [id] => id123
            [name] => Foo
        )

)

I want to multiply two columns in a pandas DataFrame and add the result into a new column

You can use the DataFrame apply method:

order_df['Value'] = order_df.apply(lambda row: (row['Prices']*row['Amount']
                                               if row['Action']=='Sell'
                                               else -row['Prices']*row['Amount']),
                                   axis=1)

It is usually faster to use these methods rather than over for loops.

How can I add new array elements at the beginning of an array in Javascript?

Another way to do that through concat

_x000D_
_x000D_
var arr = [1, 2, 3, 4, 5, 6, 7];_x000D_
console.log([0].concat(arr));
_x000D_
_x000D_
_x000D_

The difference between concat and unshift is that concat returns a new array. The performance between them could be found here.

function fn_unshift() {
  arr.unshift(0);
  return arr;
}

function fn_concat_init() {
  return [0].concat(arr)
}

Here is the test result

enter image description here

java.lang.RuntimeException: Uncompilable source code - what can cause this?

I had the same problem. My error was the packaging. So I would suggest you first check the package name and if the class is in the correct package.

NoSql vs Relational database

NOSQL has no special advantages over the relational database model. NOSQL does address certain limitations of current SQL DBMSs but it doesn't imply any fundamentally new capabilities over previous data models.

NOSQL means only no SQL (or "not only SQL") but that doesn't mean the same as no relational. A relational database in principle would make a very good NOSQL solution - it's just that none of the current set of NOSQL products uses the relational model.

Javascript - Get Image height

Try with JQuery:

<script type="text/javascript">
function jquery_get_width_height()
{
    var imgWidth = $("#img").width();
    var imgHeight = $("#img").height();
    alert("JQuery -- " + "imgWidth: " + imgWidth + " - imgHeight: " + imgHeight);
}
</script>

or

<script type="text/javascript">
function javascript_get_width_height()
{
    var img = document.getElementById('img');
    alert("JavaSript -- " + "imgWidth: " + img.width + " - imgHeight: " + img.height);
}
</script>

How to deep merge instead of shallow merge?

Most examples here seem too complex, I'm using one in TypeScript I created, I think it should cover most cases (I'm handling arrays as regular data, just replacing them).

const isObject = (item: any) => typeof item === 'object' && !Array.isArray(item);

export const merge = <A = Object, B = Object>(target: A, source: B): A & B => {
  const isDeep = (prop: string) =>
    isObject(source[prop]) && target.hasOwnProperty(prop) && isObject(target[prop]);
  const replaced = Object.getOwnPropertyNames(source)
    .map(prop => ({ [prop]: isDeep(prop) ? merge(target[prop], source[prop]) : source[prop] }))
    .reduce((a, b) => ({ ...a, ...b }), {});

  return {
    ...(target as Object),
    ...(replaced as Object)
  } as A & B;
};

Same thing in plain JS, just in case:

const isObject = item => typeof item === 'object' && !Array.isArray(item);

const merge = (target, source) => {
  const isDeep = prop => 
    isObject(source[prop]) && target.hasOwnProperty(prop) && isObject(target[prop]);
  const replaced = Object.getOwnPropertyNames(source)
    .map(prop => ({ [prop]: isDeep(prop) ? merge(target[prop], source[prop]) : source[prop] }))
    .reduce((a, b) => ({ ...a, ...b }), {});

  return {
    ...target,
    ...replaced
  };
};

Here are my test cases to show how you could use it

describe('merge', () => {
  context('shallow merges', () => {
    it('merges objects', () => {
      const a = { a: 'discard' };
      const b = { a: 'test' };
      expect(merge(a, b)).to.deep.equal({ a: 'test' });
    });
    it('extends objects', () => {
      const a = { a: 'test' };
      const b = { b: 'test' };
      expect(merge(a, b)).to.deep.equal({ a: 'test', b: 'test' });
    });
    it('extends a property with an object', () => {
      const a = { a: 'test' };
      const b = { b: { c: 'test' } };
      expect(merge(a, b)).to.deep.equal({ a: 'test', b: { c: 'test' } });
    });
    it('replaces a property with an object', () => {
      const a = { b: 'whatever', a: 'test' };
      const b = { b: { c: 'test' } };
      expect(merge(a, b)).to.deep.equal({ a: 'test', b: { c: 'test' } });
    });
  });

  context('deep merges', () => {
    it('merges objects', () => {
      const a = { test: { a: 'discard', b: 'test' }  };
      const b = { test: { a: 'test' } } ;
      expect(merge(a, b)).to.deep.equal({ test: { a: 'test', b: 'test' } });
    });
    it('extends objects', () => {
      const a = { test: { a: 'test' } };
      const b = { test: { b: 'test' } };
      expect(merge(a, b)).to.deep.equal({ test: { a: 'test', b: 'test' } });
    });
    it('extends a property with an object', () => {
      const a = { test: { a: 'test' } };
      const b = { test: { b: { c: 'test' } } };
      expect(merge(a, b)).to.deep.equal({ test: { a: 'test', b: { c: 'test' } } });
    });
    it('replaces a property with an object', () => {
      const a = { test: { b: 'whatever', a: 'test' } };
      const b = { test: { b: { c: 'test' } } };
      expect(merge(a, b)).to.deep.equal({ test: { a: 'test', b: { c: 'test' } } });
    });
  });
});

Please let me know if you think I'm missing some functionality.

git push rejected: error: failed to push some refs

If you are the only the person working on the project, what you can do is:

 git checkout master
 git push origin +HEAD

This will set the tip of origin/master to the same commit as master (and so delete the commits between 41651df and origin/master)

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

A solution that correctly handles all file names (including newlines) and extracts into a directory that is at the same location as the file, just with the extension removed:

find . -iname '*.zip' -exec sh -c 'unzip -o -d "${0%.*}" "$0"' '{}' ';'

Note that you can easily make it handle more file types (such as .jar) by adding them using -o, e.g.:

find . '(' -iname '*.zip' -o -iname '*.jar' ')' -exec ...

Disable future dates after today in Jquery Ui Datepicker

maxDate: new Date() 

its working fine for me disable with current date in date range picker

How to style a checkbox using CSS

With pure CSS, nothing fancy with :before and :after, no transforms, you can turn off the default appearance and then style it with an inline background image like the following example. This works in Chrome, Firefox, Safari, and now Edge (Chromium Edge).

_x000D_
_x000D_
INPUT[type=checkbox]:focus
{
    outline: 1px solid rgba(0, 0, 0, 0.2);
}

INPUT[type=checkbox]
{
    background-color: #DDD;
    border-radius: 2px;
    appearance: none;
    -webkit-appearance: none;
    -moz-appearance: none;
    width: 17px;
    height: 17px;
    cursor: pointer;
    position: relative;
    top: 5px;
}

INPUT[type=checkbox]:checked
{
    background-color: #409fd6;
    background: #409fd6 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
}
_x000D_
<form>
  <label><input type="checkbox"> I Agree To Terms &amp; Conditions</label>
</form>
_x000D_
_x000D_
_x000D_

How to Consume WCF Service with Android

Another option might be to avoid WCF all-together and just use a .NET HttpHandler. The HttpHandler can grab the query-string variables from your GET and just write back a response to the Java code.

PHP - include a php file and also send query parameters

Your question is not very clear, but if you want to include the php file (add the source of that page to yours), you just have to do following :

if(condition){
    $someVar=someValue;
    include "myFile.php";
}

As long as the variable is named $someVar in the myFile.php

Bash or KornShell (ksh)?

I'm a korn-shell veteran, so know that I speak from that perspective.

However, I have been comfortable with Bourne shell, ksh88, and ksh93, and for the most I know which features are supported in which. (I should skip ksh88 here, as it's not widely distributed anymore.)

For interactive use, take whatever fits your need. Experiment. I like being able to use the same shell for interactive use and for programming.

I went from ksh88 on SVR2 to tcsh, to ksh88sun (which added significant internationalisation support) and ksh93. I tried bash, and hated it because it flattened my history. Then I discovered shopt -s lithist and all was well. (The lithist option assures that newlines are preserved in your command history.)

For shell programming, I'd seriously recommend ksh93 if you want a consistent programming language, good POSIX conformance, and good performance, as many common unix commands can be available as builtin functions.

If you want portability use at least both. And make sure you have a good test suite.

There are many subtle differences between shells. Consider for example reading from a pipe:

b=42 && echo one two three four |
    read a b junk && echo $b

This will produce different results in different shells. The korn-shell runs pipelines from back to front; the last element in the pipeline runs in the current process. Bash did not support this useful behaviour until v4.x, and even then, it's not the default.

Another example illustrating consistency: The echo command itself, which was made obsolete by the split between BSD and SYSV unix, and each introduced their own convention for not printing newlines (and other behaviour). The result of this can still be seen in many 'configure' scripts.

Ksh took a radical approach to that - and introduced the print command, which actually supports both methods (the -n option from BSD, and the trailing \c special character from SYSV)

However, for serious systems programming I'd recommend something other than a shell, like python, perl. Or take it a step further, and use a platform like puppet - which allows you to watch and correct the state of whole clusters of systems, with good auditing.

Shell programming is like swimming in uncharted waters, or worse.

Programming in any language requires familiarity with its syntax, its interfaces and behaviour. Shell programming isn't any different.

How to debug SSL handshake using cURL?

curl probably does have some options for showing more information but for things like this I always use openssl s_client

With the -debug option this gives lots of useful information

Maybe I should add that this also works with non HTTP connections. So if you are doing "https", try the curl commands suggested below. If you aren't or want a second option openssl s_client might be good

How to pass arguments to Shell Script through docker run

There are a few things interacting here:

  1. docker run your_image arg1 arg2 will replace the value of CMD with arg1 arg2. That's a full replacement of the CMD, not appending more values to it. This is why you often see docker run some_image /bin/bash to run a bash shell in the container.

  2. When you have both an ENTRYPOINT and a CMD value defined, docker starts the container by concatenating the two and running that concatenated command. So if you define your entrypoint to be file.sh, you can now run the container with additional args that will be passed as args to file.sh.

  3. Entrypoints and Commands in docker have two syntaxes, a string syntax that will launch a shell, and a json syntax that will perform an exec. The shell is useful to handle things like IO redirection, chaining multiple commands together (with things like &&), variable substitution, etc. However, that shell gets in the way with signal handling (if you've ever seen a 10 second delay to stop a container, this is often the cause) and with concatenating an entrypoint and command together. If you define your entrypoint as a string, it would run /bin/sh -c "file.sh", which alone is fine. But if you have a command defined as a string too, you'll see something like /bin/sh -c "file.sh" /bin/sh -c "arg1 arg2" as the command being launched inside your container, not so good. See the table here for more on how these two options interact

  4. The shell -c option only takes a single argument. Everything after that would get passed as $1, $2, etc, to that single argument, but not into an embedded shell script unless you explicitly passed the args. I.e. /bin/sh -c "file.sh $1 $2" "arg1" "arg2" would work, but /bin/sh -c "file.sh" "arg1" "arg2" would not since file.sh would be called with no args.

Putting that all together, the common design is:

FROM ubuntu:14.04
COPY ./file.sh /
RUN chmod 755 /file.sh
# Note the json syntax on this next line is strict, double quotes, and any syntax
# error will result in a shell being used to run the line.
ENTRYPOINT ["file.sh"]

And you then run that with:

docker run your_image arg1 arg2

There's a fair bit more detail on this at:

NullPointerException in Java with no StackTrace

As you mentioned in a comment, you're using log4j. I discovered (inadvertently) a place where I had written

LOG.error(exc);

instead of the typical

LOG.error("Some informative message", e);

through laziness or perhaps just not thinking about it. The unfortunate part of this is that it doesn't behave as you expect. The logger API actually takes Object as the first argument, not a string - and then it calls toString() on the argument. So instead of getting the nice pretty stack trace, it just prints out the toString - which in the case of NPE is pretty useless.

Perhaps this is what you're experiencing?

JComboBox Selection Change Listener?

You may try these

 int selectedIndex = myComboBox.getSelectedIndex();

-or-

Object selectedObject = myComboBox.getSelectedItem();

-or-

String selectedValue = myComboBox.getSelectedValue().toString();

How to select a div element in the code-behind page?

Give ID and attribute runat='server' as :

<div class="tab-pane active" id="portlet_tab1" runat="server">

//somecode Codebehind:

Access at code behind

    Control Test = Page.FindControl("portlet_tab1");
    Test.Style.Add("display", "none"); 

    or 

    portlet_tab1.Style.Add("display", "none"); 

Converting a float to a string without rounding it

Other answers already pointed out that the representation of floating numbers is a thorny issue, to say the least.

Since you don't give enough context in your question, I cannot know if the decimal module can be useful for your needs:

http://docs.python.org/library/decimal.html

Among other things you can explicitly specify the precision that you wish to obtain (from the docs):

>>> getcontext().prec = 6
>>> Decimal('3.0')
Decimal('3.0')
>>> Decimal('3.1415926535')
Decimal('3.1415926535')
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')
>>> getcontext().rounding = ROUND_UP
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85988')

A simple example from my prompt (python 2.6):

>>> import decimal
>>> a = decimal.Decimal('10.000000001')
>>> a
Decimal('10.000000001')
>>> print a
10.000000001
>>> b = decimal.Decimal('10.00000000000000000000000000900000002')
>>> print b
10.00000000000000000000000000900000002
>>> print str(b)
10.00000000000000000000000000900000002
>>> len(str(b/decimal.Decimal('3.0')))
29

Maybe this can help? decimal is in python stdlib since 2.4, with additions in python 2.6.

Hope this helps, Francesco

How to add an extra source directory for maven to compile and include in the build jar?

NOTE: This solution will just move the java source files to the target/classes directory and will not compile the sources.

Update the pom.xml as -

<project>   
 ....
    <build>
      <resources>
        <resource>
          <directory>src/main/config</directory>
        </resource>
      </resources>
     ...
    </build>
...
</project>

Go install fails with error: no install location for directory xxx outside GOPATH

I had this problem on Windows.

My problem was that my %GOPATH% environment variable was set to

C:\Users\john\src\goworkspace

instead of

C:\Users\john\src\goworkspace\

Adding the missing trailing slash at the end fixed it for me.

What is the C# Using block and why should I use it?

Placing code in a using block ensures that the objects are disposed (though not necessarily collected) as soon as control leaves the block.

No mapping found for HTTP request with URI Spring MVC

I have the same problem.... I change my project name and i have this problem...my solution was the checking project refences and use / in my web.xml (instead of /*)

Adding git branch on the Bash command prompt

Here is a simple clean version that I use: link

enter image description here

Pythonic way to add datetime.date and datetime.time objects

It's in the python docs.

import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1), 
                          datetime.time(10, 23))

returns

datetime.datetime(2011, 1, 1, 10, 23)

How do I disable Git Credential Manager for Windows?

and if :wq doesn't work like my case use ctrl+z for abort and quit but these will probably make multiple backup file to work with later – Adeem Jan 19 at 9:14

Also be sure to run Git as Administrator! Otherwise the file won't be saved (in my case).

Why use HttpClient for Synchronous Connection

but what i am doing is purely synchronous

You could use HttpClient for synchronous requests just fine:

using (var client = new HttpClient())
{
    var response = client.GetAsync("http://google.com").Result;

    if (response.IsSuccessStatusCode)
    {
        var responseContent = response.Content; 

        // by calling .Result you are synchronously reading the result
        string responseString = responseContent.ReadAsStringAsync().Result;

        Console.WriteLine(responseString);
    }
}

As far as why you should use HttpClient over WebRequest is concerned, well, HttpClient is the new kid on the block and could contain improvements over the old client.

How can I make robocopy silent in the command line except for progress?

If you want no output at all this is the most simple way:

robocopy src dest > nul

If you still need some information and only want to strip parts of the output, use the parameters from R.Koene's answer.

round a single column in pandas

For some reason the round() method doesn't work if you have float numbers with many decimal places, but this will.

decimals = 2    
df['column'] = df['column'].apply(lambda x: round(x, decimals))

mysql delete under safe mode

You can trick MySQL into thinking you are actually specifying a primary key column. This allows you to "override" safe mode.

Assuming you have a table with an auto-incrementing numeric primary key, you could do the following:

DELETE FROM tbl WHERE id <> 0

What is SuppressWarnings ("unchecked") in Java?

Simply: It's a warning by which the compiler indicates that it cannot ensure type safety.

JPA service method for example:

@SuppressWarnings("unchecked")
public List<User> findAllUsers(){
    Query query = entitymanager.createQuery("SELECT u FROM User u");
    return (List<User>)query.getResultList();
}

If I didn'n anotate the @SuppressWarnings("unchecked") here, it would have a problem with line, where I want to return my ResultList.

In shortcut type-safety means: A program is considered type-safe if it compiles without errors and warnings and does not raise any unexpected ClassCastException s at runtime.

I build on http://www.angelikalanger.com/GenericsFAQ/FAQSections/Fundamentals.html

Removing pip's cache?

A better way to do it is to delete the cache and rebuild it. In this way, if you install it again for other virtualenv, it will use the cache instead of building every time when you install it.

For example, when you install it, it will say it uses cached wheel,

Processing <some_prefix>/Library/Caches/pip/wheels/d0/c4/e4/e49fd07bca8dda00dd6b4bbc606aa05a25aacb00d45747a47a/horovod-0.19.3-cp37-cp37m-macosx_10_9_x86_64.wh

Just delete that one and restart your install.

What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

@Garret Wilson Thank you so much! As a noob to android coding, I've been stuck with the preferences incompatibility issue for so many hours, and I find it so disappointing they deprecated the use of some methods/approaches for new ones that aren't supported by the older APIs thus having to resort to all sorts of workarounds to make your app work in a wide range of devices. It's really frustrating!

Your class is great, for it allows you to keep working in new APIs wih preferences the way it used to be, but it's not backward compatible. Since I'm trying to reach a wide range of devices I tinkered with it a bit to make it work in pre API 11 devices as well as in newer APIs:

import android.annotation.TargetApi;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;

public class MyPrefsActivity extends PreferenceActivity
{
    private static int prefs=R.xml.myprefs;

    @Override
    protected void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        try {
            getClass().getMethod("getFragmentManager");
            AddResourceApi11AndGreater();
        } catch (NoSuchMethodException e) { //Api < 11
            AddResourceApiLessThan11();
        }
    }

    @SuppressWarnings("deprecation")
    protected void AddResourceApiLessThan11()
    {
        addPreferencesFromResource(prefs);
    }

    @TargetApi(11)
    protected void AddResourceApi11AndGreater()
    {
        getFragmentManager().beginTransaction().replace(android.R.id.content,
                new PF()).commit();
    }

    @TargetApi(11)
    public static class PF extends PreferenceFragment
    {       
        @Override
        public void onCreate(final Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(MyPrefsActivity.prefs); //outer class
            // private members seem to be visible for inner class, and
            // making it static made things so much easier
        }
    }
}

Tested in two emulators (2.2 and 4.2) with success.

Why my code looks so crappy:

I'm a noob to android coding, and I'm not the greatest java fan.

In order to avoid the deprecated warning and to force Eclipse to allow me to compile I had to resort to annotations, but these seem to affect only classes or methods, so I had to move the code onto two new methods to take advantage of this.

I wouldn't like having to write my xml resource id twice anytime I copy&paste the class for a new PreferenceActivity, so I created a new variable to store this value.

I hope this will be useful to somebody else.

P.S.: Sorry for my opinionated views, but when you come new and find such handicaps, you can't help it but to get frustrated!

How to make <div> fill <td> height

Modify the background image of the <td> itself.

Or apply some css to the div:

.thatSetsABackgroundWithAnIcon{
    height:100%;
}

Convert `List<string>` to comma-separated string

Follow this:

       List<string> name = new List<string>();   

        name.Add("Latif");

        name.Add("Ram");

        name.Add("Adam");
        string nameOfString = (string.Join(",", name.Select(x => x.ToString()).ToArray()));

Can't include C++ headers like vector in Android NDK

In android NDK go to android-ndk-r9b>/sources/cxx-stl/gnu-libstdc++/4.X/include in linux machines

I've found solution from the below link http://osdir.com/ml/android-ndk/2011-09/msg00336.html

jQuery $.ajax request of dataType json will not retrieve data from PHP script

Try using jQuery.parseJSON when you get the data back.

type: "POST",
dataType: "json",
url: url,
data: { get_member: id },
success: function(data) { 
    response = jQuery.parseJSON(data);
    $("input[ name = type ]:eq(" + response.type + " )")
        .attr("checked", "checked");
    $("input[ name = name ]").val( response.name);
    $("input[ name = fname ]").val( response.fname);
    $("input[ name = lname ]").val( response.lname);
    $("input[ name = email ]").val( response.email);
    $("input[ name = phone ]").val( response.phone);
    $("input[ name = website ]").val( response.website);
    $("#admin_member_img")
        .attr("src", "images/member_images/" + response.image);
},
error: function(error) {
    alert(error);
}

What does %s and %d mean in printf in the C language?

% notation is called a format specifier. For example, %d tells printf() to print an integer. %s to print a string (char *) etc. You should really look it up here: http://google.com/search?q=printf+format+specifiers

No, commas are not used for string concatenation. Commas are for separating arguments passed to a function.

Rewrite all requests to index.php with nginx

Here's the answer of your 2nd question :

   location / {
        rewrite ^/(.*)$ /$1.php last;
}

it's work for me (based my experience), means that all of your blabla.php will rewrite into blabla

like http://yourwebsite.com/index.php to http://yourwebsite.com/index

removeEventListener on anonymous functions in JavaScript

I believe that is the point of an anonymous function, it lacks a name or a way to reference it.

If I were you I would just create a named function, or put it in a variable so you have a reference to it.

var t = {};
var handler = function(e) {
    t.scroll = function(x, y) {
        window.scrollBy(x, y);
    };
    t.scrollTo = function(x, y) {
        window.scrollTo(x, y);
    };
};
window.document.addEventListener("keydown", handler);

You can then remove it by

window.document.removeEventListener("keydown", handler);   

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

<% %> and <%- and -%> are for any Ruby code, but doesn't output the results (e.g. if statements). the two are the same.

<%= %> is for outputting the results of Ruby code

<%# %> is an ERB comment

Here's a good guide: http://api.rubyonrails.org/classes/ActionView/Base.html

String.format() to format double in java

Use DecimalFormat

 NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
 DecimalFormat decimalFormatter = (DecimalFormat) nf;
 decimalFormatter.applyPattern("#,###,###.##");
 String fString = decimalFormatter.format(myDouble);
 System.out.println(fString);

how to configure config.inc.php to have a loginform in phpmyadmin

$cfg['Servers'][$i]['auth_type'] = 'cookie';

should work.

From the manual:

auth_type = 'cookie' prompts for a MySQL username and password in a friendly HTML form. This is also the only way by which one can log in to an arbitrary server (if $cfg['AllowArbitraryServer'] is enabled). Cookie is good for most installations (default in pma 3.1+), it provides security over config and allows multiple users to use the same phpMyAdmin installation. For IIS users, cookie is often easier to configure than http.

Command-line Git on Windows

In the latest version (v2.19 for Windows when I'm writing), if you choose the option "Use git in Windows command prompt" (or sth similar, please read the options carefully when you install git), you should be able to use git commands in windows command prompt or windows powershell without any additional setting. Just remember to restart the command line tool after you install git.

How to access component methods from “outside” in ReactJS?

As of React 16.3 React.createRef can be used, (use ref.current to access)

var ref = React.createRef()

var parent = (
  <div>
    <Child ref={ref} />
    <button onClick={e=>console.log(ref.current)}
  </div>
);

React.renderComponent(parent, document.body)

pinpointing "conditional jump or move depends on uninitialized value(s)" valgrind message

Use the valgrind option --track-origins=yes to have it track the origin of uninitialized values. This will make it slower and take more memory, but can be very helpful if you need to track down the origin of an uninitialized value.

Update: Regarding the point at which the uninitialized value is reported, the valgrind manual states:

It is important to understand that your program can copy around junk (uninitialised) data as much as it likes. Memcheck observes this and keeps track of the data, but does not complain. A complaint is issued only when your program attempts to make use of uninitialised data in a way that might affect your program's externally-visible behaviour.

From the Valgrind FAQ:

As for eager reporting of copies of uninitialised memory values, this has been suggested multiple times. Unfortunately, almost all programs legitimately copy uninitialised memory values around (because compilers pad structs to preserve alignment) and eager checking leads to hundreds of false positives. Therefore Memcheck does not support eager checking at this time.

change values in array when doing foreach

To add or delete elements entirely which would alter the index, by way of extension of zhujy_8833 suggestion of slice() to iterate over a copy, simply count the number of elements you have already deleted or added and alter the index accordingly. For example, to delete elements:

let values = ["A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8"];
let count = 0;
values.slice().forEach((value, index) => {
    if (value === "A2" || value === "A5") {
        values.splice(index - count++, 1);
    };
});
console.log(values);

// Expected: [ 'A0', 'A1', 'A3', 'A4', 'A6', 'A7', 'A8' ]

To insert elements before:

if (value === "A0" || value === "A6" || value === "A8") {
    values.splice(index - count--, 0, 'newVal');
};

// Expected: ['newVal', A0, 'A1', 'A2', 'A3', 'A4', 'A5', 'newVal', 'A6', 'A7', 'newVal', 'A8' ]

To insert elements after:

if (value === "A0" || value === "A6" || value === "A8") {
    values.splice(index - --count, 0, 'newVal');
};

// Expected: ['A0', 'newVal', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'newVal', 'A7', 'A8', 'newVal']

To replace an element:

if (value === "A3" || value === "A4" || value === "A7") {
    values.splice(index, 1, 'newVal');
};

// Expected: [ 'A0', 'A1', 'A2', 'newVal', 'newVal', 'A5', 'A6', 'newVal', 'A8' ]

Note: if implementing both 'before' and 'after' inserts, code should handle 'before' inserts first, other way around would not be as expected

Spring Could not Resolve placeholder

If you are using Spring 3.1 and above, you can use something like...

@Configuration
@PropertySource("classpath:foo.properties")
public class PropertiesWithJavaConfig {

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
  return new PropertySourcesPlaceholderConfigurer();
}
}

You can also go by the xml configuration like...

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
  http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-3.2.xsd">

  <context:property-placeholder location="classpath:foo.properties" />

  </beans>

In earlier versions.

how to check if string value is in the Enum list?

You should use Enum.TryParse to achive your goal

This is a example:

[Flags]
private enum TestEnum
{
    Value1 = 1,
    Value2 = 2
}

static void Main(string[] args)
{
    var enumName = "Value1";
    TestEnum enumValue;

    if (!TestEnum.TryParse(enumName, out enumValue))
    {
        throw new Exception("Wrong enum value");
    }

    // enumValue contains parsed value
}

Get button click inside UITableViewCell

for swift 4:

_x000D_
_x000D_
inside the cellForItemAt ,_x000D_
   _x000D_
cell.chekbx.addTarget(self, action: #selector(methodname), for: .touchUpInside)_x000D_
_x000D_
then outside of cellForItemAt_x000D_
@objc func methodname()_x000D_
{_x000D_
//your function code_x000D_
}
_x000D_
_x000D_
_x000D_

How to delete an SVN project from SVN repository

There's no concept of "project" in svn. So, feel free to delete whatever you think belongs to the project.

Best way to write to the console in PowerShell

The middle one writes to the pipeline. Write-Host and Out-Host writes to the console. 'echo' is an alias for Write-Output which writes to the pipeline as well. The best way to write to the console would be using the Write-Host cmdlet.

When an object is written to the pipeline it can be consumed by other commands in the chain. For example:

"hello world" | Do-Something

but this won't work since Write-Host writes to the console, not to the pipeline (Do-Something will not get the string):

Write-Host "hello world" | Do-Something

Laravel Mail::send() sending to multiple to or bcc addresses

If you want to send emails simultaneously to all the admins, you can do something like this:

In your .env file add all the emails as comma separated values:

[email protected],[email protected],[email protected]

so when you going to send the email just do this (yes! the 'to' method of message builder instance accepts an array):

So,

$to = explode(',', env('ADMIN_EMAILS'));

and...

$message->to($to);

will now send the mail to all the admins.

Cross Browser Flash Detection in Javascript

You could use closure compiler to generate a small, cross-browser flash detection:

// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @formatting pretty_print
// @use_closure_library true
// ==/ClosureCompiler==

// ADD YOUR CODE HERE
goog.require('goog.userAgent.flash');
if (goog.userAgent.flash.HAS_FLASH) {
    alert('flash version: '+goog.userAgent.flash.VERSION);
}else{
    alert('no flash found');
}

which results in the following "compiled" code:

var a = !1,
    b = "";

function c(d) {
    d = d.match(/[\d]+/g);
    d.length = 3;
    return d.join(".")
}
if (navigator.plugins && navigator.plugins.length) {
    var e = navigator.plugins["Shockwave Flash"];
    e && (a = !0, e.description && (b = c(e.description)));
    navigator.plugins["Shockwave Flash 2.0"] && (a = !0, b = "2.0.0.11")
} else {
    if (navigator.mimeTypes && navigator.mimeTypes.length) {
        var f = navigator.mimeTypes["application/x-shockwave-flash"];
        (a = f && f.enabledPlugin) && (b = c(f.enabledPlugin.description))
    } else {
        try {
            var g = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"),
                a = !0,
                b = c(g.GetVariable("$version"))
        } catch (h) {
            try {
                g = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"), a = !0, b = "6.0.21"
            } catch (i) {
                try {
                    g = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"), a = !0, b = c(g.GetVariable("$version"))
                } catch (j) {}
            }
        }
    }
}
var k = b;
a ? alert("flash version: " + k) : alert("no flash found");

Count the number of occurrences of a string in a VARCHAR field?

SELECT 
id,
jsondata,    
ROUND (   
    (
        LENGTH(jsondata)
        - LENGTH( REPLACE ( jsondata, "sonal", "") ) 
    ) / LENGTH("sonal")        
)
+
ROUND (   
    (
        LENGTH(jsondata)
        - LENGTH( REPLACE ( jsondata, "khunt", "") ) 
    ) / LENGTH("khunt")        
)
AS count1    FROM test ORDER BY count1 DESC LIMIT 0, 2

Thanks Yannis, your solution worked for me and here I'm sharing same solution for multiple keywords with order and limit.

How do I disable right click on my web page?

If you don't care about alerting the user with a message every time they try to right click, try adding this to your body tag

<body oncontextmenu="return false;">

This will block all access to the context menu (not just from the right mouse button but from the keyboard as well).

However, as mentioned in the other answers, there really is no point adding a right click disabler. Anyone with basic browser knowledge can view the source and extract the information they need.

Can an html element have multiple ids?

ID's should be unique, so you should only use a particular ID once on a page. Classes may be used repeatedly.

check https://www.w3schools.com/html/html_id.asp for more details.

error: Your local changes to the following files would be overwritten by checkout

This error happens when the branch you are switching to, has changes that your current branch doesn't have.

If you are seeing this error when you try to switch to a new branch, then your current branch is probably behind one or more commits. If so, run:

git fetch

You should also remove dependencies which may also conflict with the destination branch.

For example, for iOS developers:

pod deintegrate

then try checking out a branch again.

If the desired branch isn't new you can either cherry pick a commit and fix the conflicts or stash the changes and then fix the conflicts.

1. Git Stash (recommended)

git stash
git checkout <desiredBranch>
git stash apply

2. Cherry pick (more work)

git add <your file>
git commit -m "Your message"
git log

Copy the sha of your commit. Then discard unwanted changes:

git checkout .
git checkout -- . 
git clean -f -fd -fx

Make sure your branch is up to date:

git fetch

Then checkout to the desired branch

git checkout <desiredBranch>

Then cherry pick the other commit:

git cherry-pick <theSha>

Now fix the conflict.

  1. Otherwise, your other option is to abandon your current branches changes with:
git checkout -f branch

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

just put all apache comons jar and file upload jar in lib folder of tomcat

IIS: Display all sites and bindings in PowerShell

function Get-ADDWebBindings {
param([string]$Name="*",[switch]$http,[switch]$https)
    try {
    if (-not (Get-Module WebAdministration)) { Import-Module WebAdministration }
    Get-WebBinding | ForEach-Object { $_.ItemXPath -replace '(?:.*?)name=''([^'']*)(?:.*)', '$1' } | Sort | Get-Unique | Where-Object {$_ -like $Name} | ForEach-Object {
        $n=$_
        Get-WebBinding | Where-Object { ($_.ItemXPath -replace '(?:.*?)name=''([^'']*)(?:.*)', '$1') -like $n } | ForEach-Object {
            if ($http -or $https) {
                if ( ($http -and ($_.protocol -like "http")) -or ($https -and ($_.protocol -like "https")) ) {
                    New-Object psobject -Property @{Name = $n;Protocol=$_.protocol;Binding = $_.bindinginformation}
                }
            } else {
                New-Object psobject -Property @{Name = $n;Protocol=$_.protocol;Binding = $_.bindinginformation}
            }
        }
    }
    }
    catch {
       $false
    }
}

Append lines to a file using a StreamWriter

Try this:

StreamWriter file2 = new StreamWriter(@"c:\file.txt", true);
file2.WriteLine(someString);
file2.Close();

Write a file on iOS

May be this is useful to you.

//Method writes a string to a text file
-(void) writeToTextFile{
        //get the documents directory:
        NSArray *paths = NSSearchPathForDirectoriesInDomains
            (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        //make a file name to write the data to using the documents directory:
        NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                                                      documentsDirectory];
        //create content - four lines of text
        NSString *content = @"One\nTwo\nThree\nFour\nFive";
        //save content to the documents directory
        [content writeToFile:fileName 
                         atomically:NO 
                               encoding:NSUTF8StringEncoding 
                                      error:nil];

}


//Method retrieves content from documents directory and
//displays it in an alert
-(void) displayContent{
        //get the documents directory:
        NSArray *paths = NSSearchPathForDirectoriesInDomains
                        (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        //make a file name to write the data to using the documents directory:
        NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                                                      documentsDirectory];
        NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
                                                      usedEncoding:nil
                                                             error:nil];
        //use simple alert from my library (see previous post for details)
        [ASFunctions alert:content];
        [content release];

}

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

I was facing this issue for long time. Finally it was issue of ssh-add. Git ssh credentials were not taken into consideration.

Check following command might work for you:

ssh-add

python pandas remove duplicate columns

Here's a one line solution to remove columns based on duplicate column names:

df = df.loc[:,~df.columns.duplicated()]

How it works:

Suppose the columns of the data frame are ['alpha','beta','alpha']

df.columns.duplicated() returns a boolean array: a True or False for each column. If it is False then the column name is unique up to that point, if it is True then the column name is duplicated earlier. For example, using the given example, the returned value would be [False,False,True].

Pandas allows one to index using boolean values whereby it selects only the True values. Since we want to keep the unduplicated columns, we need the above boolean array to be flipped (ie [True, True, False] = ~[False,False,True])

Finally, df.loc[:,[True,True,False]] selects only the non-duplicated columns using the aforementioned indexing capability.

Note: the above only checks columns names, not column values.

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

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

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

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

Despite all the great answers above and due to me being new to Django, I was still stuck. Here's my explanation from a very newbie perspective.

models.py

class Author(models.Model):
    name = models.CharField(max_length=255)

class Book(models.Model):
    author = models.ForeignKey(Author)
    title = models.CharField(max_length=255)

admin.py (Incorrect Way) - you think it would work by using 'model__field' to reference, but it doesn't

class BookAdmin(admin.ModelAdmin):
    model = Book
    list_display = ['title', 'author__name', ]

admin.site.register(Book, BookAdmin)

admin.py (Correct Way) - this is how you reference a foreign key name the Django way

class BookAdmin(admin.ModelAdmin):
    model = Book
    list_display = ['title', 'get_name', ]

    def get_name(self, obj):
        return obj.author.name
    get_name.admin_order_field  = 'author'  #Allows column order sorting
    get_name.short_description = 'Author Name'  #Renames column head

    #Filtering on side - for some reason, this works
    #list_filter = ['title', 'author__name']

admin.site.register(Book, BookAdmin)

For additional reference, see the Django model link here

How to view table contents in Mysql Workbench GUI?

After displaying the first 1000 records, you can page through them by clicking on the icon beside "Fetch rows:" in the header of the result grid.

How to set Angular 4 background image?

If you plan using background images a lot throughout your project you may find it useful to create a really simple custom pipe that will create the url for you.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'asUrl'
})
export class BackgroundUrlPipe implements PipeTransform {

  transform(value: string): string {
    return `url(./images/${value})`
  }

}

Then you can add background images without all the string concatenation.

<div [ngStyle]="{ background: trls.img | asUrl }"></div>

What's the difference between emulation and simulation?

I was confused between the two processes. I found this simple explaination about the difference between Emulators and Simulators

  1. Simulator:
    Suppose you have written assembly program in a file and corresponding exe file is ready. The simulator is the pc software which reads the instructions from the exe and 'minmics' the operation of the processor.

  2. Emulator:
    Emulator is a (PC software + a processor). The Processor can be plugged into the TARGET BOARD when you want to test the developed software in real time to check run time bugs. When not in use it can be unplugged. The Processor will have a parallel or JTAG interface with the PC for downloading the exe file for execution.

Hence, whereas the Simulator is slow in execution, Emulator will be able to give real time verification of the developed code. Generally you will test your developed code on simulator first and then go for checking on emulator.

source : http://www.dsprelated.com/groups/c6x/show/148.php

What is the equivalent of the C++ Pair<L,R> in Java?

This is Java. You have to make your own tailored Pair class with descriptive class and field names, and not to mind that you will reinvent the wheel by writing hashCode()/equals() or implementing Comparable again and again.

How to check a not-defined variable in JavaScript

Just do something like below:

function isNotDefined(value) {
  return typeof value === "undefined";
}

and call it like:

isNotDefined(undefined); //return true
isNotDefined('Alireza'); //return false

Where is svn.exe in my machine?

TortoiseSVN 1.7 has an option for installing the command line tools.

It isn't checked by default, but you can run the installer again and select it. It will also automatically update your PATH environment variable.

Git push failed, "Non-fast forward updates were rejected"

This is what worked for me. It can be found in git documentation here

If you are on your desired branch you can do this:

git fetch origin
# Fetches updates made to an online repository
git merge origin YOUR_BRANCH_NAME
# Merges updates made online with your local work

css selector to match an element without attribute x

Just wanted to add to this, you can have the :not selector in oldIE using selectivizr: http://selectivizr.com/

Modify a Column's Type in sqlite3

It is possible by recreating table.Its work for me please follow following step:

  1. create temporary table using as select * from your table
  2. drop your table, create your table using modify column type
  3. now insert records from temp table to your newly created table
  4. drop temporary table

do all above steps in worker thread to reduce load on uithread

String or binary data would be truncated. The statement has been terminated

Specify a size for the item and warehouse like in the [dbo].[testing1] FUNCTION

@trackingItems1 TABLE (
item       nvarchar(25)  NULL, -- 25 OR equal size of your item column
warehouse   nvarchar(25) NULL, -- same as above
price int   NULL

) 

Since in MSSQL only saying only nvarchar is equal to nvarchar(1) hence the values of the column from the stock table are truncated

Logarithmic returns in pandas dataframe

Here is one way to calculate log return using .shift(). And the result is similar to but not the same as the gross return calculated by pct_change(). Can you upload a copy of your sample data (dropbox share link) to reproduce the inconsistency you saw?

import pandas as pd
import numpy as np

np.random.seed(0)
df = pd.DataFrame(100 + np.random.randn(100).cumsum(), columns=['price'])
df['pct_change'] = df.price.pct_change()
df['log_ret'] = np.log(df.price) - np.log(df.price.shift(1))

Out[56]: 
       price  pct_change  log_ret
0   101.7641         NaN      NaN
1   102.1642      0.0039   0.0039
2   103.1429      0.0096   0.0095
3   105.3838      0.0217   0.0215
4   107.2514      0.0177   0.0176
5   106.2741     -0.0091  -0.0092
6   107.2242      0.0089   0.0089
7   107.0729     -0.0014  -0.0014
..       ...         ...      ...
92  101.6160      0.0021   0.0021
93  102.5926      0.0096   0.0096
94  102.9490      0.0035   0.0035
95  103.6555      0.0069   0.0068
96  103.6660      0.0001   0.0001
97  105.4519      0.0172   0.0171
98  105.5788      0.0012   0.0012
99  105.9808      0.0038   0.0038

[100 rows x 3 columns]

What's the difference between primitive and reference types?

these are primitive data types

  • boolean
  • character
  • byte
  • short
  • integer
  • long
  • float
  • double

saved in stack in the memory which is managed memory on the other hand object data type or reference data type stored in head in the memory managed by GC

this is the most important difference

Declaring functions in JSP?

You need to enclose that in <%! %> as follows:

<%!

public String getQuarter(int i){
String quarter;
switch(i){
        case 1: quarter = "Winter";
        break;

        case 2: quarter = "Spring";
        break;

        case 3: quarter = "Summer I";
        break;

        case 4: quarter = "Summer II";
        break;

        case 5: quarter = "Fall";
        break;

        default: quarter = "ERROR";
}

return quarter;
}

%>

You can then invoke the function within scriptlets or expressions:

<%
     out.print(getQuarter(4));
%>

or

<%= getQuarter(17) %>

Excel: How to check if a cell is empty with VBA?

This site uses the method isEmpty().

Edit: content grabbed from site, before the url will going to be invalid.

Worksheets("Sheet1").Range("A1").Sort _
    key1:=Worksheets("Sheet1").Range("A1")
Set currentCell = Worksheets("Sheet1").Range("A1")
Do While Not IsEmpty(currentCell)
    Set nextCell = currentCell.Offset(1, 0)
    If nextCell.Value = currentCell.Value Then
        currentCell.EntireRow.Delete
    End If
    Set currentCell = nextCell
Loop

In the first step the data in the first column from Sheet1 will be sort. In the second step, all rows with same data will be removed.

batch script - run command on each file in directory

for /r %%v in (*.xls) do ssconvert "%%v" "%%vx"

a couple have people have asked me to explain this, so:

Part 1: for /r %%v in (*.xls)

This part returns an array of files in the current directory that have the xls extension. The %% may look a little curious. This is basically the special % character from command line as used in %PATH% or %TEMP%. To use it in a batch file we need to escape it like so: %%PATH%% or %%TEMP%%. In this case we are simply escaping the temporary variable v, which will hold our array of filenames.

We are using the /r switch to search for files recursively, so any matching files in child folders will also be located.

Part 2: do ssconvert "%%v" "%%vx"

This second part is what will get executed once per matching filename, so if the following files were present in the current folder:

c:\temp\mySheet.xls, c:\temp\mySheet_yesterday.xls, c:\temp\mySheet_20160902.xls

the following commands would be executed:

ssconvert "c:\temp\mySheet.xls" "c:\temp\mySheet.xlsx" ssconvert "c:\temp\mySheet_yesterday.xls" "c:\temp\mySheet_yesterday.xlsx" ssconvert "c:\temp\mySheet_20160902.xls" "c:\temp\mySheet_20160902.xlsx"

svn cleanup: sqlite: database disk image is malformed

Integrity check

sqlite3 .svn/wc.db "pragma integrity_check"

Clean up

sqlite3 .svn/wc.db "reindex nodes"
sqlite3 .svn/wc.db "reindex pristine"

Alternatively

You may be able to dump the contents of the database that can be read to a backup file, then slurp it back into an new database file:

sqlite3 .svn/wc.db

sqlite> .mode insert
sqlite> .output dump_all.sql
sqlite> .dump
sqlite> .exit

mv .svn/wc.db .svn/wc-corrupt.db
sqlite3 .svn/wc.db

sqlite> .read dump_all.sql
sqlite> .exit

Batch Extract path and filename from a variable

if you want infos from the actual running batchfile, try this :

@echo off
set myNameFull=%0
echo myNameFull     %myNameFull%
set myNameShort=%~n0
echo myNameShort    %myNameShort%
set myNameLong=%~nx0
echo myNameLong     %myNameLong%
set myPath=%~dp0
echo myPath         %myPath%
set myLogfileWpath=%myPath%%myNameShort%.log
echo myLogfileWpath %myLogfileWpath%

more samples? C:> HELP CALL

%0 = parameter 0 = batchfile %1 = parameter 1 - 1st par. passed to batchfile... so you can try that stuff (e.g. "~dp") between 1st (e.g. "%") and last (e.g. "1") also for parameters

Returning a boolean from a Bash function

Use 0 for true and 1 for false.

Sample:

#!/bin/bash

isdirectory() {
  if [ -d "$1" ]
  then
    # 0 = true
    return 0 
  else
    # 1 = false
    return 1
  fi
}


if isdirectory $1; then echo "is directory"; else echo "nopes"; fi

Edit

From @amichair's comment, these are also possible

isdirectory() {
  if [ -d "$1" ]
  then
    true
  else
    false
  fi
}


isdirectory() {
  [ -d "$1" ]
}

How do I format a date in Jinja2?

Made it.

from datetime import datetime
dateNow = datetime.now().strftime('%Y%m%d')

AngularJs - ng-model in a SELECT

You dont need to define option tags, you can do this using the ngOptions directive: https://docs.angularjs.org/api/ng/directive/ngOptions

<select class="form-control" ng-change="unitChanged()" ng-model="data.unit" ng-options="unit.id as unit.label for unit in units"></select>

Concatenating Files And Insert New Line In Between Files

If it were me doing it I'd use sed:

sed -e '$s/$/\n/' -s *.txt > finalfile.txt

In this sed pattern $ has two meanings, firstly it matches the last line number only (as a range of lines to apply a pattern on) and secondly it matches the end of the line in the substitution pattern.

If your version of sed doesn't have -s (process input files separately) you can do it all as a loop though:

for f in *.txt ; do sed -e '$s/$/\n/' $f ; done > finalfile.txt

How to play or open *.mp3 or *.wav sound file in c++ program?

http://sfml-dev.org/documentation/2.0/classsf_1_1Music.php

SFML does not have mp3 support as another has suggested. What I always do is use Audacity and make all my music into ogg, and leave all my sound effects as wav.

Loading and playing a wav is simple (crude example):

http://www.sfml-dev.org/tutorials/2.0/audio-sounds.php

#include <SFML/Audio.hpp>
...
sf::SoundBuffer buffer;
if (!buffer.loadFromFile("sound.wav")){
    return -1;
}
sf::Sound sound;
sound.setBuffer(buffer);
sound.play();

Streaming an ogg music file is also simple:

#include <SFML/Audio.hpp>
...
sf::Music music;
if (!music.openFromFile("music.ogg"))
    return -1; // error
music.play();

How to write a simple Java program that finds the greatest common divisor between two numbers?

public static int GCD(int x, int y) {   
    int r;
    while (y!=0) {
        r = x%y;
        x = y;
        y = r;
    }
    return x;
}

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

I tried to install only LocalDB, which was missed in my VS 2015 installation. Followed below URL & selectively download the LocalDB (2012) installer which is only 33mb in size :)

https://www.microsoft.com/en-us/download/details.aspx?id=29062

If you are looking for the SQL Server Data Tool for Visual Studio 2015 Integration, then Please download that from :

https://msdn.microsoft.com/en-us/mt186501

How to get am pm from the date time string using moment js

You are using the wrong format tokens when parsing your input. You should use ddd for an abbreviation of the name of day of the week, DD for day of the month, MMM for an abbreviation of the month's name, YYYY for the year, hh for the 1-12 hour, mm for minutes and A for AM/PM. See moment(String, String) docs.

Here is a working live sample:

_x000D_
_x000D_
console.log( moment('Mon 03-Jul-2017, 11:00 AM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );_x000D_
console.log( moment('Mon 03-Jul-2017, 11:00 PM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Trusting all certificates with okHttp

Following method is deprecated

sslSocketFactory(SSLSocketFactory sslSocketFactory)

Consider updating it to

sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)

How to download a file with Node.js (without using third-party libraries)?

download.js (i.e. /project/utils/download.js)

const fs = require('fs');
const request = require('request');

const download = (uri, filename, callback) => {
    request.head(uri, (err, res, body) => {
        console.log('content-type:', res.headers['content-type']);
        console.log('content-length:', res.headers['content-length']);

        request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
    });
};

module.exports = { download };


app.js

... 
// part of imports
const { download } = require('./utils/download');

...
// add this function wherever
download('https://imageurl.com', 'imagename.jpg', () => {
  console.log('done')
});

How to get document height and width without using jquery

Even the last example given on http://www.howtocreate.co.uk/tutorials/javascript/browserwindow is not working on Quirks mode. Easier to find than I thought, this seems to be the solution(extracted from latest jquery code):

Math.max(
    document.documentElement["clientWidth"],
    document.body["scrollWidth"],
    document.documentElement["scrollWidth"],
    document.body["offsetWidth"],
    document.documentElement["offsetWidth"]
);

just replace Width for "Height" to get Height.

Convert DataTable to IEnumerable<T>

I wrote an article on this subject over here. I think it could help you.

Typically it's doing something like that:

static void Main(string[] args)
{
    // Convert from a DataTable source to an IEnumerable.
    var usersSourceDataTable = CreateMockUserDataTable();
    var usersConvertedList = usersSourceDataTable.ToEnumerable<User>();

    // Convert from an IEnumerable source to a DataTable.
    var usersSourceList = CreateMockUserList();
    var usersConvertedDataTable = usersSourceList.ToDataTable<User>();
}

jQuery vs document.querySelectorAll

Old question, but half a decade later, it’s worth revisiting. Here I am only discussing the selector aspect of jQuery.

document.querySelector[All] is supported by all current browsers, down to IE8, so compatibility is no longer an issue. I have also found no performance issues to speak of (it was supposed to be slower than document.getElementById, but my own testing suggests that it’s slightly faster).

Therefore when it comes to manipulating an element directly, it is to be preferred over jQuery.

For example:

var element=document.querySelector('h1');
element.innerHTML='Hello';

is vastly superior to:

var $element=$('h1');
$element.html('hello');

In order to do anything at all, jQuery has to run through a hundred lines of code (I once traced through code such as the above to see what jQuery was actually doing with it). This is clearly a waste of everyone’s time.

The other significant cost of jQuery is the fact that it wraps everything inside a new jQuery object. This overhead is particularly wasteful if you need to unwrap the object again or to use one of the object methods to deal with properties which are already exposed on the original element.

Where jQuery has an advantage, however, is in how it handles collections. If the requirement is to set properties of multiple elements, jQuery has a built-in each method which allows something like this:

var $elements=$('h2');  //  multiple elements
$elements.html('hello');

To do so with Vanilla JavaScript would require something like this:

var elements=document.querySelectorAll('h2');
elements.forEach(function(e) {
    e.innerHTML='Hello';
});

which some find daunting.

jQuery selectors are also slightly different, but modern browsers (excluding IE8) won’t get much benefit.

As a rule, I caution against using jQuery for new projects:

  • jQuery is an external library adding to the overhead of the project, and to your dependency on third parties.
  • jQuery function is very expensive, processing-wise.
  • jQuery imposes a methodology which needs to be learned and may compete with other aspects of your code.
  • jQuery is slow to expose new features in JavaScript.

If none of the above matters, then do what you will. However, jQuery is no longer as important to cross-platform development as it used to be, as modern JavaScript and CSS go a lot further than they used to.

This makes no mention of other features of jQuery. However, I think that they, too, need a closer look.

Text blinking jQuery

$.fn.blink = function (delay) {
  delay = delay || 500;
  return this.each(function () {
    var element = $(this);
    var interval = setInterval(function () {
      element.fadeOut((delay / 3), function() {
        element.fadeIn(delay / 3);
      })
    }, delay);
    element.data('blinkInterval', interval);
  });
};

$.fn.stopBlinking = function() {
  return this.each(function() {
    var element = $(this);
    element.stop(true, true);
    clearInterval(element.data('blinkInterval'));
  });
};

SQL Server datetime LIKE select?

The LIKE operator does not work with date parts like month or date but the DATEPART operator does.

Command to find out all accounts whose Open Date was on the 1st:

SELECT * 
  FROM Account 
 WHERE DATEPART(DAY, CAST(OpenDt AS DATE)) = 1`

*CASTING OpenDt because it's value is in DATETIME and not just DATE.

How can I declare dynamic String array in Java

What your looking for is the DefaultListModel - Dynamic String List Variable.

Here is a whole class that uses the DefaultListModel as though it were the TStringList of Delphi. The difference is that you can add Strings to the list without limitation and you have the same ability at getting a single entry by specifying the entry int.

FileName: StringList.java

package YOUR_PACKAGE_GOES_HERE;

//This is the StringList Class by i2programmer
//You may delete these comments
//This code is offered freely at no requirements
//You may alter the code as you wish
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;

public class StringList {

    public static String OutputAsString(DefaultListModel list, int entry) {
        return GetEntry(list, entry);
    }

    public static Object OutputAsObject(DefaultListModel list, int entry) {
        return GetEntry(list, entry);
    }

    public static int OutputAsInteger(DefaultListModel list, int entry) {
        return Integer.parseInt(list.getElementAt(entry).toString());
    }

    public static double OutputAsDouble(DefaultListModel list, int entry) {
        return Double.parseDouble(list.getElementAt(entry).toString());
    }

    public static byte OutputAsByte(DefaultListModel list, int entry) {
        return Byte.parseByte(list.getElementAt(entry).toString());
    }

    public static char OutputAsCharacter(DefaultListModel list, int entry) {
        return list.getElementAt(entry).toString().charAt(0);
    }

    public static String GetEntry(DefaultListModel list, int entry) {
        String result = "";
        result = list.getElementAt(entry).toString();
        return result;
    }

    public static void AddEntry(DefaultListModel list, String entry) {
        list.addElement(entry);
    }

    public static void RemoveEntry(DefaultListModel list, int entry) {
        list.removeElementAt(entry);
    }

    public static DefaultListModel StrToList(String input, String delimiter) {
        DefaultListModel dlmtemp = new DefaultListModel();
        input = input.trim();
        delimiter = delimiter.trim();
        while (input.toLowerCase().contains(delimiter.toLowerCase())) {
            int index = input.toLowerCase().indexOf(delimiter.toLowerCase());
            dlmtemp.addElement(input.substring(0, index).trim());
            input = input.substring(index + delimiter.length(), input.length()).trim();
        }
        return dlmtemp;
    }

    public static String ListToStr(DefaultListModel list, String delimiter) {
        String result = "";
        for (int i = 0; i < list.size(); i++) {
            result = list.getElementAt(i).toString() + delimiter;
        }
        result = result.trim();
        return result;
    }

    public static String LoadFile(String inputfile) throws IOException {
        int len;
        char[] chr = new char[4096];
        final StringBuffer buffer = new StringBuffer();
        final FileReader reader = new FileReader(new File(inputfile));
        try {
            while ((len = reader.read(chr)) > 0) {
                buffer.append(chr, 0, len);
            }
        } finally {
            reader.close();
        }
        return buffer.toString();
    }

    public static void SaveFile(String outputfile, String outputstring) {
        try {
            FileWriter f0 = new FileWriter(new File(outputfile));
            f0.write(outputstring);
            f0.flush();
            f0.close();
        } catch (IOException ex) {
            Logger.getLogger(StringList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

OutputAs methods are for outputting an entry as int, double, etc... so that you don't have to convert from string on the other side.

SaveFile & LoadFile are to save and load strings to and from files.

StrToList & ListToStr are to place delimiters between each entry.

ex. 1<>2<>3<>4<> if "<>" is the delimiter and 1 2 3 & 4 are the entries.

AddEntry & GetEntry are to add and get strings to and from the DefaultListModel.

RemoveEntry is to delete a string from the DefaultListModel.

You use the DefaultListModel instead of an array here like this:

DefaultListModel list = new DefaultListModel();
//now that you have a list, you can run it through the above class methods.

ngrok command not found

On Windows ngrok.cmd works well from Git Bash, not ngrok

how to execute a scp command with the user name and password in one line

Thanks for your feed back got it to work I used the sshpass tool.

sshpass -p 'password' scp [email protected]:sys_config /var/www/dev/

Best way to check if object exists in Entity Framework?

Best way to do it

Regardless of what your object is and for what table in the database the only thing you need to have is the primary key in the object.

C# Code

var dbValue = EntityObject.Entry(obj).GetDatabaseValues();
if (dbValue == null)
{
   Don't exist
}

VB.NET Code

Dim dbValue = EntityObject.Entry(obj).GetDatabaseValues()
If dbValue Is Nothing Then
   Don't exist
End If

How to access environment variable values?

For django see (https://github.com/joke2k/django-environ)

$ pip install django-environ

import environ
env = environ.Env(
# set casting, default value
DEBUG=(bool, False)
)
# reading .env file
environ.Env.read_env()

# False if not in os.environ
DEBUG = env('DEBUG')

# Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')

HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents

Just in case if anyone reached here looking for solution, here is how i resolved it. By mistake I deleted all files from my server ( bin directory ) but when i recopied all files i missed App_global.asax.dll and App_global.asax.compiled files. Because these files were missing IIS was giving me this error

403 - Forbidden: Access is denied.

As soon as i added these files, it started working perfectly fine.

Bootstrap: wider input field

I am going to assume you were having the same issue I was. Even though you specify larger sizes for the TextBox and mark it as important, the box would not get larger. That is likely because in your site.css file the MaxWidth is being set to 280px.

Add a style attribute to your input to remove the MaxWidth like this:

<input type="text"  style="max-width:none !important" class="input-medium">

Find and kill a process in one line using bash and regex

One liner:

ps aux | grep -i csp_build | awk '{print $2}' | xargs sudo kill -9

  • Print out column 2: awk '{print $2}'
  • sudo is optional
  • Run kill -9 5124, kill -9 5373 etc (kill -15 is more graceful but slightly slower)

Bonus:

I also have 2 shortcut functions defined in my .bash_profile (~/.bash_profile is for osx, you have to see what works for your *nix machine).

  1. p keyword
    • lists out all Processes containing keyword
    • usage e.g: p csp_build , p python etc

bash_profile code:

# FIND PROCESS
function p(){
        ps aux | grep -i $1 | grep -v grep
}
  1. ka keyword
    • Kills All processes that have this keyword
    • usage e.g: ka csp_build , ka python etc
    • optional kill level e.g: ka csp_build 15, ka python 9

bash_profile code:

# KILL ALL
function ka(){

    cnt=$( p $1 | wc -l)  # total count of processes found
    klevel=${2:-15}       # kill level, defaults to 15 if argument 2 is empty

    echo -e "\nSearching for '$1' -- Found" $cnt "Running Processes .. "
    p $1

    echo -e '\nTerminating' $cnt 'processes .. '

    ps aux  |  grep -i $1 |  grep -v grep   | awk '{print $2}' | xargs sudo kill -klevel
    echo -e "Done!\n"

    echo "Running search again:"
    p "$1"
    echo -e "\n"
}

In where shall I use isset() and !empty()

Neither is a good way to check for valid input.

  • isset() is not sufficient because – as has been noted already – it considers an empty string to be a valid value.
  • ! empty() is not sufficient either because it rejects '0', which could be a valid value.

Using isset() combined with an equality check against an empty string is the bare minimum that you need to verify that an incoming parameter has a value without creating false negatives:

if( isset($_GET['gender']) and ($_GET['gender'] != '') )
{
  ...
}

But by "bare minimum", I mean exactly that. All the above code does is determine whether there is some value for $_GET['gender']. It does not determine whether the value for $_GET['gender'] is valid (e.g., one of ("Male", "Female","FileNotFound")).

For that, see Josh Davis's answer.

How to fully clean bin and obj folders within Visual Studio?

This is how I do with a batch file to delete all BIN and OBJ folders recursively.

  • Create an empty file and name it DeleteBinObjFolders.bat
  • Copy-paste code the below code into the DeleteBinObjFolders.bat
  • Move the DeleteBinObjFolders.bat file in the same folder with your solution (*.sln) file.
@echo off
@echo Deleting all BIN and OBJ folders...
for /d /r . %%d in (bin,obj) do @if exist "%%d" rd /s/q "%%d"
@echo BIN and OBJ folders successfully deleted :) Close the window.
pause > nul

How to increase dbms_output buffer?

You can Enable DBMS_OUTPUT and set the buffer size. The buffer size can be between 1 and 1,000,000.

dbms_output.enable(buffer_size IN INTEGER DEFAULT 20000);
exec dbms_output.enable(1000000);

Check this

EDIT

As per the comment posted by Frank and Mat, you can also enable it with Null

exec dbms_output.enable(NULL);

buffer_size : Upper limit, in bytes, the amount of buffered information. Setting buffer_size to NULL specifies that there should be no limit. The maximum size is 1,000,000, and the minimum is 2,000 when the user specifies buffer_size (NOT NULL).

Remap values in pandas column with a dict

You can use .replace. For example:

>>> df = pd.DataFrame({'col2': {0: 'a', 1: 2, 2: np.nan}, 'col1': {0: 'w', 1: 1, 2: 2}})
>>> di = {1: "A", 2: "B"}
>>> df
  col1 col2
0    w    a
1    1    2
2    2  NaN
>>> df.replace({"col1": di})
  col1 col2
0    w    a
1    A    2
2    B  NaN

or directly on the Series, i.e. df["col1"].replace(di, inplace=True).

How to calculate cumulative normal distribution?

Alex's answer shows you a solution for standard normal distribution (mean = 0, standard deviation = 1). If you have normal distribution with mean and std (which is sqr(var)) and you want to calculate:

from scipy.stats import norm

# cdf(x < val)
print norm.cdf(val, m, s)

# cdf(x > val)
print 1 - norm.cdf(val, m, s)

# cdf(v1 < x < v2)
print norm.cdf(v2, m, s) - norm.cdf(v1, m, s)

Read more about cdf here and scipy implementation of normal distribution with many formulas here.

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers

Open Project properties by selecting project then go to

View>Properties Windows

and make sure Anonymous Authentication is Enabled

enter image description here

How to use UIVisualEffectView to Blur Image?

If anyone would like the answer in Swift :

var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark) // Change .Dark into .Light if you'd like.

var blurView = UIVisualEffectView(effect: blurEffect)

blurView.frame = theImage.bounds // 'theImage' is an image. I think you can apply this to the view too!

Update :

As of now, it's available under the IB so you don't have to code anything for it :)

Set database timeout in Entity Framework

I extended Ronnie's answer with a fluent implementation so you can use it like so:

dm.Context.SetCommandTimeout(120).Database.SqlQuery...

public static class EF
{
    public static DbContext SetCommandTimeout(this DbContext db, TimeSpan? timeout)
    {
        ((IObjectContextAdapter)db).ObjectContext.CommandTimeout = timeout.HasValue ? (int?) timeout.Value.TotalSeconds : null;

        return db;
    }

    public static DbContext SetCommandTimeout(this DbContext db, int seconds)
    {
        return db.SetCommandTimeout(TimeSpan.FromSeconds(seconds));
    } 
}

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

Hours of problems SOLVED. I had installed the Beta Entity Framework for Oracle and in in visual studio 2010 MVC 3 project I was referencing under the tab .NET the Oracle.DataAccess ... This kept giving me the "Oracle ORA-12154: TNS: Could not..." error. I finally just browsed to the previous Oracle install under c:\Oracle\product.... using the old 10.2.0.100 version of the dll. Finally it works now. Hope it helps someone else.

Node.js server that accepts POST requests

The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.

const http = require('http')

const server = http.createServer(function(request, response) {
  console.dir(request.param)

  if (request.method == 'POST') {
    console.log('POST')
    var body = ''
    request.on('data', function(data) {
      body += data
      console.log('Partial body: ' + body)
    })
    request.on('end', function() {
      console.log('Body: ' + body)
      response.writeHead(200, {'Content-Type': 'text/html'})
      response.end('post received')
    })
  } else {
    console.log('GET')
    var html = `
            <html>
                <body>
                    <form method="post" action="http://localhost:3000">Name: 
                        <input type="text" name="name" />
                        <input type="submit" value="Submit" />
                    </form>
                </body>
            </html>`
    response.writeHead(200, {'Content-Type': 'text/html'})
    response.end(html)
  }
})

const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)


If you use something like Express.js and Bodyparser then it would look like this since Express will handle the request.body concatenation

var express = require('express')
var fs = require('fs')
var app = express()

app.use(express.bodyParser())

app.get('/', function(request, response) {
  console.log('GET /')
  var html = `
    <html>
        <body>
            <form method="post" action="http://localhost:3000">Name: 
                <input type="text" name="name" />
                <input type="submit" value="Submit" />
            </form>
        </body>
    </html>`
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end(html)
})

app.post('/', function(request, response) {
  console.log('POST /')
  console.dir(request.body)
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end('thanks')
})

port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)

How to put a component inside another component in Angular2?

You don't put a component in directives

You register it in @NgModule declarations:

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App , MyChildComponent ],
  bootstrap: [ App ]
})

and then You just put it in the Parent's Template HTML as : <my-child></my-child>

That's it.

Disable back button in react navigation

For latest version of React Navigation, even if you use null in some cases it may still show "back" written!

Go for this in your main app.js under your screen name or just go to your class file and add: -

static navigationOptions = {
   headerTitle:'Disable back Options',
   headerTitleStyle: {color:'white'},
   headerStyle: {backgroundColor:'black'},
   headerTintColor: 'red',
   headerForceInset: {vertical: 'never'},
   headerLeft: " "
}

Why dividing two integers doesn't get a float?

Dividing two integers will result in an integer (whole number) result.

You need to cast one number as a float, or add a decimal to one of the numbers, like a/350.0.

How to programmatically send a 404 response with Express/Node?

IMO the nicest way is to use the next() function:

router.get('/', function(req, res, next) {
    var err = new Error('Not found');
    err.status = 404;
    return next(err);
}

Then the error is handled by your error handler and you can style the error nicely using HTML.

Regular Expressions- Match Anything

Because . Find a single character, except newline or line terminator.

So, to match anything, You can use like this: (.|\n)*?

Hope it helps!

Add line break to 'git commit -m' from the command line

Personally, I find it easiest to modify commit messages after the fact in vi (or whatever your git editor of choice is) rather than on the command line, by doing git commit --amend right after git commit.

'pip' is not recognized as an internal or external command

You need to add the path of your pip installation to your PATH system variable. By default, pip is installed to C:\Python34\Scripts\pip (pip now comes bundled with new versions of python), so the path "C:\Python34\Scripts" needs to be added to your PATH variable.

To check if it is already in your PATH variable, type echo %PATH% at the CMD prompt

To add the path of your pip installation to your PATH variable, you can use the Control Panel or the setx command. For example:

setx PATH "%PATH%;C:\Python34\Scripts"

Note: According to the official documentation, "[v]ariables set with setx variables are available in future command windows only, not in the current command window". In particular, you will need to start a new cmd.exe instance after entering the above command in order to utilize the new environment variable.

Thanks to Scott Bartell for pointing this out.

Node.js spawn child process and get terminal output live

child:

setInterval(function() {
    process.stdout.write("hi");
}, 1000); // or however else you want to run a timer

parent:

require('child_process').fork('./childfile.js');
// fork'd children use the parent's stdio

How can I insert a line break into a <Text> component in React Native?

React won't like you putting HTML <br /> in where it's expecting text, and \ns aren't always rendered unless in a <pre> tag.

Perhaps wrap each line-breaked string (paragraph) in a <p> tag like this:

{text.split("\n").map((line, idx) => <p key={idx}>{line}</p>)}

Don't forget the key if you're iterating React components.

Add column to dataframe with constant value

Single liner works

df['Name'] = 'abc'

Creates a Name column and sets all rows to abc value

How to validate phone numbers using regex

Here's my best try so far. It handles the formats above but I'm sure I'm missing some other possible formats.

^\d?(?:(?:[\+]?(?:[\d]{1,3}(?:[ ]+|[\-.])))?[(]?(?:[\d]{3})[\-/)]?(?:[ ]+)?)?(?:[a-zA-Z2-9][a-zA-Z0-9 \-.]{6,})(?:(?:[ ]+|[xX]|(i:ext[\.]?)){1,2}(?:[\d]{1,5}))?$

Does my application "contain encryption"?

@hisnameisjimmy is correct: You will notice (at least as of today, Dec 1st 2016) when you go to submit your app for review and reach the Export Compliance walkthrough, you'll notice the menu now states that HTTPS is an exempt version of encryption (if you use it for every call):

enter image description here

enter image description here

Take n rows from a spark dataframe and pass to toPandas()

Try it:

def showDf(df, count=None, percent=None, maxColumns=0):
    if (df == None): return
    import pandas
    from IPython.display import display
    pandas.set_option('display.encoding', 'UTF-8')
    # Pandas dataframe
    dfp = None
    # maxColumns param
    if (maxColumns >= 0):
        if (maxColumns == 0): maxColumns = len(df.columns)
        pandas.set_option('display.max_columns', maxColumns)
    # count param
    if (count == None and percent == None): count = 10 # Default count
    if (count != None):
        count = int(count)
        if (count == 0): count = df.count()
        pandas.set_option('display.max_rows', count)
        dfp = pandas.DataFrame(df.head(count), columns=df.columns)
        display(dfp)
    # percent param
    elif (percent != None):
        percent = float(percent)
        if (percent >=0.0 and percent <= 1.0):
            import datetime
            now = datetime.datetime.now()
            seed = long(now.strftime("%H%M%S"))
            dfs = df.sample(False, percent, seed)
            count = df.count()
            pandas.set_option('display.max_rows', count)
            dfp = dfs.toPandas()    
            display(dfp)

Examples of usages are:

# Shows the ten first rows of the Spark dataframe
showDf(df)
showDf(df, 10)
showDf(df, count=10)

# Shows a random sample which represents 15% of the Spark dataframe
showDf(df, percent=0.15) 

Getting rid of \n when using .readlines()

with open('D:\\file.txt', 'r') as f1:
    lines = f1.readlines()
lines = [s[:-1] for s in lines]

What is the default Jenkins password?

I am a Mac OS user & following credential pair worked for me:
Username: admin
Password: admin

Is there a way to select sibling nodes?

Quick:

var siblings = n => [...n.parentElement.children].filter(c=>c!=n)

https://codepen.io/anon/pen/LLoyrP?editors=1011

Get the parent's children as an array, filter out this element.

Edit:

And to filter out text nodes (Thanks pmrotule):

var siblings = n => [...n.parentElement.children].filter(c=>c.nodeType == 1 && c!=n)

Specify the from user when sending email using the mail command

echo "This is the main body of the mail" | mail -s "Subject of the Email" [email protected] -- -f [email protected] -F "Elvis Presley"

or

echo "This is the main body of the mail" | mail -s "Subject of the Email" [email protected] -aFrom:"Elvis Presley<[email protected]>"

Getting execute permission to xp_cmdshell

I want to complete the answer from tchester.

(1) Enable the xp_cmdshell procedure:

-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO

-- Enable the xp_cmdshell procedure
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE
GO

(2) Create a login 'Domain\TestUser' (windows user) for the non-sysadmin user that has public access to the master database

(3) Grant EXEC permission on the xp_cmdshell stored procedure:

GRANT EXECUTE ON xp_cmdshell TO [Domain\TestUser]

(4) Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account

EXEC sp_xp_cmdshell_proxy_account 'Domain\TestUser', 'pwd'
-- Note: pwd means windows password for [Domain\TestUser] account id on the box.
--       Don't include square brackets around Domain\TestUser.

(5) Grant control server permission to user

USE master;
GRANT CONTROL SERVER TO [Domain\TestUser]
GO

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

Delimiters in MySQL

When you create a stored routine that has a BEGIN...END block, statements within the block are terminated by semicolon (;). But the CREATE PROCEDURE statement also needs a terminator. So it becomes ambiguous whether the semicolon within the body of the routine terminates CREATE PROCEDURE, or terminates one of the statements within the body of the procedure.

The way to resolve the ambiguity is to declare a distinct string (which must not occur within the body of the procedure) that the MySQL client recognizes as the true terminator for the CREATE PROCEDURE statement.

How to run (not only install) an android application using .apk file?

I created terminal aliases to install and run an apk using a single command.

// I use ZSH, here is what I added to my .zshrc file (config file)
// at ~/.zshrc
// If you use bash shell, append it to ~/.bashrc

# Have the adb accessible, by including it in the PATH
export PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:path/to/android_sdk/platform-tools/"

# Setup your Android SDK path in ANDROID_HOME variable
export ANDROID_HOME=~/sdks/android_sdk

# Setup aapt tool so it accessible using a single command
alias aapt="$ANDROID_HOME/build-tools/27.0.3/aapt"

# Install APK to device
# Use as: apkinstall app-debug.apk
alias apkinstall="adb devices | tail -n +2 | cut -sf 1 | xargs -I X adb -s X install -r $1"
# As an alternative to apkinstall, you can also do just ./gradlew installDebug

# Alias for building and installing the apk to connected device
# Run at the root of your project
# $ buildAndInstallApk
alias buildAndInstallApk='./gradlew assembleDebug && apkinstall ./app/build/outputs/apk/debug/app-debug.apk'

# Launch your debug apk on your connected device
# Execute at the root of your android project
# Usage: launchDebugApk
alias launchDebugApk="adb shell monkey -p `aapt dump badging ./app/build/outputs/apk/debug/app-debug.apk | grep -e 'package: name' | cut -d \' -f 2` 1"

# ------------- Single command to build+install+launch apk------------#
# Execute at the root of your android project
# Use as: buildInstallLaunchDebugApk
alias buildInstallLaunchDebugApk="buildAndInstallApk && launchDebugApk"

Note: Here I am building, installing and launching the debug apk which is usually in the path: ./app/build/outputs/apk/debug/app-debug.apk, when this command is executed from the root of the project

If you would like to install and run any other apk, simply replace the path for debug apk with path of your own apk

Here is the gist for the same. I created this because I was having trouble working with Android Studio build reaching around 28 minutes, so I switched over to terminal builds which were around 3 minutes. You can read more about this here

Explanation:

The one alias that I think needs explanation is the launchDebugApk alias. Here is how it is broken down:

The part aapt dump badging ./app/build/outputs/apk/debug/app-debug.apk | grep -e 'package: name basically uses the aapt tool to extract the package name from the apk.

Next, is the command: adb shell monkey -p com.package.name 1, which basically uses the monkey tool to open up the default launcher activity of the installed app on the connected device. The part of com.package.name is replaced by our previous command which takes care of getting the package name from the apk.

Copy every nth line from one sheet to another

Create a macro and use the following code to grab the data and put it in a new sheet (Sheet2):

Dim strValue As String
Dim strCellNum As String
Dim x As String
x = 1

For i = 1 To 700 Step 7
    strCellNum = "A" & i
    strValue = Worksheets("Sheet1").Range(strCellNum).Value
    Debug.Print strValue
    Worksheets("Sheet2").Range("A" & x).Value = strValue
    x = x + 1
Next

Let me know if this helps! JFV

gdb: how to print the current line or find the current line number?

The 'frame' command will give you what you are looking for. (This can be abbreviated just 'f'). Here is an example:

(gdb) frame
\#0  zmq::xsub_t::xrecv (this=0x617180, msg_=0x7ffff00008e0) at xsub.cpp:139
139         int rc = fq.recv (msg_);
(gdb)

Without an argument, 'frame' just tells you where you are at (with an argument it changes the frame). More information on the frame command can be found here.

kill -3 to get java thread dump

In the same location where the JVM's stdout is placed. If you have a Tomcat server, this will be the catalina_(date).out file.

Twitter API returns error 215, Bad Authentication Data

The url with /1.1/ in it is correct, it is the new Twitter API Version 1.1.

But you need an application and authorize your application (and the user) using oAuth.

Read more about this on the Twitter Developers documentation site :)

jQuery: Test if checkbox is NOT checked

if($("#checkbox1").prop('checked') == false){
    alert('checkbox is not checked');
    //do something
}
else
{ 
    alert('checkbox is checked');
}

Count number of tables in Oracle

If you'd like a list of owners, and the count of the number of tables per owner, try:

    SELECT distinct owner, count(table_name) FROM dba_tables GROUP BY owner;

iOS 9 not opening Instagram app with URL SCHEME

From, Session 703 WWDC 2015:

You can continue to use URL schemes when you build your app for iOS 9 and you want to call URL schemes, you will now need to declare them in your apps Info.plist. There is a new key, LSApplicationQueriesSchemes, and here you will need to add the list of schemes you want to are canOpenURL on.

For instance, incase of FB

How to get the difference between two arrays in JavaScript?

to subtract one array from another, simply use the snippet below:

var a1 = ['1','2','3','4','6'];
var a2 = ['3','4','5'];

var items = new Array();

items = jQuery.grep(a1,function (item) {
    return jQuery.inArray(item, a2) < 0;
});

It will returns ['1,'2','6'] that are items of first array which don't exist in the second.

Therefore, according to your problem sample, following code is the exact solution:

var array1 = ["test1", "test2","test3", "test4"];
var array2 = ["test1", "test2","test3","test4", "test5", "test6"];

var _array = new Array();

_array = jQuery.grep(array2, function (item) {
     return jQuery.inArray(item, array1) < 0;
});

Writing a dict to txt file and reading it back?

To store Python objects in files, use the pickle module:

import pickle

a = {
  'a': 1,
  'b': 2
}

with open('file.txt', 'wb') as handle:
  pickle.dump(a, handle)

with open('file.txt', 'rb') as handle:
  b = pickle.loads(handle.read())

print a == b # True

Notice that I never set b = a, but instead pickled a to a file and then unpickled it into b.

As for your error:

self.whip = open('deed.txt', 'r').read()

self.whip was a dictionary object. deed.txt contains text, so when you load the contents of deed.txt into self.whip, self.whip becomes the string representation of itself.

You'd probably want to evaluate the string back into a Python object:

self.whip = eval(open('deed.txt', 'r').read())

Notice how eval sounds like evil. That's intentional. Use the pickle module instead.

Getting text from td cells with jQuery

You can use .map: http://jsfiddle.net/9ndcL/1/.

// array of text of each td

var texts = $("td").map(function() {
    return $(this).text();
});

Why is document.body null in my javascript?

document.body is not yet available when your code runs.

What you can do instead:

var docBody=document.getElementsByTagName("body")[0];
docBody.appendChild(mySpan);

How can I get the current screen orientation?

getActivity().getResources().getConfiguration().orientation

this command returns int value 1 for Portrait and 2 for Landscape

Remove empty lines in a text file via grep

Simplest Answer -----------------------------------------

[root@node1 ~]# cat /etc/sudoers | grep -v -e ^# -e ^$
Defaults   !visiblepw
Defaults    always_set_home
Defaults    match_group_by_gid
Defaults    always_query_group_plugin
Defaults    env_reset
Defaults    env_keep =  "COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS_COLORS"
Defaults    env_keep += "MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE"
Defaults    env_keep += "LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES"
Defaults    env_keep += "LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE"
Defaults    env_keep += "LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY"
Defaults    secure_path = /sbin:/bin:/usr/sbin:/usr/bin
root    ALL=(ALL)       ALL
%wheel  ALL=(ALL)       ALL
[root@node1 ~]#

How to find if a given key exists in a C++ std::map

If you want to compare pair of map you can use this method:

typedef map<double, double> TestMap;
TestMap testMap;
pair<map<double,double>::iterator,bool> controlMapValues;

controlMapValues= testMap.insert(std::pair<double,double>(x,y));
if (controlMapValues.second == false )
{
    TestMap::iterator it;
    it = testMap.find(x);

    if (it->second == y)
    {
        cout<<"Given value is already exist in Map"<<endl;
    }
}

This is a useful technique.

Upload a file to Amazon S3 with NodeJS

var express = require('express')

app = module.exports = express();
var secureServer = require('http').createServer(app);
secureServer.listen(3001);

var aws = require('aws-sdk')
var multer = require('multer')
var multerS3 = require('multer-s3')

    aws.config.update({
    secretAccessKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    accessKeyId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    region: 'us-east-1'
    });
    s3 = new aws.S3();

   var upload = multer({
   storage: multerS3({
    s3: s3,
    dirname: "uploads",
    bucket: "Your bucket name",
    key: function (req, file, cb) {
        console.log(file);
        cb(null, "uploads/profile_images/u_" + Date.now() + ".jpg"); //use  
     Date.now() for unique file keys
    }
  })
   });

 app.post('/upload', upload.single('photos'), function(req, res, next) {

 console.log('Successfully uploaded ', req.file)

 res.send('Successfully uploaded ' + req.file.length + ' files!')

})

Limiting Powershell Get-ChildItem by File Creation Date Range

Fixed it...

Get-ChildItem C:\Windows\ -recurse -include @("*.txt*","*.pdf") |
Where-Object {$_.CreationTime -gt "01/01/2013" -and $_.CreationTime -lt "12/02/2014"} | 
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} | 
Export-Csv C:\search_TXT-and-PDF_files_01012013-to-12022014_sort.txt

How to check for file lock?

You can see if the file is locked by trying to read or lock it yourself first.

Please see my answer here for more information.

Query an object array using linq

Add:

using System.Linq;

to the top of your file.

And then:

Car[] carList = ...
var carMake = 
    from item in carList
    where item.Model == "bmw" 
    select item.Make;

or if you prefer the fluent syntax:

var carMake = carList
    .Where(item => item.Model == "bmw")
    .Select(item => item.Make);

Things to pay attention to:

  • The usage of item.Make in the select clause instead if s.Make as in your code.
  • You have a whitespace between item and .Model in your where clause

Setting onSubmit in React.js

In your doSomething() function, pass in the event e and use e.preventDefault().

doSomething = function (e) {
    alert('it works!');
    e.preventDefault();
}

HTML combo box with option to type an entry

Given that the HTML datalist tag is still not fully supported, an alternate approach that I used is the Dojo Toolkit ComboBox. It was easier to implement and better documented than other options I've explored. It also plays nicely with existing frameworks. In my case, I added this combobox to an existing website that's based on Codeigniter and Bootstrap with no problems You just need to be sure to apply the Dojo theme (e.g. class="claro") to the combo's parent element instead of the body tag to avoid styling conflicts.

First, include the CSS for one of the Dojo themes (such as 'Claro'). It's important that the CSS file is included prior to the JS files below.

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/dojo/1.9.6/dijit/themes/claro/claro.css" />

Next, include jQuery and Dojo Toolkit via CDN

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/dojo/1.10.3/dojo/dojo.js"></script>

Next, you can just follow Dojo's sample code or use the sample below to get a working combobox.

<body>
    <!-- Dojo Dijit ComboBox with 'Claro' theme -->
    <div class="claro"><input id="item_name_1" class=""/></div>

    <script type="text/javascript">
        $(document).ready(function () {
            //In this example, dataStore is simply an array of JSON-encoded id/name pairs
            dataStore = [{"id":"43","name":"Domain Name Renewal"},{"id":"42","name":"Hosting Renewal"}];

            require(
                [ "dojo/store/Memory", "dijit/form/ComboBox", "dojo/domReady!"], 
                function (Memory, ComboBox) {
                    var stateStore = new Memory({
                        data: dataStore
                    });

                    var combo = new ComboBox({
                        id: "item_name_1",
                        name: "desc_1",
                        store: stateStore,
                        searchAttr: "name"},                        
                        "item_name_1"
                        ).startup();

                });

        });

    </script>
</body>

Prevent BODY from scrolling when a modal is opened

You need to go beyond @charlietfl's answer and account for scrollbars, otherwise you may see a document reflow.

Opening the modal:

  1. Record the body width
  2. Set body overflow to hidden
  3. Explicitly set the body width to what it was in step 1.

    var $body = $(document.body);
    var oldWidth = $body.innerWidth();
    $body.css("overflow", "hidden");
    $body.width(oldWidth);
    

Closing the modal:

  1. Set body overflow to auto
  2. Set body width to auto

    var $body = $(document.body);
    $body.css("overflow", "auto");
    $body.width("auto");
    

Inspired by: http://jdsharp.us/jQuery/minute/calculate-scrollbar-width.php

sql - insert into multiple tables in one query

MySQL doesn't support multi-table insertion in a single INSERT statement. Oracle is the only one I'm aware of that does, oddly...

INSERT INTO NAMES VALUES(...)
INSERT INTO PHONES VALUES(...)

How to delete specific rows and columns from a matrix in a smarter way?

> S = matrix(c(1,2,3,4,5,2,1,2,3,4,3,2,1,2,3,4,3,2,1,2,5,4,3,2,1),ncol = 5,byrow = TRUE);S
[,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    2    1    2    3    4
[3,]    3    2    1    2    3
[4,]    4    3    2    1    2
[5,]    5    4    3    2    1
> S<-S[,-2]
> S
[,1] [,2] [,3] [,4]
[1,]    1    3    4    5
[2,]    2    2    3    4
[3,]    3    1    2    3
[4,]    4    2    1    2
[5,]    5    3    2    1

Just use the command S <- S[,-2] to remove the second column. Similarly to delete a row, for example, to delete the second row use S <- S[-2,].

How to convert a date to milliseconds

The SimpleDateFormat class allows you to parse a String into a java.util.Date object. Once you have the Date object, you can get the milliseconds since the epoch by calling Date.getTime().

The full example:

String myDate = "2014/10/29 18:10:45";
//creates a formatter that parses the date in the given format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long timeInMillis = date.getTime();

Note that this gives you a long and not a double, but I think that's probably what you intended. The documentation for the SimpleDateFormat class has tons on information on how to set it up to parse different formats.

How do I split a multi-line string into multiple lines?

inputString.splitlines()

Will give you a list with each item, the splitlines() method is designed to split each line into a list element.

Determine what user created objects in SQL Server

If you need a small and specific mechanism, you can search for DLL Triggers info.

MySQL show current connection info

If you want to know the port number of your local host on which Mysql is running you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'port';


mysql> SHOW VARIABLES WHERE Variable_name = 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  |
+---------------+-------+
1 row in set (0.00 sec)

It will give you the port number on which MySQL is running.


If you want to know the hostname of your Mysql you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'hostname';


mysql> SHOW VARIABLES WHERE Variable_name = 'hostname';
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| hostname          | Dell  |
+-------------------+-------+
1 row in set (0.00 sec)

It will give you the hostname for mysql.


If you want to know the username of your Mysql you can use this query on MySQL Command line client --

select user();   


mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)

It will give you the username for mysql.

Pyinstaller setting icons don't change

Here is how you can add an icon while creating an exe file from a Python file

  • open command prompt at the place where Python file exist

  • type:

    pyinstaller --onefile -i"path of icon"  path of python file
    

Example-

pyinstaller --onefile -i"C:\icon\Robot.ico" C:\Users\Jarvis.py

This is the easiest way to add an icon.

Install windows service without InstallUtil.exe

Not double click, you run it with the correct command line parameters, so type something like MyService -i and then MyService -u to uninstall it`.

You could otherwise use sc.exe to install and uninstall it (or copy along InstallUtil.exe).

How to find time complexity of an algorithm

Taken from here - Introduction to Time Complexity of an Algorithm

1. Introduction

In computer science, the time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a function of the length of the string representing the input.

2. Big O notation

The time complexity of an algorithm is commonly expressed using big O notation, which excludes coefficients and lower order terms. When expressed this way, the time complexity is said to be described asymptotically, i.e., as the input size goes to infinity.

For example, if the time required by an algorithm on all inputs of size n is at most 5n3 + 3n, the asymptotic time complexity is O(n3). More on that later.

Few more Examples:

  • 1 = O(n)
  • n = O(n2)
  • log(n) = O(n)
  • 2 n + 1 = O(n)

3. O(1) Constant Time:

An algorithm is said to run in constant time if it requires the same amount of time regardless of the input size.

Examples:

  • array: accessing any element
  • fixed-size stack: push and pop methods
  • fixed-size queue: enqueue and dequeue methods

4. O(n) Linear Time

An algorithm is said to run in linear time if its time execution is directly proportional to the input size, i.e. time grows linearly as input size increases.

Consider the following examples, below I am linearly searching for an element, this has a time complexity of O(n).

int find = 66;
var numbers = new int[] { 33, 435, 36, 37, 43, 45, 66, 656, 2232 };
for (int i = 0; i < numbers.Length - 1; i++)
{
    if(find == numbers[i])
    {
        return;
    }
}

More Examples:

  • Array: Linear Search, Traversing, Find minimum etc
  • ArrayList: contains method
  • Queue: contains method

5. O(log n) Logarithmic Time:

An algorithm is said to run in logarithmic time if its time execution is proportional to the logarithm of the input size.

Example: Binary Search

Recall the "twenty questions" game - the task is to guess the value of a hidden number in an interval. Each time you make a guess, you are told whether your guess is too high or too low. Twenty questions game implies a strategy that uses your guess number to halve the interval size. This is an example of the general problem-solving method known as binary search

6. O(n2) Quadratic Time

An algorithm is said to run in quadratic time if its time execution is proportional to the square of the input size.

Examples:

7. Some Useful links

Parsing jQuery AJAX response

calling

var parsed_data = JSON.parse(data);

should result in the ability to access the data like you want.

console.log(parsed_data.success);

should now show '1'

How to change lowercase chars to uppercase using the 'keyup' event?

Let say your html code is :

<input type="text" id="txtMyText" />

then the jquery should be :

$('#txtMyText').keyup(function() {
  this.value = this.value.toUpperCase();
});

How to create an ArrayList from an Array in PowerShell?

Probably the shortest version:

[System.Collections.ArrayList]$someArray

It is also faster because it does not call relatively expensive New-Object.

What does the "static" modifier after "import" mean?

The basic idea of static import is that whenever you are using a static class,a static variable or an enum,you can import them and save yourself from some typing.

I will elaborate my point with example.

import java.lang.Math;

class WithoutStaticImports {

 public static void main(String [] args) {
  System.out.println("round " + Math.round(1032.897));
  System.out.println("min " + Math.min(60,102));
 }
}

Same code, with static imports:

import static java.lang.System.out;
import static java.lang.Math.*;

class WithStaticImports {
  public static void main(String [] args) {
    out.println("round " + round(1032.897));
    out.println("min " + min(60,102));
  }
}

Note: static import can make your code confusing to read.

Cannot ignore .idea/workspace.xml - keeps popping up

I had this problem just now, I had to do git rm -f .idea/workspace.xml now it seems to be gone (I also had to put it into .gitignore)

SQL Case Sensitive String Compare

Select * from a_table where attribute = 'k' COLLATE Latin1_General_CS_AS 

Did the trick.

Set disable attribute based on a condition for Html.TextBoxFor

Actually, the internal behavior is translating the anonymous object to a dictionary. So what I do in these scenarios is go for a dictionary:

@{
  var htmlAttributes = new Dictionary<string, object>
  {
    { "class" , "form-control"},
    { "placeholder", "Why?" }        
  };
  if (Model.IsDisabled)
  {
    htmlAttributes.Add("disabled", "disabled");
  }
}
@Html.EditorFor(m => m.Description, new { htmlAttributes = htmlAttributes })

Or, as Stephen commented here:

@Html.EditorFor(m => m.Description,
    Model.IsDisabled ? (object)new { disabled = "disabled" } : (object)new { })

Importing data from a JSON file into R

packages:

  • library(httr)
  • library(jsonlite)

I have had issues converting json to dataframe/csv. For my case I did:

Token <- "245432532532"
source <- "http://......."
header_type <- "applcation/json"
full_token <- paste0("Bearer ", Token)
response <- GET(n_source, add_headers(Authorization = full_token, Accept = h_type), timeout(120), verbose())
text_json <- content(response, type = 'text', encoding = "UTF-8")
jfile <- fromJSON(text_json)
df <- as.data.frame(jfile)

then from df to csv.

In this format it should be easy to convert it to multiple .csvs if needed.

The important part is content function should have type = 'text'.

Trying to read cell 1,1 in spreadsheet using Google Script API

You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of

function email() {

// Opens SS by its ID

var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");

// Get the name of this SS

var name = ss.getName();  // Not necessary 

// Read cell 1,1 * Line below does't work *

// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet 
var range = sheet.getRange(1,1); 
var data = range.getValue();

}

The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.

Java String to SHA1

Base 64 Representation of SHA1 Hash:

String hashedVal = Base64.getEncoder().encodeToString(DigestUtils.sha1(stringValue.getBytes(Charset.forName("UTF-8"))));

How to set delay in android?

Handler answer in Kotlin :

1 - Create a top-level function inside a file (for example a file that contains all your top-level functions) :

fun delayFunction(function: ()-> Unit, delay: Long) {
    Handler().postDelayed(function, delay)
}

2 - Then call it anywhere you needed it :

delayFunction({ myDelayedFunction() }, 300)

How to get the children of the $(this) selector?

The jQuery constructor accepts a 2nd parameter called context which can be used to override the context of the selection.

jQuery("img", this);

Which is the same as using .find() like this:

jQuery(this).find("img");

If the imgs you desire are only direct descendants of the clicked element, you can also use .children():

jQuery(this).children("img");

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

The following works for me. Add the following method to the entity that is not the owner of the relationship (Group)

@PreRemove
private void removeGroupsFromUsers() {
    for (User u : users) {
        u.getGroups().remove(this);
    }
}

Keep in mind that for this to work, the Group must have an updated list of Users (which is not done automatically). so everytime you add a Group to the group list in User entity, you should also add a User to the user list in the Group entity.

Styling Password Fields in CSS

The best I can find is to set input[type="password"] {font:small-caption;font-size:16px}

Demo:

_x000D_
_x000D_
input {_x000D_
  font: small-caption;_x000D_
  font-size: 16px;_x000D_
}
_x000D_
<input type="password">
_x000D_
_x000D_
_x000D_

How to embed a PDF viewer in a page?

PDF.js is an HTML5 technology experiment that explores building a faithful and efficient Portable Document Format (PDF) renderer without native code assistance. It is community-driven and supported by Mozilla Labs.

You can see the demo here.

Gson: How to exclude specific fields from Serialization without annotations

After reading all available answers I found out, that most flexible, in my case, was to use custom @Exclude annotation. So, I implemented simple strategy for this (I didn't want to mark all fields using @Expose nor I wanted to use transient which conflicted with in app Serializable serialization) :

Annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Exclude {
}

Strategy:

public class AnnotationExclusionStrategy implements ExclusionStrategy {

    @Override
    public boolean shouldSkipField(FieldAttributes f) {
        return f.getAnnotation(Exclude.class) != null;
    }

    @Override
    public boolean shouldSkipClass(Class<?> clazz) {
        return false;
    }
}

Usage:

new GsonBuilder().setExclusionStrategies(new AnnotationExclusionStrategy()).create();

Add new field to every document in a MongoDB collection

Since MongoDB version 3.2 you can use updateMany():

> db.yourCollection.updateMany({}, {$set:{"someField": "someValue"}})

Oracle copy data to another table

insert into EXCEPTION_CODES (CODE, MESSAGE)
select CODE, MESSAGE from Exception_code_tmp

Tesseract running error

You can call tesseract API function from C code:

#include <tesseract/baseapi.h>
#include <tesseract/ocrclass.h>; // ETEXT_DESC

using namespace tesseract;

class TessAPI : public TessBaseAPI {
    public:
    void PrintRects(int len);
};

...
TessAPI *api = new TessAPI();
int res = api->Init(NULL, "rus");
api->SetAccuracyVSpeed(AVS_MOST_ACCURATE);
api->SetImage(data, w0, h0, bpp, stride);
api->SetRectangle(x0,y0,w0,h0);

char *text;
ETEXT_DESC monitor;
api->RecognizeForChopTest(&monitor);
text = api->GetUTF8Text();
printf("text: %s\n", text);
printf("m.count: %s\n", monitor.count);
printf("m.progress: %s\n", monitor.progress);

api->RecognizeForChopTest(&monitor);
text = api->GetUTF8Text();
printf("text: %s\n", text);
...
api->End();

And build this code:

g++ -g -I. -I/usr/local/include -o _test test.cpp -ltesseract_api -lfreeimageplus

(i need FreeImage for picture loading)

.NET - How do I retrieve specific items out of a Dataset?

I prefer to use something like this:

int? var1 = ds.Tables[0].Rows[0].Field<int?>("ColumnName");

or

int? var1 = ds.Tables[0].Rows[0].Field<int?>(3);   //column index