Programs & Examples On #Ugc

User-generated content

Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }

Here is the function example trim generic type of array object

const trimArrayObject = <T>(items: T[]) => {

  items.forEach(function (o) {

    for (let [key, value] of Object.entries(o)) {

      const keyName = <keyof typeof o>key;

      if (Array.isArray(value)) {

        trimArrayObject(value);

      } else if (typeof o[keyName] === "string") {

        o[keyName] = value.trim();

      }

    }

  });

};

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.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

Below is a workaround demo image of ; Uncheck Offline work option by going to:

File -> Settings -> Build, Execution, Deployment -> Gradle

enter image description here

If above workaround not works then try this:

  1. Open the build.gradle file for your application.

  2. Make sure that the repositories section includes a maven section with the "https://maven.google.com" endpoint. For example:

    allprojects {
         repositories {
             jcenter()
             maven {
                 url "https://maven.google.com"
             }
         }
    }
    
  3. Add the support library to the dependencies section. For example, to add the v4 core-utils library, add the following lines:

    dependencies {
        ...
        compile "com.android.support:support-core-utils:27.1.0"
    }
    

Caution: Using dynamic dependencies (for example, palette-v7:23.0.+) can cause unexpected version updates and regression incompatibilities. We recommend that you explicitly specify a library version (for example, palette-v7:27.1.0).

Manifest Declaration Changes

Specifically, you should update the android:minSdkVersion element of the <uses-sdk> tag in the manifest to the new, lower version number, as shown below:

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

If you are using Gradle build files, the minSdkVersion setting in the build file overrides the manifest settings.

apply plugin: 'com.android.application'

android {
   ...
      defaultConfig {
            minSdkVersion 16
            ...
        }
        ...
    }

Following Android Developer Library Support.

Cannot find control with name: formControlName in angular reactive form

You should specify formGroupName for nested controls

<div class="panel panel-default" formGroupName="address"> <== add this
    <div class="panel-heading">Contact Info</div>

Plunker Example

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

I have faced a similar issue working in a multiple modules app environment:

Error: Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'. More than one file was found with OS independent path 'META-INF/AL2.0'

This issue was being reported by several of these modules of mine and none of the above solutions were fixing it. Turns out, I was using version Coroutines 1.3.6 which seemed to be embedding META-INF/AL2.0 which was already embedded by another of the libraries I was using. To fix it, I have added the following code snippet to the build.gradle of the module that was failing:

configurations.all {
    resolutionStrategy {
        exclude group: "org.jetbrains.kotlinx", module: "kotlinx-coroutines-debug"

    }
}

Given that it was happening on multiple modules, I have moved that resolutionStrategy code to my project level build.gradle. Everything worked after that.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

You did not post the code generated by the compiler, so there' some guesswork here, but even without having seen it, one can say that this:

test rax, 1
jpe even

... has a 50% chance of mispredicting the branch, and that will come expensive.

The compiler almost certainly does both computations (which costs neglegibly more since the div/mod is quite long latency, so the multiply-add is "free") and follows up with a CMOV. Which, of course, has a zero percent chance of being mispredicted.

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

you can try to use

  androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})

instead of

androidTestCompile 'com.android.support.test:runner:0.4.1'

androidTestCompile 'com.android.support.test:rules:0.4.1'

androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
androidTestCompile 'com.android.support.test.espresso:espresso-contrib:2.2.1'

Play multiple CSS animations at the same time

You cannot play two animations since the attribute can be defined only once. Rather why don't you include the second animation in the first and adjust the keyframes to get the timing right?

_x000D_
_x000D_
.image {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    width: 120px;_x000D_
    height: 120px;_x000D_
    margin:-60px 0 0 -60px;_x000D_
    -webkit-animation:spin-scale 4s linear infinite;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes spin-scale { _x000D_
    50%{_x000D_
        transform: rotate(360deg) scale(2);_x000D_
    }_x000D_
    100% { _x000D_
        transform: rotate(720deg) scale(1);_x000D_
    } _x000D_
}
_x000D_
<img class="image" src="http://makeameme.org/media/templates/120/grumpy_cat.jpg" alt="" width="120" height="120">
_x000D_
_x000D_
_x000D_

java.util.zip.ZipException: duplicate entry during packageAllDebugClassesForMultiDex

You need to check that you have inserted v4 library and compile library? You must not repeat library in your app or your dependence program.

delete the repeat library so that just one V4 remains.

in your app dir build.gradle file add this command:

android{


    configurations {
        all*.exclude group: 'com.android.support', module: 'support-v4'
        all*.exclude group: 'com.android.support', module: 'support-annotations'
    }

}

it works for me! You can try it!

resize2fs: Bad magic number in super-block while trying to open

After reading about LVM and being familiar with PV -> VG -> LV, this works for me :

0) #df -h

Filesystem               Size  Used Avail Use% Mounted on
devtmpfs                 1.9G     0  1.9G   0% /dev
tmpfs                    1.9G     0  1.9G   0% /dev/shm
tmpfs                    1.9G  824K  1.9G   1% /run
tmpfs                    1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/mapper/fedora-root   15G  2.1G   13G  14% /
tmpfs                    1.9G     0  1.9G   0% /tmp
/dev/md126p1             976M  119M  790M  14% /boot
tmpfs                    388M     0  388M   0% /run/user/0

1) # vgs

  VG     #PV #LV #SN Attr   VSize   VFree   
  fedora   1   2   0 wz--n- 231.88g 212.96g

2) # vgdisplay

  --- Volume group ---
  VG Name               fedora
  System ID
  Format                lvm2
  Metadata Areas        1
  Metadata Sequence No  3
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                2
  Open LV               2
  Max PV                0
  Cur PV                1
  Act PV                1
  VG Size               231.88 GiB
  PE Size               4.00 MiB
  Total PE              59361
  Alloc PE / Size       4844 / 18.92 GiB
  Free  PE / Size       54517 / 212.96 GiB
  VG UUID               9htamV-DveQ-Jiht-Yfth-OZp7-XUDC-tWh5Lv

3) # lvextend -l +100%FREE /dev/mapper/fedora-root

  Size of logical volume fedora/root changed from 15.00 GiB (3840 extents) to 227.96 GiB (58357 extents).
  Logical volume fedora/root successfully resized.

4) #lvdisplay

5) #fd -h

6) # xfs_growfs /dev/mapper/fedora-root

meta-data=/dev/mapper/fedora-root isize=512    agcount=4, agsize=983040 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=1        finobt=1 spinodes=0 rmapbt=0
         =                       reflink=0
data     =                       bsize=4096   blocks=3932160, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0 ftype=1
log      =internal               bsize=4096   blocks=2560, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
data blocks changed from 3932160 to 59757568

7) #df -h

Filesystem               Size  Used Avail Use% Mounted on
devtmpfs                 1.9G     0  1.9G   0% /dev
tmpfs                    1.9G     0  1.9G   0% /dev/shm
tmpfs                    1.9G  828K  1.9G   1% /run
tmpfs                    1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/mapper/fedora-root  228G  2.3G  226G   2% /
tmpfs                    1.9G     0  1.9G   0% /tmp
/dev/md126p1             976M  119M  790M  14% /boot
tmpfs                    388M     0  388M   0% /run/user/0

Best Regards,

Adding external library in Android studio

1)just get your lib from here http://search.maven.org/

2)create a libs folder in app directory

3)paste ur library there

4)right click on ur library and click "Add as Library"

5)thats all u need to do!

I hope this will definitely gonna help you!!!!

add maven repository to build.gradle

You will need to define the repository outside of buildscript. The buildscript configuration block only sets up the repositories and dependencies for the classpath of your build script but not your application.

using facebook sdk in Android studio

*Gradle Repository for the Facebook SDK.

dependencies {
    compile 'com.facebook.android:facebook-android-sdk:4.4.0'
}

Search for the latest version facebook sdk

How to add Android Support Repository to Android Studio?

You are probably hit by this bug which prevents the Android Gradle Plugin from automatically adding the "Android Support Repository" to the list of Gradle repositories. The work-around, as mentioned in the bug report, is to explicitly add the m2repository directory as a local Maven directory in the top-level build.gradle file as follows:

allprojects {
    repositories {
        // Work around https://code.google.com/p/android/issues/detail?id=69270.
        def androidHome = System.getenv("ANDROID_HOME")
        maven {
            url "$androidHome/extras/android/m2repository/"
        }
    }
}

Gradle Build Android Project "Could not resolve all dependencies" error

Add this to your gradle:

allprojects {
    buildscript {
        repositories {
            maven {
                url "https://dl.bintray.com/android/android-tools"
            }
        }
    }
...
}

server error:405 - HTTP verb used to access this page is not allowed

I've been pulling my hair out over this one for a couple of hours also. fakeartist appears correct though - I changed the file extension from .htm to .php and I can now see my page in Facebook! It also works if you change the extension to .aspx - perhaps it just needs to be a server side extension (I've not tried with .jsp).

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

Use BigDecimal.valueOf(double d) instead of new BigDecimal(double d). The last one has precision errors by float and double.

Eliminating duplicate values based on only one column of the table

From your example it seems reasonable to assume that the siteIP column is determined by the siteName column (that is, each site has only one siteIP). If this is indeed the case, then there is a simple solution using group by:

select
  sites.siteName,
  sites.siteIP,
  max(history.date)
from sites
inner join history on
  sites.siteName=history.siteName
group by
  sites.siteName,
  sites.siteIP
order by
  sites.siteName;

However, if my assumption is not correct (that is, it is possible for a site to have multiple siteIP), then it is not clear from you question which siteIP you want the query to return in the second column. If just any siteIP, then the following query will do:

select
  sites.siteName,
  min(sites.siteIP),
  max(history.date)
from sites
inner join history on
  sites.siteName=history.siteName
group by
  sites.siteName
order by
  sites.siteName;

Using C# regular expressions to remove HTML tags

Use this method to remove tags:

public string From_To(string text, string from, string to)
{
    if (text == null)
        return null;
    string pattern = @"" + from + ".*?" + to;
    Regex rx = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
    MatchCollection matches = rx.Matches(text);
    return matches.Count <= 0 ? text : matches.Cast<Match>().Where(match => !string.IsNullOrEmpty(match.Value)).Aggregate(text, (current, match) => current.Replace(match.Value, ""));
}

Python 3.6 install win32api?

Information provided by @Gord

As of September 2019 pywin32 is now available from PyPI and installs the latest version (currently version 224). This is done via the pip command

pip install pywin32

If you wish to get an older version the sourceforge link below would probably have the desired version, if not you can use the command, where xxx is the version you require, e.g. 224

pip install pywin32==xxx

This differs to the pip command below as that one uses pypiwin32 which currently installs an older (namely 223)

Browsing the docs I see no reason for these commands to work for all python3.x versions, I am unsure on python2.7 and below so you would have to try them and if they do not work then the solutions below will work.


Probably now undesirable solutions but certainly still valid as of September 2019

There is no version of specific version ofwin32api. You have to get the pywin32module which currently cannot be installed via pip. It is only available from this link at the moment.

https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/

The install does not take long and it pretty much all done for you. Just make sure to get the right version of it depending on your python version :)


EDIT

Since I posted my answer there are other alternatives to downloading the win32api module.

It is now available to download through pip using this command;

pip install pypiwin32

Also it can be installed from this GitHub repository as provided in comments by @Heath

Is there a program to decompile Delphi?

You can use IDR it is a great program to decompile Delphi, it is updated to the current Delphi versions and it has a lot of features.

What is the connection string for localdb for version 11

This is a fairly old thread, but since I was reinstalling my Visual Studio 2015 Community today, I thought I might add some info on what to use on VS2015, or what might work in general.

To see which instances were installed by default, type sqllocaldb info inside a command prompt. On my machine, I get two instances, the first one named MSSQLLocalDB.

C:\>sqllocaldb info
MSSQLLocalDB
ProjectsV13

You can also create a new instance if you wish, using sqllocaldb create "some_instance_name", but the default one will work just fine:

// if not using a verbatim string literal, don't forget to escape backslashes
@"Server=(localdb)\MSSQLLocalDB;Integrated Security=true;"

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

Why do I get permission denied when I try use "make" to install something?

Giving us the whole error message would be much more useful. If it's for make install then you're probably trying to install something to a system directory and you're not root. If you have root access then you can run

sudo make install

or log in as root and do the whole process as root.

how to pass variable from shell script to sqlplus

You appear to have a heredoc containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF

or if BUILDING is $2 in your script:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF

If your file.sql had an exit at the end then it would be even simpler as you wouldn't need the heredoc:

sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2

In your SQL you can then refer to the position parameters using substitution variables:

...
}',SEM_Models('&1'),NULL,
...

The &1 will be replaced with the first value passed to the SQL script, BUILDING; because that is a string it still needs to be enclosed in quotes. You might want to set verify off to stop if showing you the substitutions in the output.


You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1, the second is &2, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF

or:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF

If total_count is being passed to your shell script then just use its positional parameter, $4 or whatever. And your SQL would then be:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:

define MY_ALIAS = &1
define MY_MODEL = &2

SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

From your separate question, maybe you just wanted:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

... so the alias will be the same value you're querying on (the value in $2, or BUILDING in the original part of the answer). You can refer to a substitution variable as many times as you want.

That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:

select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT

If you set pages 0 and set heading off, your repeated calls might appear in a neat list. You might also need to set tab off and possibly use rpad('&1', 20) or similar to make that column always the same width. Or get the results as CSV with:

select '&1' ||','|| COUNT(*)

Depends what you're using the results for...

How do you save/store objects in SharedPreferences on Android?

there are two file solved your all problem about sharedpreferences

1)AppPersistence.java

    public class AppPersistence {
    public enum keys {
        USER_NAME, USER_ID, USER_NUMBER, USER_EMAIL, USER_ADDRESS, CITY, USER_IMAGE,
        DOB, MRG_Anniversary, COMPANY, USER_TYPE, support_phone
    }

    private static AppPersistence mAppPersistance;
    private SharedPreferences sharedPreferences;

    public static AppPersistence start(Context context) {
        if (mAppPersistance == null) {
            mAppPersistance = new AppPersistence(context);
        }
        return mAppPersistance;
    }

    private AppPersistence(Context context) {
        sharedPreferences = context.getSharedPreferences(context.getString(R.string.prefrence_file_name),
                Context.MODE_PRIVATE);
    }

    public Object get(Enum key) {
        Map<String, ?> all = sharedPreferences.getAll();
        return all.get(key.toString());
    }

    void save(Enum key, Object val) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        if (val instanceof Integer) {
            editor.putInt(key.toString(), (Integer) val);
        } else if (val instanceof String) {
            editor.putString(key.toString(), String.valueOf(val));
        } else if (val instanceof Float) {
            editor.putFloat(key.toString(), (Float) val);
        } else if (val instanceof Long) {
            editor.putLong(key.toString(), (Long) val);
        } else if (val instanceof Boolean) {
            editor.putBoolean(key.toString(), (Boolean) val);
        }
        editor.apply();
    }

    void remove(Enum key) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove(key.toString());
        editor.apply();
    }

    public void removeAll() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();
    }
}

2)AppPreference.java

public static void setPreference(Context context, Enum Name, String Value) {
        AppPersistence.start(context).save(Name, Value);
    }

    public static String getPreference(Context context, Enum Name) {
        return (String) AppPersistence.start(context).get(Name);
    }

    public static void removePreference(Context context, Enum Name) {
        AppPersistence.start(context).remove(Name);
    }
}

now you can save,remove or get like,

-save

AppPreference.setPreference(context, AppPersistence.keys.USER_ID, userID);

-remove

AppPreference.removePreference(context, AppPersistence.keys.USER_ID);

-get

 AppPreference.getPreference(context, AppPersistence.keys.USER_ID);

Seeing the console's output in Visual Studio 2010?

System.Diagnostics.Debug.WriteLine() will work, but you have to be looking in the right place for the output. In Visual Studio 2010, on the menu bar, click Debug -> Windows -> Output. Now, at the bottom of the screen docked next to your error list, there should be an output tab. Click it and double check it's showing output from the debug stream on the dropdown list.

P.S.: I think the output window shows on a fresh install, but I can't remember. If it doesn't, or if you closed it by accident, follow these instructions.

Console logging for react?

Here are some more console logging "pro tips":

console.table

var animals = [
    { animal: 'Horse', name: 'Henry', age: 43 },
    { animal: 'Dog', name: 'Fred', age: 13 },
    { animal: 'Cat', name: 'Frodo', age: 18 }
];

console.table(animals);

console.table

console.trace

Shows you the call stack for leading up to the console.

console.trace

You can even customise your consoles to make them stand out

console.todo = function(msg) {
    console.log(‘ % c % s % s % s‘, ‘color: yellow; background - color: black;’, ‘–‘, msg, ‘–‘);
}

console.important = function(msg) {
    console.log(‘ % c % s % s % s’, ‘color: brown; font - weight: bold; text - decoration: underline;’, ‘–‘, msg, ‘–‘);
}

console.todo(“This is something that’ s need to be fixed”);
console.important(‘This is an important message’);

console.todo

If you really want to level up don't limit your self to the console statement.

Here is a great post on how you can integrate a chrome debugger right into your code editor!

https://hackernoon.com/debugging-react-like-a-champ-with-vscode-66281760037

How to get difference between two dates in Year/Month/Week/Day?

I came across this post while looking to solve a similar problem. I was trying to find the age of an animal in units of Years, Months, Weeks, and Days. Those values are then displayed in SpinEdits where the user can manually change the values to find/estimate a birth date. When my form was passed a birth date from a month with less than 31 days, the value calculated was 1 day off. I based my solution off of Ic's answer above.

Main calculation method that is called after my form loads.

        birthDateDisplay.Text = birthDate.ToString("MM/dd/yyyy");

        DateTime currentDate = DateTime.Now;

        Int32 numOfDays = 0; 
        Int32 numOfWeeks = 0;
        Int32 numOfMonths = 0; 
        Int32 numOfYears = 0; 

        // changed code to follow this model http://stackoverflow.com/posts/1083990/revisions
        //years 
        TimeSpan diff = currentDate - birthDate;
        numOfYears = diff.Days / 366;
        DateTime workingDate = birthDate.AddYears(numOfYears);

        while (workingDate.AddYears(1) <= currentDate)
        {
            workingDate = workingDate.AddYears(1);
            numOfYears++;
        }

        //months
        diff = currentDate - workingDate;
        numOfMonths = diff.Days / 31;
        workingDate = workingDate.AddMonths(numOfMonths);

        while (workingDate.AddMonths(1) <= currentDate)
        {
            workingDate = workingDate.AddMonths(1);
            numOfMonths++;
        }

        //weeks and days
        diff = currentDate - workingDate;
        numOfWeeks = diff.Days / 7; //weeks always have 7 days

        // if bday month is same as current month and bday day is after current day, the date is off by 1 day
        if(DateTime.Now.Month == birthDate.Month && DateTime.Now.Day < birthDate.Day)
            numOfDays = diff.Days % 7 + 1;
        else
            numOfDays = diff.Days % 7;

        // If the there are fewer than 31 days in the birth month, the date calculated is 1 off
        // Dont need to add a day for the first day of the month
        int daysInMonth = 0;
        if ((daysInMonth = DateTime.DaysInMonth(birthDate.Year, birthDate.Month)) != 31 && birthDate.Day != 1)
        {
            startDateforCalc = DateTime.Now.Date.AddDays(31 - daysInMonth);
            // Need to add 1 more day if it is a leap year and Feb 29th is the date
            if (DateTime.IsLeapYear(birthDate.Year) && birthDate.Day == 29)
                startDateforCalc = startDateforCalc.AddDays(1);
        }

        yearsSpinEdit.Value = numOfYears;
        monthsSpinEdit.Value = numOfMonths;
        weeksSpinEdit.Value = numOfWeeks;
        daysSpinEdit.Value = numOfDays;

And then, in my spinEdit_EditValueChanged event handler, I calculate the new birth date starting from my startDateforCalc based on the values in the spin edits. (SpinEdits are constrained to only allow >=0)

birthDate = startDateforCalc.Date.AddYears(-((Int32)yearsSpinEdit.Value)).AddMonths(-((Int32)monthsSpinEdit.Value)).AddDays(-(7 * ((Int32)weeksSpinEdit.Value) + ((Int32)daysSpinEdit.Value)));
birthDateDisplay.Text = birthDate.ToString("MM/dd/yyyy");

I know its not the prettiest solution, but it seems to be working for me for all month lengths and years.

Best way to list files in Java, sorted by Date Modified?

Elegant solution since Java 8:

File[] files = directory.listFiles();
Arrays.sort(files, Comparator.comparingLong(File::lastModified));

Or, if you want it in descending order, just reverse it:

File[] files = directory.listFiles();
Arrays.sort(files, Comparator.comparingLong(File::lastModified).reversed());

Best tool for inspecting PDF files?

PDFXplorer from O2 Solutions does an outstanding job of displaying the internals.

http://www.o2sol.com/pdfxplorer/overview.htm

(Free, distracting banner at the bottom).

How do I link to a library with Code::Blocks?

The gdi32 library is already installed on your computer, few programs will run without it. Your compiler will (if installed properly) normally come with an import library, which is what the linker uses to make a binding between your program and the file in the system. (In the unlikely case that your compiler does not come with import libraries for the system libs, you will need to download the Microsoft Windows Platform SDK.)

To link with gdi32:

enter image description here

This will reliably work with MinGW-gcc for all system libraries (it should work if you use any other compiler too, but I can't talk about things I've not tried). You can also write the library's full name, but writing libgdi32.a has no advantage over gdi32 other than being more type work.
If it does not work for some reason, you may have to provide a different name (for example the library is named gdi32.lib for MSVC).

For libraries in some odd locations or project subfolders, you will need to provide a proper pathname (click on the "..." button for a file select dialog).

How to set connection timeout with OkHttp

Adding in gradle file and sync project:

compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.google.code.gson:gson:2.6.2'

Adding in Java class:

import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;


Builder b = new Builder();
b.readTimeout(200, TimeUnit.MILLISECONDS);
b.writeTimeout(600, TimeUnit.MILLISECONDS);
// set other properties

OkHttpClient client = b.build();

Use grep to report back only line numbers

To count the number of lines matched the pattern:

grep -n "Pattern" in_file.ext | wc -l 

To extract matched pattern

sed -n '/pattern/p' file.est

To display line numbers on which pattern was matched

grep -n "pattern" file.ext | cut -f1 -d:

Combine multiple JavaScript files into one JS file

This may be a bit of effort but you could download my open-source wiki project from codeplex:

http://shuttlewiki.codeplex.com

It contains a CompressJavascript project (and CompressCSS) that uses the http://yuicompressor.codeplex.com/ project.

The code should be self-explanatory but it makes combining and compressing the files a bit simnpler --- for me anyway :)

The ShuttleWiki project shows how to use it in the post-build event.

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

An other cause of this problem is corruption of maven repository jars so you can use the following command to solve the problem :

mvn dependency:purge-local-repository

.htaccess or .htpasswd equivalent on IIS?

There isn't a direct 1:1 equivalent.

You can password protect a folder or file using file system permissions. If you are using ASP.Net you can also use some of its built in functions to protect various urls.

If you are trying to port .htaccess files used for url rewriting, check out ISAPI Rewrite: http://www.isapirewrite.com/

Convert String to Uri

If you are using Kotlin and Kotlin android extensions, then there is a beautiful way of doing this.

val uri = myUriString.toUri()

To add Kotlin extensions (KTX) to your project add the following to your app module's build.gradle

  repositories {
    google()
}

dependencies {
    implementation 'androidx.core:core-ktx:1.0.0-rc01'
}

What does `m_` variable prefix mean?

One argument that I haven't seen yet is that a prefix such as m_ can be used to prevent name clashing with #define'd macro's.

Regex search for #define [a-z][A-Za-z0-9_]*[^(] in /usr/include/term.h from curses/ncurses.

no overload for matches delegate 'system.eventhandler'

You need to change public void klik(PaintEventArgs pea, EventArgs e) to public void klik(object sender, System.EventArgs e) because there is no Click event handler with parameters PaintEventArgs pea, EventArgs e.

How to add header to a dataset in R?

this should work out,

      kable(dt) %>%
      kable_styling("striped") %>%
      add_header_above(c(" " = 1, "Group 1" = 2, "Group 2" = 2, "Group 3" = 2))
#OR
kable(dt) %>%
  kable_styling(c("striped", "bordered")) %>%
  add_header_above(c(" ", "Group 1" = 2, "Group 2" = 2, "Group 3" = 2)) %>%
  add_header_above(c(" ", "Group 4" = 4, "Group 5" = 2)) %>%
  add_header_above(c(" ", "Group 6" = 6))

for more you can check the link

Difference between .dll and .exe?

The major exact difference between DLL and EXE that DLL hasn't got an entry point and EXE does. If you are familiar with c++ you can see that build EXE has main() entry function and DLL doesn't :)

Java Spring Boot: How to map my app root (“/”) to index.html?

I had the same problem. Spring boot knows where static html files are located.

  1. Add index.html into resources/static folder
  2. Then delete full controller method for root path like @RequestMapping("/") etc
  3. Run app and check http://localhost:8080 (Should work)

Java: Best way to iterate through a Collection (here ArrayList)

Here is an example

Query query = em.createQuery("from Student");
             java.util.List list = query.getResultList();
             for (int i = 0; i < list.size(); i++) 
             {

                 student = (Student) list.get(i);
                 System.out.println(student.id  + "  " + student.age + " " + student.name + " " + student.prenom);

             }

CSS: how do I create a gap between rows in a table?

You could also just modify the height for each row using CSS.

<head>
 <style>
 tr {
   height:40px;
 }
</style>
</head>

<body>
<table>

<tr> <td>One</td> <td>Two</td> </tr>
<tr> <td>Three</td> <td>Four</td> </tr>
<tr> <td>Five</td> <td>Six</td> </tr>

</table>
</body>

You could also modify the height of the <td> element, it should give you the same result.

Remove border from IFrame

In addition to adding the frameBorder attribute you might want to consider setting the scrolling attribute to "no" to prevent scrollbars from appearing.

<iframe src="myURL" width="300" height="300" frameBorder="0" scrolling="no">Browser not compatible. </iframe > 

Extract a part of the filepath (a directory) in Python

In Python 3.4 you can use the pathlib module:

>>> from pathlib import Path
>>> p = Path('C:\Program Files\Internet Explorer\iexplore.exe')
>>> p.name
'iexplore.exe'
>>> p.suffix
'.exe'
>>> p.root
'\\'
>>> p.parts
('C:\\', 'Program Files', 'Internet Explorer', 'iexplore.exe')
>>> p.relative_to('C:\Program Files')
WindowsPath('Internet Explorer/iexplore.exe')
>>> p.exists()
True

Difference between parameter and argument

Generally, the parameters are what are used inside the function and the arguments are the values passed when the function is called. (Unless you take the opposite view — Wikipedia mentions alternative conventions when discussing parameters and arguments).

double sqrt(double x)
{
    ...
    return x;
}

void other(void)
{
     double two = sqrt(2.0);
}

Under my thesis, x is the parameter to sqrt() and 2.0 is the argument.

The terms are often used at least somewhat interchangeably.

How can I call a shell command in my Perl script?

There are a lot of ways you can call a shell command from a Perl script, such as:

  1. back tick ls which captures the output and gives back to you.
  2. system system('ls');
  3. open

Refer #17 here: Perl programming tips

Printing long int value in C

Use printf("%ld",a);

Have a look at format specifiers for printf

How to rename a file using Python

import os
import re
from pathlib import Path

for f in os.listdir(training_data_dir2):
  for file in os.listdir( training_data_dir2 + '/' + f):
    oldfile= Path(training_data_dir2 + '/' + f + '/' + file)
    newfile = Path(training_data_dir2 + '/' + f + '/' + file[49:])
    p=oldfile
    p.rename(newfile)

Batch File: ( was unexpected at this time

You are getting that error because when the param1 if statements are evaluated, param is always null due to being scoped variables without delayed expansion.

When parentheses are used, all the commands and variables within those parentheses are expanded. And at that time, param1 has no value making the if statements invalid. When using delayed expansion, the variables are only expanded when the command is actually called.

Also I recommend using if not defined command to determine if a variable is set.

@echo off
setlocal EnableExtensions EnableDelayedExpansion
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.

set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if not defined a goto :aPrompt
echo %a%

IF "%a%"=="2" (
    title USB WRITE LOCK
    echo What do you want to do?
    echo 1.Apply USB Write Protection
    echo 2.Remove USB Write Protection

    ::param1
    set "param1=%globalparam2%"
    goto :param1Check
    :param1Prompt
    set /p "param1=Enter Choice: "
    :param1Check
    if not defined param1 goto :param1Prompt
    echo !param1!

    if "!param1!"=="1" (
        REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001 
        echo USB Write is Locked!
    )
    if "!param1!"=="2" (
        REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
        echo USB Write is Unlocked! 
    )
)
pause
endlocal

How to get All input of POST in Laravel

It should be at least this:

public function login(Request $loginCredentials){
     $data = $loginCredentials->all();
     return $data['username'];
}

Nested select statement in SQL Server

The answer provided by Joe Stefanelli is already correct.

SELECT name FROM (SELECT name FROM agentinformation) as a  

We need to make an alias of the subquery because a query needs a table object which we will get from making an alias for the subquery. Conceptually, the subquery results are substituted into the outer query. As we need a table object in the outer query, we need to make an alias of the inner query.

Statements that include a subquery usually take one of these forms:

  • WHERE expression [NOT] IN (subquery)
  • WHERE expression comparison_operator [ANY | ALL] (subquery)
  • WHERE [NOT] EXISTS (subquery)

Check for more subquery rules and subquery types.

More examples of Nested Subqueries.

  1. IN / NOT IN – This operator takes the output of the inner query after the inner query gets executed which can be zero or more values and sends it to the outer query. The outer query then fetches all the matching [IN operator] or non matching [NOT IN operator] rows.

  2. ANY – [>ANY or ANY operator takes the list of values produced by the inner query and fetches all the values which are greater than the minimum value of the list. The

e.g. >ANY(100,200,300), the ANY operator will fetch all the values greater than 100.

  1. ALL – [>ALL or ALL operator takes the list of values produced by the inner query and fetches all the values which are greater than the maximum of the list. The

e.g. >ALL(100,200,300), the ALL operator will fetch all the values greater than 300.

  1. EXISTS – The EXISTS keyword produces a Boolean value [TRUE/FALSE]. This EXISTS checks the existence of the rows returned by the sub query.

ASP.NET MVC JsonResult Date Format

Format the date within the query.

var _myModel = from _m in model.ModelSearch(word)
    select new { date = ((DateTime)_m.Date).ToShortDateString() };

The only problem with this solution is that you won't get any results if ANY of the date values are null. To get around this you could either put conditional statements in your query BEFORE you select the date that ignores date nulls or you could set up a query to get all the results and then loop through all of that info using a foreach loop and assign a value to all dates that are null BEFORE you do your SELECT new.

Example of both:

var _test = from _t in adc.ItemSearchTest(word)
                        where _t.Date != null
                        select new { date = ((DateTime)_t.Date).ToShortDateString() };

The second option requires another query entirely so you can assign values to all nulls. This and the foreach loop would have to be BEFORE your query that selects the values.

var _testA = from _t in adc.ItemSearchTest(word)
                         select _i;

            foreach (var detail in _testA)
            {
                if (detail.Date== null)
                {
                    detail.Date= Convert.ToDateTime("1/1/0001");
                }
            }

Just an idea which I found easier than all of the javascript examples.

How to choose the right bean scope?

Since JSF 2.3 all the bean scopes defined in package javax.faces.bean package have been deprecated to align the scopes with CDI. Moreover they're only applicable if your bean is using @ManagedBean annotation. If you are using JSF versions below 2.3 refer to the legacy answer at the end.


From JSF 2.3 here are scopes that can be used on JSF Backing Beans:

1. @javax.enterprise.context.ApplicationScoped: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. This is useful when you have data for whole application.

2. @javax.enterprise.context.SessionScoped: The session scope persists from the time that a session is established until session termination. The session context is shared between all requests that occur in the same HTTP session. This is useful when you wont to save data for a specific client for a particular session.

3. @javax.enterprise.context.ConversationScoped: The conversation scope persists as log as the bean lives. The scope provides 2 methods: Conversation.begin() and Conversation.end(). These methods should called explicitly, either to start or end the life of a bean.

4. @javax.enterprise.context.RequestScoped: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.

5. @javax.faces.flow.FlowScoped: The Flow scope persists as long as the Flow lives. A flow may be defined as a contained set of pages (or views) that define a unit of work. Flow scoped been is active as long as user navigates with in the Flow.

6. @javax.faces.view.ViewScoped: A bean in view scope persists while the same JSF page is redisplayed. As soon as the user navigates to a different page, the bean goes out of scope.


The following legacy answer applies JSF version before 2.3

As of JSF 2.x there are 4 Bean Scopes:

  • @SessionScoped
  • @RequestScoped
  • @ApplicationScoped
  • @ViewScoped

Session Scope: The session scope persists from the time that a session is established until session termination. A session terminates if the web application invokes the invalidate method on the HttpSession object, or if it times out.

RequestScope: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.

ApplicationScope: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. You place managed beans into the application scope if a single bean should be shared among all instances of a web application. The bean is constructed when it is first requested by any user of the application, and it stays alive until the web application is removed from the application server.

ViewScope: View scope was added in JSF 2.0. A bean in view scope persists while the same JSF page is redisplayed. (The JSF specification uses the term view for a JSF page.) As soon as the user navigates to a different page, the bean goes out of scope.

Choose the scope you based on your requirement.

Source: Core Java Server Faces 3rd Edition by David Geary & Cay Horstmann [Page no. 51 - 54] enter image description here

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .AddItem
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

App.Config file in console application C#

use this

System.Configuration.ConfigurationSettings.AppSettings.Get("Keyname")

Change the current directory from a Bash script

I like to do the same thing for different projects without firing up a new shell.

In your case:

cd /home/artemb

Save the_script as:

echo cd /home/artemb

Then fire it up with:

\`./the_script\`

Then you get to the directory using the same shell.

Check if Cookie Exists

There are a lot of right answers here depending on what you are trying to accomplish; here's my attempt at providing a comprehensive answer:

Both the Request and Response objects contain Cookies properties, which are HttpCookieCollection objects.

Request.Cookies:

  • This collection contains cookies received from the client
  • This collection is read-only
  • If you attempt to access a non-existent cookie from this collection, you will receive a null value.

Response.Cookies:

  • This collection contains only cookies that have been added by the server during the current request.
  • This collection is writeable
  • If you attempt to access a non-existent cookie from this collection, you will receive a new cookie object; If the cookie that you attempted to access DOES NOT exist in the Request.Cookies collection, it will be added (but if the Request.Cookies object already contains a cookie with the same key, and even if it's value is stale, it will not be updated to reflect the changes from the newly-created cookie in the Response.Cookies collection.

Solutions


If you want to check for the existence of a cookie from the client, do one of the following

  • Request.Cookies["COOKIE_KEY"] != null
  • Request.Cookies.Get("COOKIE_KEY") != null
  • Request.Cookies.AllKeys.Contains("COOKIE_KEY")

If you want to check for the existence of a cookie that has been added by the server during the current request, do the following:

  • Response.Cookies.AllKeys.Contains("COOKIE_KEY") (see here)

Attempting to check for a cookie that has been added by the server during the current request by one of these methods...

  • Response.Cookies["COOKIE_KEY"] != null
  • Response.Cookies.Get("COOKIE_KEY") != null (see here)

...will result in the creation of a cookie in the Response.Cookies collection and the state will evaluate to true.

PHP filesize MB/KB conversion

This is based on @adnan's great answer.

Changes:

  • added internal filesize() call
  • return early style
  • saving one concatentation on 1 byte

And you can still pull the filesize() call out of the function, in order to get a pure bytes formatting function. But this works on a file.


/**
 * Formats filesize in human readable way.
 *
 * @param file $file
 * @return string Formatted Filesize, e.g. "113.24 MB".
 */
function filesize_formatted($file)
{
    $bytes = filesize($file);

    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        return $bytes . ' bytes';
    } elseif ($bytes == 1) {
        return '1 byte';
    } else {
        return '0 bytes';
    }
}

WCF error - There was no endpoint listening at

I had the same issue. For me I noticed that the https is using another Certificate which was invalid in terms of expiration date. Not sure why it happened. I changed the Https port number and a new self signed cert. WCFtestClinet could connect to the server via HTTPS!

Sleep function in ORACLE

It would be better to implement a synchronization mechanism. The easiest is to write a file after the first file is complete. So you have a sentinel file.

So the external programs looks for the sentinel file to exist. When it does it knows that it can safely use the data in the real file.

Another way to do this, which is similar to how some browsers do it when downloading files, is to have the file named base-name_part until the file is completely downloaded and then at the end rename the file to base-name. This way the external program can't "see" the file until it is complete. This way wouldn't require rewrite of the external program. Which might make it best for this situation.

How to move (and overwrite) all files from one directory to another?

mv -f source target

From the man page:

-f, --force
          do not prompt before overwriting

How to compare two JSON objects with the same elements in a different order equal?

If you want two objects with the same elements but in a different order to compare equal, then the obvious thing to do is compare sorted copies of them - for instance, for the dictionaries represented by your JSON strings a and b:

import json

a = json.loads("""
{
    "errors": [
        {"error": "invalid", "field": "email"},
        {"error": "required", "field": "name"}
    ],
    "success": false
}
""")

b = json.loads("""
{
    "success": false,
    "errors": [
        {"error": "required", "field": "name"},
        {"error": "invalid", "field": "email"}
    ]
}
""")
>>> sorted(a.items()) == sorted(b.items())
False

... but that doesn't work, because in each case, the "errors" item of the top-level dict is a list with the same elements in a different order, and sorted() doesn't try to sort anything except the "top" level of an iterable.

To fix that, we can define an ordered function which will recursively sort any lists it finds (and convert dictionaries to lists of (key, value) pairs so that they're orderable):

def ordered(obj):
    if isinstance(obj, dict):
        return sorted((k, ordered(v)) for k, v in obj.items())
    if isinstance(obj, list):
        return sorted(ordered(x) for x in obj)
    else:
        return obj

If we apply this function to a and b, the results compare equal:

>>> ordered(a) == ordered(b)
True

Routing with Multiple Parameters using ASP.NET MVC

You can pass arbitrary parameters through the query string, but you can also set up custom routes to handle it in a RESTful way:

http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist=cher&
                                  api_key=b25b959554ed76058ac220b7b2e0a026

That could be:

routes.MapRoute(
    "ArtistsImages",
    "{ws}/artists/{artist}/{action}/{*apikey}",
    new { ws = "2.0", controller="artists" artist = "", action="", apikey="" }
    );

So if someone used the following route:

ws.audioscrobbler.com/2.0/artists/cher/images/b25b959554ed76058ac220b7b2e0a026/

It would take them to the same place your example querystring did.

The above is just an example, and doesn't apply the business rules and constraints you'd have to set up to make sure people didn't 'hack' the URL.

What is the meaning of ImagePullBackOff status on a Kubernetes pod?

Despite all the other great answers none helped me until I found a comment that pointed out this Updating images:

The default pull policy is IfNotPresent which causes the kubelet to skip pulling an image if it already exists.

That's exactly what I wanted, but didn't seem to work.

Reading further said the following:

If you would like to always force a pull, you can do one of the following:

  • omit the imagePullPolicy and use :latest as the tag for the image to use.

When I replaced latest with a version (that I had pushed to minikube's Docker daemon), it worked fine.

$ kubectl create deployment presto-coordinator \
    --image=warsaw-data-meetup/presto-coordinator:beta0
deployment.apps/presto-coordinator created

$ kubectl get deployments
NAME                 READY   UP-TO-DATE   AVAILABLE   AGE
presto-coordinator   1/1     1            1           3s

Find the pod of the deployment (using kubectl get pods) and use kubectl describe pod to find out more on the pod.

Why do I get TypeError: can't multiply sequence by non-int of type 'float'?

raw_input returns a string (a sequence of characters). In Python, multiplying a string and a float makes no defined meaning (while multiplying a string and an integer has a meaning: "AB" * 3 is "ABABAB"; how much is "L" * 3.14 ? Please do not reply "LLL|"). You need to parse the string to a numerical value.

You might want to try:

salesAmount = float(raw_input("Insert sale amount here\n"))

How do I remove the first characters of a specific column in a table?

It would be good to share, For DB2 use: INSERT(someColumn, 1, 4, '')

Stuff is not supported in DB2

Get client IP address via third party web service

    $.ajax({
        url: '//freegeoip.net/json/',
        type: 'POST',
        dataType: 'jsonp',
        success: function(location) {
            alert(location.ip);
        }
    });

This will work https too

How to change default text file encoding in Eclipse?

To change the default encoding used for all workspaces you can do the following:

Create a defaults.ini file in the Eclipse configuration folder. For example, if Eclipse is installed in C:/Eclipse create C:/Eclipse/configuration/defaults.ini. The file should contain:

org.eclipse.core.resources/encoding=UTF-8

If you want to set the line terminator to UNIX values you can also add:

org.eclipse.core.runtime/line.separator=\n

In eclipse.ini in the Eclipse install folder (e.g., C:/Eclipse) add the following lines:

-plugincustomization 
D:/Java/Eclipse/configuration/defaults.ini

You might need to play around with where you put it. Inserting it before the "-product" option seemed to work.

How to read numbers separated by space using scanf

scanf uses any whitespace as a delimiter, so if you just say scanf("%d", &var) it will skip any whitespace and then read an integer (digits up to the next non-digit) and nothing more.

Note that whitespace is any whitespace -- spaces, tabs, newlines, or carriage returns. Any of those are whitespace and any one or more of them will serve to delimit successive integers.

regular expression for finding 'href' value of a <a> link

I'd recommend using an HTML parser over a regex, but still here's a regex that will create a capturing group over the value of the href attribute of each links. It will match whether double or single quotes are used.

<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1

You can view a full explanation of this regex at here.

Snippet playground:

_x000D_
_x000D_
const linkRx = /<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1/;_x000D_
const textToMatchInput = document.querySelector('[name=textToMatch]');_x000D_
_x000D_
document.querySelector('button').addEventListener('click', () => {_x000D_
  console.log(textToMatchInput.value.match(linkRx));_x000D_
});
_x000D_
<label>_x000D_
  Text to match:_x000D_
  <input type="text" name="textToMatch" value='<a href="google.com"'>_x000D_
  _x000D_
  <button>Match</button>_x000D_
 </label>
_x000D_
_x000D_
_x000D_

How do I install TensorFlow's tensorboard?

I have a local install of tensorflow 1.15.0 (with tensorboard obviously included) on MacOS.

For me, the path to the relevant file within my user directory is Library/Python/3.7/lib/python/site-packages/tensorboard/main.py. So, which does not work for me, but you have to look for the file named main.py, which is weird since it apparently is named something else for other users.

A TypeScript GUID class?

I found this https://typescriptbcl.codeplex.com/SourceControl/latest

here is the Guid version they have in case the link does not work later.

module System {
    export class Guid {
        constructor (public guid: string) {
            this._guid = guid;
        }

        private _guid: string;

        public ToString(): string {
            return this.guid;
        }

        // Static member
        static MakeNew(): Guid {
            var result: string;
            var i: string;
            var j: number;

            result = "";
            for (j = 0; j < 32; j++) {
                if (j == 8 || j == 12 || j == 16 || j == 20)
                    result = result + '-';
                i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
                result = result + i;
            }
            return new Guid(result);
        }
    }
}

Error: free(): invalid next size (fast):

It means that you have a memory error. You may be trying to free a pointer that wasn't allocated by malloc (or delete an object that wasn't created by new) or you may be trying to free/delete such an object more than once. You may be overflowing a buffer or otherwise writing to memory to which you shouldn't be writing, causing heap corruption.

Any number of programming errors can cause this problem. You need to use a debugger, get a backtrace, and see what your program is doing when the error occurs. If that fails and you determine you have corrupted the heap at some previous point in time, you may be in for some painful debugging (it may not be too painful if the project is small enough that you can tackle it piece by piece).

Oracle DB : java.sql.SQLException: Closed Connection

It means the connection was successfully established at some point, but when you tried to commit right there, the connection was no longer open. The parameters you mentioned sound like connection pool settings. If so, they're unrelated to this problem. The most likely cause is a firewall between you and the database that is killing connections after a certain amount of idle time. The most common fix is to make your connection pool run a validation query when a connection is checked out from it. This will immediately identify and evict dead connnections, ensuring that you only get good connections out of the pool.

Java: Literal percent sign in printf statement

You can use StringEscapeUtils from Apache Commons Logging utility or escape manually using code for each character.

SOAP request to WebService with java

I have come across other similar question here. Both of above answers are perfect, but here trying to add additional information for someone looking for SOAP1.1, and not SOAP1.2.

Just change one line code provided by @acdcjunior, use SOAPMessageFactory1_1Impl implementation, it will change namespace to xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/", which is SOAP1.1 implementation.

Change callSoapWebService method first line to following.

SOAPMessage soapMessage = SOAPMessageFactory1_1Impl.newInstance().createMessage();

I hope it will be helpful to others.

'App not Installed' Error on Android

In case, you have your app's older version installed from Google Play and you want to test the newer release version of your app:

  1. Open Google Play Console

  2. Upload the newer release version of your app to Alpha / Beta, but do not release it yet!

enter image description here

  1. You can now download the derived apk:
    enter image description here

Install the downloaded derived apk on your phone now. The derived apk is re-signed by Google Play with a different key from the release app Android Studio generates.

Inline comments for Bash?

Here's my solution for inline comments in between multiple piped commands.

Example uncommented code:

    #!/bin/sh
    cat input.txt \
    | grep something \
    | sort -r

Solution for a pipe comment (using a helper function):

    #!/bin/sh
    pipe_comment() {
        cat - 
    }
    cat input.txt \
    | pipe_comment "filter down to lines that contain the word: something" \
    | grep something \
    | pipe_comment "reverse sort what is left" \
    | sort -r

Or if you prefer, here's the same solution without the helper function, but it's a little messier:

    #!/bin/sh
    cat input.txt \
    | cat - `: filter down to lines that contain the word: something` \
    | grep something \
    | cat - `: reverse sort what is left` \
    | sort -r

Get domain name

I found this question by the title. If anyone else is looking for the answer on how to just get the domain name, use the following environment variable.

System.Environment.UserDomainName

I'm aware that the author to the question mentions this, but I missed it at the first glance and thought someone else might do the same.

What the description of the question then ask for is the fully qualified domain name (FQDN).

Chrome ignores autocomplete="off"

Chrome version 34 now ignores the autocomplete=off, see this.

Lots of discussion on whether this is a good thing or a bad thing? Whats your views?

Prefer composition over inheritance?

Composition v/s Inheritance is a wide subject. There is no real answer for what is better as I think it all depends on the design of the system.

Generally type of relationship between object provide better information to choose one of them.

If relation type is "IS-A" relation then Inheritance is better approach. otherwise relation type is "HAS-A" relation then composition will better approach.

Its totally depend on entity relationship.

What's the difference between process.cwd() vs __dirname?

As per node js doc process.cwd()

cwd is a method of global object process, returns a string value which is the current working directory of the Node.js process.

As per node js doc __dirname

The directory name of current script as a string value. __dirname is not actually a global but rather local to each module.

Let me explain with example,

suppose we have a main.js file resides inside C:/Project/main.js and running node main.js both these values return same file

or simply with following folder structure

Project 
+-- main.js
+--lib
   +-- script.js

main.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

suppose we have another file script.js files inside a sub directory of project ie C:/Project/lib/script.js and running node main.js which require script.js

main.js

require('./lib/script.js')
console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

script.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project\lib
console.log(__dirname===process.cwd())
// false

MINGW64 "make build" error: "bash: make: command not found"

  • Go to ezwinports, https://sourceforge.net/projects/ezwinports/files/

  • Download make-4.2.1-without-guile-w32-bin.zip (get the version without guile)

  • Extract zip
  • Copy the contents to C:\ProgramFiles\Git\mingw64\ merging the folders, but do NOT overwrite/replace any exisiting files.

How can I share Jupyter notebooks with non-programmers?

Google has recently made public its internal Collaboratory project (link here). You can start a notebook in the same way as starting a Google Sheet or Google Doc, and then simply share the notebook or add collaborators..

For now, this is the easiest way for me.

Command-line Unix ASCII-based charting / plotting tool

Try gnuplot. It has very powerful graphing possibilities.

It can output to your terminal in the following way:

gnuplot> set terminal dumb
Terminal type set to 'dumb'
Options are 'feed 79 24'
gnuplot> plot sin(x)

   1 ++----------------**---------------+----**-----------+--------**-----++
     +                *+ *              +   *  *          +  sin(x) ****** +
 0.8 ++              *    *                *    *                *    *   ++
     |               *    *                *    *                *    *    |
 0.6 ++              *     *              *      *              *      *  ++
     *              *       *             *       *             *      *   |
 0.4 +*             *       *             *       *             *      *  ++
     |*            *        *            *        *            *        *  |
 0.2 +*            *        *            *        *            *        * ++
     | *          *          *          *          *          *          * |
   0 ++*          *          *          *          *          *          *++
     |  *         *           *         *           *         *           *|
-0.2 ++ *         *           *         *           *         *           *+
     |   *       *            *        *            *        *            *|
-0.4 ++  *       *            *        *            *        *            *+
     |   *      *              *      *              *      *              *
-0.6 ++  *      *              *      *              *      *             ++
     |    *     *               *     *               *    *               |
-0.8 ++    *   *                 *   *                *    *              ++
     +     *  *        +         *  *   +              *  *                +
  -1 ++-----**---------+----------**----+---------------**+---------------++
    -10               -5                0                 5                10

function to remove duplicate characters in a string

I resolve a similar exercise of the book : crackring the coding interview using recursion.

package crackingcodeinterview;

public class Exercise {

static String textString = "this is a random text of example!@#$%^(^452464156";

public static void main(String[] args) {

    filterLetters(0, "");
}

public static void filterLetters(int position, String letters) {
    if (position != textString.length()) {

        boolean p = false;

        for (int i = 0; i < letters.length(); i++) {
            if (letters.charAt(i) == textString.charAt(position)) {
                p = true;
                break;
            }
        }

        if (!p) {
            letters += textString.charAt(position);
        }
        position++;
        filterLetters(position, letters);
    } else {
        System.out.println(letters);
    }
  }
}

Other solution using substring and recursion

public class MyClass {
public static void main(String args[]) {

    getUnicLetter("esta es una cadena con letras repetidas","");
}



   public static String getUnicLetter(String originalWord,String finalWord){
        if(originalWord.isEmpty()) return  null;
        System.out.print(finalWord);
        return getUnicLetter(originalWord.replace(originalWord.substring(0,1),""),finalWord.contains(originalWord.substring(0,1)) ? "" : originalWord.substring(0,1));
    }

}

Create an ArrayList of unique values

If you need unique values, you should use the implementation of the SET interface

Nginx: Permission denied for nginx on Ubuntu

If i assume that your second code is the puppet config then i have a logical explaination, if the error and log files were create before, you can try this

sudo chown -R www-data:www-data /var/log/nginx;
sudo chmod -R 755 /var/log/nginx;

How to print something when running Puppet client?

You could go a step further and break into the puppet code using a breakpoint.

http://logicminds.github.io/blog/2017/04/25/break-into-your-puppet-code/

This would only work with puppet apply or using a rspec test. Or you can manually type your code into the debugger console. Note: puppet still needs to know where your module code is at if you haven't set already.

gem install puppet puppet-debugger 
puppet module install nwops/debug
cat > test.pp <<'EOF'
$var1 = 'test'
debug::break()
EOF

Should show something like.

puppet apply test.pp
From file: test.pp
     1: $var1 = 'test'
     2: # add 'debug::break()' where you want to stop in your code
  => 3: debug::break()
1:>> $var1
=> "test"
2:>>

https://www.puppet-debugger.com

How to check if another instance of the application is running

You can try this

Process[] processes = Process.GetProcessesByName("processname");
foreach (Process p in processes)
{
    IntPtr pFoundWindow = p.MainWindowHandle;
    // Do something with the handle...
    //
}

Can't create handler inside thread which has not called Looper.prepare()

You create handler in background thread this way

private void createHandler() {
        Thread thread = new Thread() {
          public void run() {
               Looper.prepare();

               final Handler handler = new Handler();
               handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                       // Do Work
                        handler.removeCallbacks(this);
                        Looper.myLooper().quit();
                   }
                }, 2000);

                Looper.loop();
            }
        };
        thread.start();
    }

How to create dynamic href in react render function?

Use string concatenation:

href={'/posts/' + post.id}

The JSX syntax allows either to use strings or expressions ({...}) as values. You cannot mix both. Inside an expression you can, as the name suggests, use any JavaScript expression to compute the value.

Shell Script: Execute a python program from within a shell script

Method 1 - Create a shell script:

Suppose you have a python file hello.py Create a file called job.sh that contains

#!/bin/bash
python hello.py

mark it executable using

$ chmod +x job.sh

then run it

$ ./job.sh

Method 2 (BETTER) - Make the python itself run from shell:

Modify your script hello.py and add this as the first line

#!/usr/bin/env python

mark it executable using

$ chmod +x hello.py

then run it

$ ./hello.py

jQuery convert line breaks to br (nl2br equivalent)

you can simply do:

textAreaContent=textAreaContent.replace(/\n/g,"<br>");

python modify item in list, save back in list

For Python 3:

ListOfStrings = []
ListOfStrings.append('foo')
ListOfStrings.append('oof')
for idx, item in enumerate(ListOfStrings):
if 'foo' in item:
    ListOfStrings[idx] = "bar"

How to get image width and height in OpenCV?

You can use rows and cols:

cout << "Width : " << src.cols << endl;
cout << "Height: " << src.rows << endl;

or size():

cout << "Width : " << src.size().width << endl;
cout << "Height: " << src.size().height << endl;

How to getElementByClass instead of GetElementById with JavaScript?

adding to CMS's answer, this is a more generic approach of toggle_visibility I've just used myself:

function toggle_visibility(className,display) {
   var elements = getElementsByClassName(document, className),
       n = elements.length;
   for (var i = 0; i < n; i++) {
     var e = elements[i];

     if(display.length > 0) {
       e.style.display = display;
     } else {
       if(e.style.display == 'block') {
         e.style.display = 'none';
       } else {
         e.style.display = 'block';
       }
     }
  }
}

How to write a basic swap function in Java

//here is also another answer:
class SwapDemo{
    static int a=1, b=2 ;
    public static void main(String [] args){
        Swap swp = new Swap();
        swp.swaps(x,y);
        System.out.println( " a (was 1)now is " + a + " b (was 2) now is " + b);
    }
}
class Swap{
    void swaps(int c, int d){
            SwapDemo f = new SwapDemo();
            f.a = c;
            f.a = d;
        }
}

What does "@" mean in Windows batch scripts

Another useful time to include @ is when you use FOR in the command line. For example:

FOR %F IN (*.*) DO ECHO %F

Previous line show for every file: the command prompt, the ECHO command, and the result of ECHO command. This way:

FOR %F IN (*.*) DO @ECHO %F

Just the result of ECHO command is shown.

moment.js get current time in milliseconds?

See this link http://momentjs.com/docs/#/displaying/unix-timestamp-milliseconds/

valueOf() is the function you're looking for.

Editing my answer (OP wants milliseconds of today, not since epoch)

You want the milliseconds() function OR you could go the route of moment().valueOf()

How do you do natural logs (e.g. "ln()") with numpy in Python?

I usually do like this:

from numpy import log as ln

Perhaps this can make you more comfortable.

Correct way to work with vector of arrays

There is no error in the following piece of code:

float arr[4];
arr[0] = 6.28;
arr[1] = 2.50;
arr[2] = 9.73;
arr[3] = 4.364;
std::vector<float*> vec = std::vector<float*>();
vec.push_back(arr);
float* ptr = vec.front();
for (int i = 0; i < 3; i++)
    printf("%g\n", ptr[i]);

OUTPUT IS:

6.28

2.5

9.73

4.364

IN CONCLUSION:

std::vector<double*>

is another possibility apart from

std::vector<std::array<double, 4>>

that James McNellis suggested.

jQuery .live() vs .on() method for adding a click event after loading dynamic html

Try this:

$('#parent').on('click', '#child', function() {
    // Code
});

From the $.on() documentation:

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

Your #child element doesn't exist when you call $.on() on it, so the event isn't bound (unlike $.live()). #parent, however, does exist, so binding the event to that is fine.

The second argument in my code above acts as a 'filter' to only trigger if the event bubbled up to #parent from #child.

Excel 2010 VBA Referencing Specific Cells in other worksheets

I am going to give you a simplistic answer that hopefully will help you with VBA in general. The easiest way to learn how VBA works and how to reference and access elements is to record your macro then edit it in the VBA editor. This is how I learned VBA. It is based on visual basic so all the programming conventions of VB apply. Recording the macro lets you see how to access and do things.

you could use something like this:

var result = 0
Sheets("Sheet1").Select
result = Range("A1").Value * Range("B1").Value
Sheets("Sheet2").Select
Range("D1").Value = result

Alternatively you can also reference a cell using Cells(1,1).Value This way you can set variables and increment them as you wish. I think I am just not clear on exactly what you are trying to do but i hope this helps.

SimpleXML - I/O warning : failed to load external entity

You can also load the content with cURL, if file_get_contents insn't enabled on your server.

Example:

$ch = curl_init();  

curl_setopt($ch,CURLOPT_URL,"http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=int");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

$output = curl_exec($ch);

curl_close($ch);

$items = simplexml_load_string($output);

How to set downloading file name in ASP.NET Web API

If you are using ASP.NET Core MVC, the answers above are ever so slightly altered...

In my action method (which returns async Task<JsonResult>) I add the line (anywhere before the return statement):

Response.Headers.Add("Content-Disposition", $"attachment; filename={myFileName}");

How to use Console.WriteLine in ASP.NET (C#) during debug?

Trace.Write("Error Message") and Trace.Warn("Error Message") are the methods to use in web, need to decorate the page header trace=true and in config file to hide the error message text to go to end-user and so as to stay in iis itself for programmer debug.

Django: save() vs update() to update the database?

Both looks similar, but there are some key points:

  1. save() will trigger any overridden Model.save() method, but update() will not trigger this and make a direct update on the database level. So if you have some models with overridden save methods, you must either avoid using update or find another way to do whatever you are doing on that overridden save() methods.

  2. obj.save() may have some side effects if you are not careful. You retrieve the object with get(...) and all model field values are passed to your obj. When you call obj.save(), django will save the current object state to record. So if some changes happens between get() and save() by some other process, then those changes will be lost. use save(update_fields=[.....]) for avoiding such problems.

  3. Before Django version 1.5, Django was executing a SELECT before INSERT/UPDATE, so it costs 2 query execution. With version 1.5, that method is deprecated.

In here, there is a good guide or save() and update() methods and how they are executed.

Git Bash won't run my python files?

When you install python for windows, there is an option to include it in the path. For python 2 this is not the default. It adds the python installation folder and script folder to the Windows path. When starting the GIT Bash command prompt, it have included it in the linux PATH variable.

If you start the python installation again, you should select the option Change python and in the next step you can "Add python.exe to Path". Next time you open GIT Bash, the path is correct.

How to test abstract class in Java with JUnit?

You could do something like this

public abstract MyAbstractClass {

    @Autowire
    private MyMock myMock;        

    protected String sayHello() {
            return myMock.getHello() + ", " + getName();
    }

    public abstract String getName();
}

// this is your JUnit test
public class MyAbstractClassTest extends MyAbstractClass {

    @Mock
    private MyMock myMock;

    @InjectMocks
    private MyAbstractClass thiz = this;

    private String myName = null;

    @Override
    public String getName() {
        return myName;
    }

    @Test
    public void testSayHello() {
        myName = "Johnny"
        when(myMock.getHello()).thenReturn("Hello");
        String result = sayHello();
        assertEquals("Hello, Johnny", result);
    }
}

XSL xsl:template match="/"

The match attribute indicates on which parts the template transformation is going to be applied. In that particular case the "/" means the root of the xml document. The value you have to provide into the match attribute should be XPath expression. XPath is the language you have to use to refer specific parts of the target xml file.

To gain a meaningful understanding of what else you can put into match attribute you need to understand what xpath is and how to use it. I suggest yo look at links I've provided for youat the bottom of the answer.

Could I write "table" or any other html tag instead of "/" ?

Yes you can. But this depends what exactly you are trying to do. if your target xml file contains HMTL elements and you are triyng to apply this xsl:template on them it makes sense to use table, div or anithing else.

Here a few links:

Make a VStack fill the width of the screen in SwiftUI

use this

.edgesIgnoringSafeArea(.all)

Difference between break and continue in PHP?

I am not writing anything same here. Just a changelog note from PHP manual.


Changelog for continue

Version Description

7.0.0 - continue outside of a loop or switch control structure is now detected at compile-time instead of run-time as before, and triggers an E_COMPILE_ERROR.

5.4.0   continue 0; is no longer valid. In previous versions it was interpreted the same as continue 1;.

5.4.0   Removed the ability to pass in variables (e.g., $num = 2; continue $num;) as the numerical argument.

Changelog for break

Version Description

7.0.0   break outside of a loop or switch control structure is now detected at compile-time instead of run-time as before, and triggers an E_COMPILE_ERROR.

5.4.0   break 0; is no longer valid. In previous versions it was interpreted the same as break 1;.

5.4.0   Removed the ability to pass in variables (e.g., $num = 2; break $num;) as the numerical argument.

How to send custom headers with requests in Swagger UI?

For those who use NSwag and need a custom header:

app.UseSwaggerUi3(typeof(Startup).GetTypeInfo().Assembly, settings =>
      {
          settings.GeneratorSettings.IsAspNetCore = true;
          settings.GeneratorSettings.OperationProcessors.Add(new OperationSecurityScopeProcessor("custom-auth"));

          settings.GeneratorSettings.DocumentProcessors.Add(
              new SecurityDefinitionAppender("custom-auth", new SwaggerSecurityScheme
                {
                    Type = SwaggerSecuritySchemeType.ApiKey,
                    Name = "header-name",
                    Description = "header description",
                    In = SwaggerSecurityApiKeyLocation.Header
                }));
        });            
    }

Swagger UI will then include an Authorize button.

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

Doing it in one bulk read:

import re

textfile = open(filename, 'r')
filetext = textfile.read()
textfile.close()
matches = re.findall("(<(\d{4,5})>)?", filetext)

Line by line:

import re

textfile = open(filename, 'r')
matches = []
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
    matches += reg.findall(line)
textfile.close()

But again, the matches that returns will not be useful for anything except counting unless you added an offset counter:

import re

textfile = open(filename, 'r')
matches = []
offset = 0
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
    matches += [(reg.findall(line),offset)]
    offset += len(line)
textfile.close()

But it still just makes more sense to read the whole file in at once.

Python re.sub replace with matched content

Simply use \1 instead of $1:

In [1]: import re

In [2]: method = 'images/:id/huge'

In [3]: re.sub(r'(:[a-z]+)', r'<span>\1</span>', method)
Out[3]: 'images/<span>:id</span>/huge'

Also note the use of raw strings (r'...') for regular expressions. It is not mandatory but removes the need to escape backslashes, arguably making the code slightly more readable.

Reverse a string in Java

import java.util.Scanner;
public class StringReverseExample
{
    public static void main(String[] args)
    {
        String str,rev;
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the string : ");
        str = in.nextLine();
        rev = new StringBuffer(str).reverse().toString();
        System.out.println("\nString before reverse:"+str);
        System.out.println("String after reverse:"+rev);
    }
}
/* Output : 
Enter the string : satyam

String before reverse:satyam
String after reverse:maytas */

T-SQL datetime rounded to nearest minute and nearest hours with using functions

"Rounded" down as in your example. This will return a varchar value of the date.

DECLARE @date As DateTime2
SET @date = '2007-09-22 15:07:38.850'

SELECT CONVERT(VARCHAR(16), @date, 120) --2007-09-22 15:07
SELECT CONVERT(VARCHAR(13), @date, 120) --2007-09-22 15

MySQL convert date string to Unix timestamp

For current date just use UNIX_TIMESTAMP() in your MySQL query.

Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu

From my experience, sudo apt-get install gcc-multilib g++-multilib helps. But my another issue is that I FORGET to clean the directory so I still get the same error. It is the first time to use clang or cmake. So I just delete my original directory and re-compile and it works. Hope it helps someone like me.

What is the difference between a framework and a library?

Actually these terms can mean a lot of different things depending the context they are used.

For example, on Mac OS X frameworks are just libraries, packed into a bundle. Within the bundle you will find an actual dynamic library (libWhatever.dylib). The difference between a bare library and the framework on Mac is that a framework can contain multiple different versions of the library. It can contain extra resources (images, localized strings, XML data files, UI objects, etc.) and unless the framework is released to public, it usually contains the necessary .h files you need to use the library.

Thus you have everything within a single package you need to use the library in your application (a C/C++/Objective-C library without .h files is pretty useless, unless you write them yourself according to some library documentation), instead of a bunch of files to move around (a Mac bundle is just a directory on the Unix level, but the UI treats it like a single file, pretty much like you have JAR files in Java and when you click it, you usually don't see what's inside, unless you explicitly select to show the content).

Wikipedia calls framework a "buzzword". It defines a software framework as

A software framework is a re-usable design for a software system (or subsystem). A software framework may include support programs, code libraries, a scripting language, or other software to help develop and glue together the different components of a software project. Various parts of the framework may be exposed through an API..

So I'd say a library is just that, "a library". It is a collection of objects/functions/methods (depending on your language) and your application "links" against it and thus can use the objects/functions/methods. It is basically a file containing re-usable code that can usually be shared among multiple applications (you don't have to write the same code over and over again).

A framework can be everything you use in application development. It can be a library, a collection of many libraries, a collection of scripts, or any piece of software you need to create your application. Framework is just a very vague term.

Here's an article about some guy regarding the topic "Library vs. Framework". I personally think this article is highly arguable. It's not wrong what he's saying there, however, he's just picking out one of the multiple definitions of framework and compares that to the classic definition of library. E.g. he says you need a framework for sub-classing. Really? I can have an object defined in a library, I can link against it, and sub-class it in my code. I don't see how I need a "framework" for that. In some way he rather explains how the term framework is used nowadays. It's just a hyped word, as I said before. Some companies release just a normal library (in any sense of a classical library) and call it a "framework" because it sounds more fancy.

How does Spring autowire by name when more than one matching bean is found?

Another way of achieving the same result is to use the @Value annotation:

public class Main {
     private Country country;

     @Autowired
     public void setCountry(@Value("#{country}") Country country) {
          this.country = country;
     }
}

In this case, the "#{country} string is an Spring Expression Language (SpEL) expression which evaluates to a bean named country.

Refreshing all the pivot tables in my excel workbook with a macro

There is a refresh all option in the Pivot Table tool bar. That is enough. Dont have to do anything else.

Press ctrl+alt+F5

Mysql password expired. Can't connect

Just download MySQL workbench to log in. It will prompt you to change the password immediately and automatically.

How to display count of notifications in app launcher icon

It works in samsung touchwiz launcher

public static void setBadge(Context context, int count) {
    String launcherClassName = getLauncherClassName(context);
    if (launcherClassName == null) {
        return;
    }
    Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
    intent.putExtra("badge_count", count);
    intent.putExtra("badge_count_package_name", context.getPackageName());
    intent.putExtra("badge_count_class_name", launcherClassName);
    context.sendBroadcast(intent);
}

public static String getLauncherClassName(Context context) {

    PackageManager pm = context.getPackageManager();

    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);

    List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
    for (ResolveInfo resolveInfo : resolveInfos) {
        String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
        if (pkgName.equalsIgnoreCase(context.getPackageName())) {
            String className = resolveInfo.activityInfo.name;
            return className;
        }
    }
    return null;
}

Entity Framework Code First - two Foreign Keys from same table

It's also possible to specify the ForeignKey() attribute on the navigation property:

[ForeignKey("HomeTeamID")]
public virtual Team HomeTeam { get; set; }
[ForeignKey("GuestTeamID")]
public virtual Team GuestTeam { get; set; }

That way you don't need to add any code to the OnModelCreate method

What is the difference between SAX and DOM?

You're comparing apples and pears. SAX is a parser that parses serialized DOM structures. There are many different parsers, and "event-based" refers to the parsing method.

Maybe a small recap is in order:

  • The document object model (DOM) is an abstract data model that describes a hierarchical, tree-based document structure; a document tree consists of nodes, namely element, attribute and text nodes (and some others). Nodes have parents, siblings and children and can be traversed, etc., all the stuff you're used to from doing JavaScript (which incidentally has nothing to do with the DOM).

  • A DOM structure may be serialized, i.e. written to a file, using a markup language like HTML or XML. An HTML or XML file thus contains a "written out" or "flattened out" version of an abstract document tree.

  • For a computer to manipulate, or even display, a DOM tree from a file, it has to deserialize, or parse, the file and reconstruct the abstract tree in memory. This is where parsing comes in.

Now we come to the nature of parsers. One way to parse would be to read in the entire document and recursively build up a tree structure in memory, and finally expose the entire result to the user. (I suppose you could call these parsers "DOM parsers".) That would be very handy for the user (I think that's what PHP's XML parser does), but it suffers from scalability problems and becomes very expensive for large documents.

On the other hand, event-based parsing, as done by SAX, looks at the file linearly and simply makes call-backs to the user whenever it encounters a structural piece of data, like "this element started", "that element ended", "some text here", etc. This has the benefit that it can go on forever without concern for the input file size, but it's a lot more low-level because it requires the user to do all the actual processing work (by providing call-backs). To return to your original question, the term "event-based" refers to those parsing events that the parser raises as it traverses the XML file.

The Wikipedia article has many details on the stages of SAX parsing.

What's the UIScrollView contentInset property for?

Great question.

Consider the following example (scroller is a UIScrollView):

float offset = 1000;
[super viewDidLoad];
for (int i=0;i<500; i++) {
    UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(i * 100, 50, 95, 100)] autorelease];
    [label setText:[NSString stringWithFormat:@"label %d",i]];
    [self.scroller addSubview:label];
    [self.scroller setContentSize:CGSizeMake(self.view.frame.size.width * 2 + offset, 0)];
    [self.scroller setContentInset:UIEdgeInsetsMake(0, -offset, 0, 0)];
}

The insets are the ONLY way to force your scroller to have a "window" on the content where you want it. I'm still messing with this sample code, but the idea is there: use the insets to get a "window" on your UIScrollView.

How to pass List from Controller to View in MVC 3

Passing data to view is simple as passing object to method. Take a look at Controller.View Method

protected internal ViewResult View(
    Object model
)

Something like this

//controller

List<MyObject> list = new List<MyObject>();

return View(list);


//view

@model List<MyObject>

// and property Model is type of List<MyObject>

@foreach(var item in Model)
{
    <span>@item.Name</span>
}

How can I sort a dictionary by key?

In Python 3.

>>> D1 = {2:3, 1:89, 4:5, 3:0}
>>> for key in sorted(D1):
    print (key, D1[key])

gives

1 89
2 3
3 0
4 5

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

One of the most common errors that I found developing Android Apps is the “java.lang.OutOfMemoryError: Bitmap Size Exceeds VM Budget” error. I found this error frequently on activities using lots of bitmaps after changing orientation: the Activity is destroyed, created again and the layouts are “inflated” from the XML consuming the VM memory available for bitmaps.

Bitmaps on the previous activity layout are not properly de-allocated by the garbage collector because they have crossed references to their activity. After many experiments I found a quite good solution for this problem.

First, set the “id” attribute on the parent view of your XML layout:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:id="@+id/RootView"
     >
     ...

Then, on the onDestroy() method of your Activity, call the unbindDrawables() method passing a reference to the parent View and then do a System.gc().

    @Override
    protected void onDestroy() {
    super.onDestroy();

    unbindDrawables(findViewById(R.id.RootView));
    System.gc();
    }

    private void unbindDrawables(View view) {
        if (view.getBackground() != null) {
        view.getBackground().setCallback(null);
        }
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
            unbindDrawables(((ViewGroup) view).getChildAt(i));
            }
        ((ViewGroup) view).removeAllViews();
        }
    }

This unbindDrawables() method explores the view tree recursively and:

  1. Removes callbacks on all the background drawables
  2. Removes children on every viewgroup

Laravel 5: Display HTML with Blade

For laravel 5

{!!html_entity_decode($text)!!}

Figured out through this link, see RachidLaasri answer

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

cracked it after 2 hours...

  1. download this usb driver: http://dlcdnet.asus.com/pub/ASUS/EeePAD/nexus7/usb_driver_r06_windows.zip

2.go to the device manager , right click the nexus device and choose properties, choose "hardware" and then choose update your driver , choose manualy and pick the folder you opend the zip file to and press apply.

3.open your setting in nexus . go to : "about the device" , at to the bottom of the page and press it strong text7 times .

4.open the developers menu and enable debug with usb.

5.finally press storage from the setting menu and click the menu that apears at the top left corner. press the connect usb to the computer, choose the second option (PTP).

one more thing: if that doesn't work restart your computer

that should do the trick , they couldn't make it more simple than that...

How are software license keys generated?

I've not got any experience with what people actually do to generate CD keys, but (assuming you're not wanting to go down the road of online activation) here are a few ways one could make a key:

  • Require that the number be divisible by (say) 17. Trivial to guess, if you have access to many keys, but the majority of potential strings will be invalid. Similar would be requiring that the checksum of the key match a known value.

  • Require that the first half of the key, when concatenated with a known value, hashes down to the second half of the key. Better, but the program still contains all the information needed to generate keys as well as to validate them.

  • Generate keys by encrypting (with a private key) a known value + nonce. This can be verified by decrypting using the corresponding public key and verifying the known value. The program now has enough information to verify the key without being able to generate keys.

These are still all open to attack: the program is still there and can be patched to bypass the check. Cleverer might be to encrypt part of the program using the known value from my third method, rather than storing the value in the program. That way you'd have to find a copy of the key before you could decrypt the program, but it's still vulnerable to being copied once decrypted and to having one person take their legit copy and use it to enable everyone else to access the software.

Integer division: How do you produce a double?

Type Casting Is The Only Way

May be you will not do it explicitly but it will happen.

Now, there are several ways we can try to get precise double value (where num and denom are int type, and of-course with casting)-

  1. with explicit casting:
  • double d = (double) num / denom;
  • double d = ((double) num) / denom;
  • double d = num / (double) denom;
  • double d = (double) num / (double) denom;

but not double d = (double) (num / denom);

  1. with implicit casting:
  • double d = num * 1.0 / denom;
  • double d = num / 1d / denom;
  • double d = ( num + 0.0 ) / denom;
  • double d = num; d /= denom;

but not double d = num / denom * 1.0;
and not double d = 0.0 + ( num / denom );


Now if you are asking- Which one is better? explicit? or implicit?

Well, lets not follow a straight answer here. Simply remember- We programmers don't like surprises or magics in a source. And we really hate Easter Eggs.

Also, an extra operation will definitely not make your code more efficient. Right?

Read a text file in R line by line

I write a code to read file line by line to meet my demand which different line have different data type follow articles: read-line-by-line-of-a-file-in-r and determining-number-of-linesrecords. And it should be a better solution for big file, I think. My R version (3.3.2).

con = file("pathtotargetfile", "r")
readsizeof<-2    # read size for one step to caculate number of lines in file
nooflines<-0     # number of lines
while((linesread<-length(readLines(con,readsizeof)))>0)    # calculate number of lines. Also a better solution for big file
  nooflines<-nooflines+linesread

con = file("pathtotargetfile", "r")    # open file again to variable con, since the cursor have went to the end of the file after caculating number of lines
typelist = list(0,'c',0,'c',0,0,'c',0)    # a list to specific the lines data type, which means the first line has same type with 0 (e.g. numeric)and second line has same type with 'c' (e.g. character). This meet my demand.
for(i in 1:nooflines) {
  tmp <- scan(file=con, nlines=1, what=typelist[[i]], quiet=TRUE)
  print(is.vector(tmp))
  print(tmp)
}
close(con)

Git: How to reset a remote Git repository to remove all commits?

First, follow the instructions in this question to squash everything to a single commit. Then make a forced push to the remote:

$ git push origin +master

And optionally delete all other branches both locally and remotely:

$ git push origin :<branch>
$ git branch -d <branch>

Ansible: Store command's stdout in new variable?

In case than you want to store a complex command to compare text result, for example to compare the version of OS, maybe this can help you:

tasks:
       - shell: echo $(cat /etc/issue | awk {'print $7'})
         register: echo_content

       - shell: echo "It works"
         when: echo_content.stdout == "12"
         register: out
       - debug: var=out.stdout_lines

Is it possible to import a whole directory in sass using @import?

You might want to retain source order then you can just use this.

@import
  'foo',
  'bar';

I prefer this.

Professional jQuery based Combobox control?

Here's one that looks very promising. It's a true combo - you see what you type. Has a cool feature I haven't seen elsewhere: paging results.

FlexBox

What's the most appropriate HTTP status code for an "item not found" error page

/**
* {@code 422 Unprocessable Entity}.
* @see <a href="https://tools.ietf.org/html/rfc4918#section-11.2">WebDAV</a>
*/
UNPROCESSABLE_ENTITY(422, "Unprocessable Entity")

Binary search (bisection) in Python

Why not look at the code for bisect_left/right and adapt it to suit your purpose.

like this:

def binary_search(a, x, lo=0, hi=None):
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        midval = a[mid]
        if midval < x:
            lo = mid+1
        elif midval > x: 
            hi = mid
        else:
            return mid
    return -1

Callback to a Fragment from a DialogFragment

Maybe a bit late, but may help other people with the same question like I did.

You can use setTargetFragment on Dialog before showing, and in dialog you can call getTargetFragment to get the reference.

how to get the attribute value of an xml node using java

I'm happy that this snippet works fine:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File("config.xml"));
NodeList nodeList = document.getElementsByTagName("source");
for(int x=0,size= nodeList.getLength(); x<size; x++) {
    System.out.println(nodeList.item(x).getAttributes().getNamedItem("type").getNodeValue());
} 

IOS - How to segue programmatically using swift

This worked for me:

//Button method example
 @IBAction func LogOutPressed(_ sender: UIBarButtonItem) {

        do {
            try Auth.auth().signOut()
            navigationController?.popToRootViewController(animated: true)

        } catch let signOutError as NSError {
          print ("Error signing out: %@", signOutError)
        }


    }

Issue with parsing the content from json file with Jackson & message- JsonMappingException -Cannot deserialize as out of START_ARRAY token

Your JSON string is malformed: the type of center is an array of invalid objects. Replace [ and ] with { and } in the JSON string around longitude and latitude so they will be objects:

[
    {
        "name" : "New York",
        "number" : "732921",
        "center" : {
                "latitude" : 38.895111, 
                "longitude" : -77.036667
            }
    },
    {
        "name" : "San Francisco",
        "number" : "298732",
        "center" : {
                "latitude" : 37.783333, 
                "longitude" : -122.416667
            }
    }
]

php form action php self

How about leaving it empty, what is wrong with that?

<form name="form1" id="mainForm" method="post" enctype="multipart/form-data" action="">

</form>

Also, you can omit the action attribute and it will work as expected.

How to JOIN three tables in Codeigniter

try this

In your model

If u want get all album data use

  function get_all_album_data() {

    $this->db->select ( '*' ); 
    $this->db->from ( 'Album' );
    $this->db->join ( 'Category', 'Category.cat_id = Album.cat_id' , 'left' );
    $this->db->join ( 'Soundtrack', 'Soundtrack.album_id = Album.album_id' , 'left' );
    $query = $this->db->get ();
    return $query->result ();
 }

if u want to get specific album data use

  function get_album_data($album_id) {

    $this->db->select ( '*' ); 
    $this->db->from ( 'Album' );
    $this->db->join ( 'Category', 'Category.cat_id = Album.cat_id' , 'left' );
    $this->db->join ( 'Soundtrack', 'Soundtrack.album_id = Album.album_id' , 'left' );
    $this->db->where ( 'Album.album_id', $album_id);
    $query = $this->db->get ();
    return $query->result ();
 }

How do you find the current user in a Windows environment?

It should be in %USERNAME%. Obviously this can be easily spoofed, so don't rely on it for security.

Useful tip: type set in a command prompt will list all environment variables.

When is it appropriate to use C# partial classes?

I note two usages which I couldn't find explicitly in the answers.

Grouping Class Items

Some developers use comments to separate different "parts" of their class. For example, a team might use the following convention:

public class MyClass{  
  //Member variables
  //Constructors
  //Properties
  //Methods
}

With partial classes, we can go a step further, and split the sections into separate files. As a convention, a team might suffix each file with the section corresponding to it. So in the above we would have something like: MyClassMembers.cs, MyClassConstructors.cs, MyClassProperties.cs, MyClassMethods.cs.

As other answers alluded to, whether or not it's worth splitting the class up probably depends on how big the class is in this case. If it's small, it's probably easier to have everything in one master class. But if any of those sections get too big, its content can be moved to a separate partial class, in order to keep the master class neat. A convention in that case might be to leave a comment in saying something like "See partial class" after the section heading e.g.:

//Methods - See partial class

Managing Scope of Using statements / Namespace

This is probably a rare occurrence, but there might be a namespace collision between two functions from libraries that you want to use. In a single class, you could at most use a using clause for one of these. For the other you'd need a fully qualified name or an alias. With partial classes, since each namespace & using statements list is different, one could separate the two sets of functions into two separate files.

How do I remove my IntelliJ license in 2019.3?

Not sure about older versions, but in 2016.2 removing the .key file(s) didn't work for me.

I'm using my JetBrains account and used the 'Remove License' button found at the bottom of the registration dialog. You can find this under the Help menu or from the startup dialog via Configure -> Manage License....

Add views in UIStackView programmatically

In my case the thing that was messing with I would expect was that I was missing this line:

stackView.translatesAutoresizingMaskIntoConstraints = false;

After that no need to set constraints to my arranged subviews whatsoever, the stackview is taking care of that.

What is the difference between C and embedded C?

Embedded C is generally an extension of the C language, they are more or less similar. However, some differences do exist, such as:

  • C is generally used for desktop computers, while embedded C is for microcontroller based applications.

  • C can use the resources of a desktop PC like memory, OS, etc. While, embedded C has to use with the limited resources, such as RAM, ROM, I/Os on an embedded processor.

  • Embedded C includes extra features over C, such as fixed point types, multiple memory areas, and I/O register mapping.

  • Compilers for C (ANSI C) typically generate OS dependant executables. Embedded C requires compilers to create files to be downloaded to the microcontrollers/microprocessors where it needs to run.

Refer difference between C and embedded C

update query with join on two tables

Officially, the SQL languages does not support a JOIN or FROM clause in an UPDATE statement unless it is in a subquery. Thus, the Hoyle ANSI approach would be something like

Update addresses
Set cid = (
            Select c.id
            From customers As c
            where c.id = a.id
            )
Where Exists    (
                Select 1
                From customers As C1
                Where C1.id = addresses.id
                )

However many DBMSs such Postgres support the use of a FROM clause in an UPDATE statement. In many cases, you are required to include the updating table and alias it in the FROM clause however I'm not sure about Postgres:

Update addresses
Set cid = c.id
From addresses As a
    Join customers As c
        On c.id = a.id

How to use "like" and "not like" in SQL MSAccess for the same field?

what's the problem with:

field like "*AA*" and field not like "*BB*"

it should be working.

Could you post some example of your data?

How to pass the password to su/sudo/ssh without overriding the TTY?

I had the same problem. dialog script to create directory on remote pc. dialog with ssh is easy. I use sshpass (previously installed).

   dialog --inputbox "Enter IP" 8 78 2> /tmp/ip

   IP=$(cat /tmp/ip)


   dialog --inputbox "Please enter username" 8 78 2> /tmp/user

   US=$(cat /tmp/user)


   dialog --passwordbox "enter password for \"$US\" 8 78 2> /tmp/pass

   PASSWORD = $(cat /tmp/pass)


   sshpass -p "$PASSWORD" ssh $US@$IP mkdir -p /home/$US/TARGET-FOLDER


   rm /tmp/ip

   rm /tmp/user

   rm /tmp/pass

greetings from germany

titus

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I eventually figured out an easy way to do it:

  1. On your Twitter feed, click the date/time of the tweet containing the video. That will open the single tweet view
  2. Look for the down-pointing arrow at the top-right corner of the tweet, click it to open drop-down menue
  3. Select the "Embed Video" option and copy the HTML embed code and Paste it to Notepad
  4. Find the last "t.co" shortened URL inside the HTML code (should be something like this: https://``t.co/tQM43ftXyM). Copy this URL and paste it in a new browser tab.
  5. The browser will expand the shortened URL to something which looks like this: https://twitter.com/UserName/status/828267001496784896/video/1

This is the link to the Twitter Card containing the native video. Pasting this link in a new tweet or DM will include the native video in it!

Using (Ana)conda within PyCharm

Change the project interpreter to ~/anaconda2/python/bin by going to File -> Settings -> Project -> Project Interpreter. Also update the run configuration to use the project default Python interpreter via Run -> Edit Configurations. This makes PyCharm use Anaconda instead of the default Python interpreter under usr/bin/python27.

How to round the minute of a datetime object

Those seem overly complex

def round_down_to():
    num = int(datetime.utcnow().replace(second=0, microsecond=0).minute)
    return num - (num%10)

How to refresh datagrid in WPF

I had a lot of trouble with this and this is what helped me get the DataGrid reloaded with the new values. Make sure you use the data type that your are getting the data from to get the latest data values.

I represented that with SomeDataType below.

DataContext.Refresh(RefreshMode.OverwriteCurrentValues, DataContext.SomeDataType);

Hope this helps someone with the same issues I had.

How do I add an integer value with javascript (jquery) to a value that's returning a string?

parseInt() will force it to be type integer, or will be NaN (not a number) if it cannot perform the conversion.

var currentValue = parseInt($("#replies").text(),10);

The second paramter (radix) makes sure it is parsed as a decimal number.

How to test if a double is an integer

if ((variable == Math.floor(variable)) && !Double.isInfinite(variable)) {
    // integer type
}

This checks if the rounded-down value of the double is the same as the double.

Your variable could have an int or double value and Math.floor(variable) always has an int value, so if your variable is equal to Math.floor(variable) then it must have an int value.

This also doesn't work if the value of the variable is infinite or negative infinite hence adding 'as long as the variable isn't inifinite' to the condition.

How do you convert Html to plain text?

If you have data that has HTML tags and you want to display it so that a person can SEE the tags, use HttpServerUtility::HtmlEncode.

If you have data that has HTML tags in it and you want the user to see the tags rendered, then display the text as is. If the text represents an entire web page, use an IFRAME for it.

If you have data that has HTML tags and you want to strip out the tags and just display the unformatted text, use a regular expression.

Check if table exists and if it doesn't exist, create it in SQL Server 2008

Declare @Username varchar(20)
Set @Username = 'Mike'

if not exists 
(Select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'tblEmp')

Begin
    Create table tblEmp (ID int primary key, Name varchar(50))
    Print (@Username + ' Table created successfully')
End

Else

Begin
    Print (@Username + ' : this Table Already exists in the database')
End

How to use if, else condition in jsf to display image

Instead of using the "c" tags, you could also do the following:

<h:outputLink value="Images/thumb_02.jpg" target="_blank" rendered="#{not empty user or user.userId eq 0}" />
<h:graphicImage value="Images/thumb_02.jpg" rendered="#{not empty user or user.userId eq 0}" />

<h:outputLink value="/DisplayBlobExample?userId=#{user.userId}" target="_blank" rendered="#{not empty user and user.userId neq 0}" />
<h:graphicImage value="/DisplayBlobExample?userId=#{user.userId}" rendered="#{not empty user and user.userId neq 0}"/>

I think that's a little more readable alternative to skuntsel's alternative answer and is utilizing the JSF rendered attribute instead of nesting a ternary operator. And off the answer, did you possibly mean to put your image in between the anchor tags so the image is clickable?

jQuery 'input' event

Be Careful while using INPUT. This event fires on focus and on blur in IE 11. But it is triggered on change in other browsers.

https://connect.microsoft.com/IE/feedback/details/810538/ie-11-fires-input-event-on-focus

How to insert spaces/tabs in text using HTML/CSS

To insert tab space between two words/sentences I usually use

&emsp; and &ensp;

ASP.Net MVC 4 Form with 2 submit buttons/actions

Here is a good eplanation: ASP.NET MVC – Multiple buttons in the same form

In 2 words:
you may analize value of submitted button in yout action
or
make separate actions with your version of ActionMethodSelectorAttribute (which I personaly prefer and suggest).

Threading pool similar to the multiprocessing Pool?

Yes, and it seems to have (more or less) the same API.

import multiprocessing

def worker(lnk):
    ....    
def start_process():
    .....
....

if(PROCESS):
    pool = multiprocessing.Pool(processes=POOL_SIZE, initializer=start_process)
else:
    pool = multiprocessing.pool.ThreadPool(processes=POOL_SIZE, 
                                           initializer=start_process)

pool.map(worker, inputs)
....

How to redirect back to form with input - Laravel 5

In your HTML you have to use value = {{ old('') }}. Without using it, you can't get the value back because what session will store in their cache.

Like for a name validation, this will be-

<input type="text" name="name" value="{{ old('name') }}" />

Now, you can get the value after submitting it if there is error with redirect.

return redirect()->back()->withInput();

As @infomaniac says, you can also use the Input class directly,

return Redirect::back()->withInput(Input::all());

Add: If you only show the specific field, then use $request->only()

return redirect()->back()->withInput($request->only('name'));

Hope, it might work in all case, thanks.

Unable to open debugger port in IntelliJ

I once have this problem too. My solution is to work around this problem by kill the application which is using the port. Here is a article to teach us how to check which application is using which port, find it and kill/close it.

How I can check if an object is null in ruby on rails 2?

it's nilin Ruby, not null. And it's enough to say if @objectname to test whether it's not nil. And no then. You can find more on if syntax here:

http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Control_Structures#if

Pass variables from servlet to jsp

Simple way which i found is,

In servlet:

You can set the value and forward it to JSP like below

req.setAttribute("myname",login);
req.getRequestDispatcher("welcome.jsp").forward(req, resp); 

In Welcome.jsp you can get the values by

.<%String name = (String)request.getAttribute("myname"); %>
<%= name%>

(or) directly u can call

<%= request.getAttribute("myname") %>.

Binding a Button's visibility to a bool value in ViewModel

Since Windows 10 15063 upwards

Since Windows 10 build 15063, there is a new feature called "Implicit Visibility conversion" that binds Visibility to bool value natively - There is no need anymore to use a converter.

(see https://social.technet.microsoft.com/wiki/contents/articles/34846.uwp-compiled-binding-windows-10-anniversary-update.aspx#Implicit_Visibility_conversion).

My code (which supposes that MVVM is used, and Template 10 as well):

<!-- In XAML -->
<StackPanel x:Name="Msg_StackPanel" Visibility="{x:Bind ViewModel.ShowInlineHelp}" Orientation="Horizontal" Margin="0,24,0,0">
    <TextBlock Text="Frosty the snowman was a jolly happy soul" Margin="0,0,8,0"/>
    <SymbolIcon Symbol="OutlineStar "/>
    <TextBlock Text="With a corncob pipe and a button nose" Margin="8,0,0,0"/>
</StackPanel>

<!-- in companion View-Model -->
public bool ShowInlineHelp // using T10 SettingsService
{ 
    get { return (_settings.ShowInlineHelp); }
    set { _settings.ShowInlineHelp = !value; base.RaisePropertyChanged(); }
}

How do I get HTTP Request body content in Laravel?

I don't think you want the data from your Request, I think you want the data from your Response. The two are different. Also you should build your response correctly in your controller.

Looking at the class in edit #2, I would make it look like this:

class XmlController extends Controller
{
    public function index()
    {
        $content = Request::all();
        return Response::json($content);
    }
}

Once you've gotten that far you should check the content of your response in your test case (use print_r if necessary), you should see the data inside.

More information on Laravel responses here:

http://laravel.com/docs/5.0/responses

How to get HTML 5 input type="date" working in Firefox and/or IE 10

The type="date" is not an actual specification at this point. It is a concept Google came up with and is in their whatwg specifications (not official) and is only partially supported by Chrome.

http://caniuse.com/#search=date

I would not rely on this input type at this point. It would be nice to have, but I do not foresee this one actually making it. The #1 reason is it puts too much burden on the browser to determine the best UI for a somewhat complicated input. Think about it from a responsive perspective, how would any of the vendors know what will work best with your UI say at 400 pixels, 800 pixels and 1200 pixels wide?

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'

Now you database connection create according to the this format.

public void Connect() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost/JavaCRUD","root","");
        }catch(ClassNotFoundException ex) {
            
        } catch (SQLException ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        }
    }

Edit this code like this.

    public void Connect() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost/JavaCRUD","root","");
        }catch(ClassNotFoundException ex) {
            
        } catch (SQLException ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        }
    }

Now it will execute.

How to set JAVA_HOME in Mac permanently?

Try this link http://www.mkyong.com/java/how-to-set-java_home-environment-variable-on-mac-os-x/

This explains correctly, I did the following to make it work

  1. Open Terminal
  2. Type vim .bash_profile
  3. Type your java instalation dir in my case export JAVA_HOME="/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home
  4. Click ESC then type :wq (save and quit in vim)
  5. Then type source .bash_profile
  6. echo $JAVA_HOME if you see the path you are all set.

Hope it helps.

java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0 (unable to load class frontend.listener.StartupListener)

What is your output when you do java -version? This will tell you what version the running JVM is.

The Unsupported major.minor version 51.0 error could mean:

  • Your server is running a lower Java version then the one used to compile your Servlet and vice versa

Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)

See: http://www.java.com/en/download/manual.jsp (7 Update 25 )

and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)

for the latest version of the JRE and JDK respectively.

EDIT:

Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.

Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.

How to upgrade Angular CLI project?

USEFUL:

Use the official Angular Update Guide select your current version and the version you wish to upgrade to for the relevant upgrade guide. https://update.angular.io/

See GitHub repository Angular CLI diff for comparing Angular CLI changes. https://github.com/cexbrayat/angular-cli-diff/

UPDATED 26/12/2018:

Use the official Angular Update Guide mentioned in the useful section above. It provides the most up to date information with links to other resources that may be useful during the upgrade.

UPDATED 08/05/2018:

Angular CLI 1.7 introduced ng update.

ng update

A new Angular CLI command to help simplify keeping your projects up to date with the latest versions. Packages can define logic which will be applied to your projects to ensure usage of latest features as well as making changes to reduce or eliminate the impact related to breaking changes.

Configuration information for ng update can be found here

1.7 to 6 update

CLI 1.7 does not support an automatic v6 update. Manually install @angular/cli via your package manager, then run the update migration schematic to finish the process.

npm install @angular/cli@^6.0.0
ng update @angular/cli --migrate-only --from=1

UPDATED 30/04/2017:

1.0 Update

You should now follow the Angular CLI migration guide


UPDATED 04/03/2017:

RC Update

You should follow the Angular CLI RC migration guide


UPDATED 20/02/2017:

Please be aware 1.0.0-beta.32 has breaking changes and has removed ng init and ng update

The pull request here states the following:

BREAKING CHANGE: Removing the ng init & ng update commands because their current implementation causes more problems than it solves. Update functionality will return to the CLI, until then manual updates of applications will need done.

The angular-cli CHANGELOG.md states the following:

BREAKING CHANGES - @angular/cli: Removing the ng init & ng update commands because their current implementation causes more problems than it solves. Once RC is released, we won't need to use those to update anymore as the step will be as simple as installing the latest version of the CLI.


UPDATED 17/02/2017:

Angular-cli has now been added to the NPM @angular package. You should now replace the above command with the following -

Global package:

npm uninstall -g angular-cli @angular/cli
npm cache clean
npm install -g @angular/cli@latest

Local project package:

rm -rf node_modules dist # On Windows use rmdir /s /q node_modules dist
npm install --save-dev @angular/cli@latest
npm install
ng init

ORIGINAL ANSWER

You should follow the steps from the README.md on GitHub for updating angular via the angular-cli.

Here they are:

Updating angular-cli

To update angular-cli to a new version, you must update both the global package and your project's local package.

Global package:

npm uninstall -g angular-cli
npm cache clean
npm install -g angular-cli@latest

Local project package:

rm -rf node_modules dist tmp # On Windows use rmdir /s /q node_modules dist tmp
npm install --save-dev angular-cli@latest
npm install
ng init

Running ng init will check for changes in all the auto-generated files created by ng new and allow you to update yours. You are offered four choices for each changed file: y (overwrite), n (don't overwrite), d (show diff between your file and the updated file) and h (help).

Carefully read the diffs for each code file, and either accept the changes or incorporate them manually after ng init finishes.

MVC Razor Radio Button

MVC Razor provides one elegant Html Helper called RadioButton with two parameters (this is general, But we can overload it uptil five parameters) i.e. one with the group name and other being the value

<div class="col-md-10">
    Male:   @Html.RadioButton("Gender", "Male")
    Female: @Html.RadioButton("Gender", "Female")
</div>                         

How to get a password from a shell script without echoing

A POSIX compliant answer. Notice the use of /bin/sh instead of /bin/bash. (It does work with bash, but it does not require bash.)

#!/bin/sh
stty -echo
printf "Password: "
read PASSWORD
stty echo
printf "\n"

Setting the default ssh key location

If you are only looking to point to a different location for you identity file, the you can modify your ~/.ssh/config file with the following entry:

IdentityFile ~/.foo/identity

man ssh_config to find other config options.

Using multiple IF statements in a batch file

is there a special guideline that should be followed

There is no "standard" way to do batch files, because the vast majority of their authors and maintainers either don't understand programming concepts, or they think they don't apply to batch files.

But I am a programmer. I'm used to compiling, and I'm used to debuggers. Batch files aren't compiled, and you can't run them through a debugger, so they make me nervous. I suggest you be extra strict on what you write, so you can be very sure it will do what you think it does.

There are some coding standards that say: If you write an if statement, you must use braces, even if you don't have an else clause. This saves you from subtle, hard-to-debug problems, and is unambiguously readable. I see no reason you couldn't apply this reasoning to batch files.

Let's take a look at your code.

IF EXIST somefile.txt IF EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt

And the IF syntax, from the command, HELP IF:

IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXISTS filename command

...

IF EXIST filename (
  command
) ELSE (
  other command
)

So you are chaining IF's as commands.

If you use the common coding-standard rule I mentioned above, you would always want to use parens. Here is how you would do so for your example code:

IF EXIST "somefile.txt" (
  IF EXIST "someotherfile.txt" (
    SET var="somefile.txt,someotherfile.txt"
  )
)

Make sure you cleanly format, and do some form of indentation. You do it in code, and you should do it in your batch scripts.

Also, you should also get in the habit of always quoting your file names, and getting the quoting right. There is some verbiage under HELP FOR and HELP SET that will help you with removing extra quotes when re-quoting strings.

Edit

From your comments, and re-reading your original question, it seems like you want to build a comma separated list of files that exist. For this case, you could simply use a bunch of if/else statements, but that would result in a bunch of duplicated logic, and would not be at all clean if you had more than two files.

A better way is to write a sub-routine that checks for a single file's existence, and appends to a variable if the file specified exists. Then just call that subroutine for each file you want to check for:

@ECHO OFF
SETLOCAL

REM Todo: Set global script variables here
CALL :MainScript
GOTO :EOF

REM MainScript()
:MainScript
  SETLOCAL

  CALL :AddIfExists "somefile.txt" "%files%" "files"
  CALL :AddIfExists "someotherfile.txt" "%files%" "files"

  ECHO.Files: %files%

  ENDLOCAL
GOTO :EOF

REM AddIfExists(filename, existingFilenames, returnVariableName)
:AddIfExists
  SETLOCAL

  IF EXIST "%~1" (
    SET "result=%~1"
  ) ELSE (
    SET "result="
  )

  (
    REM Cleanup, and return result - concatenate if necessary
    ENDLOCAL

    IF "%~2"=="" (
      SET "%~3=%result%"
    ) ELSE (
      SET "%~3=%~2,%result%"
    )
  )
GOTO :EOF

jQuery: How to capture the TAB keypress within a Textbox

Working example in jQuery 1.9:

$('body').on('keydown', '#textbox', function(e) {
    if (e.which == 9) {
        e.preventDefault();
        // do your code
    }
});

Python Regex - How to Get Positions and Values of Matches

import re
p = re.compile("[a-z]")
for m in p.finditer('a1b2c3d4'):
    print(m.start(), m.group())

Android Studio update -Error:Could not run build action using Gradle distribution

I had same issue. I have tried many things but nothing worked Until I try following:

  1. Close Android Studio
  2. Delete any directory matching gradle-[version]-all within C:\Users\<username>\.gradle\wrapper\dists\. If you encounter a "File in use" error (or similar), terminate any running Java executables.
  3. Open Android Studio as Administrator.
  4. Try to sync project files.
  5. If the above does not work, try restarting your computer and/or delete the project's .gradle directory.
  6. Open the problem project and trigger a Gradle sync.

Get all column names of a DataTable into string array using (LINQ/Predicate)

Use

var arrayNames = (from DataColumn x in dt.Columns
                  select x.ColumnName).ToArray();

How do I check if an HTML element is empty using jQuery?

JavaScript

var el= document.querySelector('body'); 
console.log(el);
console.log('Empty : '+ isEmptyTag(el));
console.log('Having Children : '+ hasChildren(el));


function isEmptyTag(tag) { 
    return (tag.innerHTML.trim() === '') ? true : false ;
}
function hasChildren(tag) {
    //return (tag.childElementCount !== 0) ? true : false ; // Not For IE
    //return (tag.childNodes.length !== 0) ? true : false ; // Including Comments
    return (tag.children.length !== 0) ? true : false ; // Only Elements
}

try using any of this!

document.getElementsByTagName('div')[0];
document.getElementsByClassName('topbar')[0];

document.querySelectorAll('div')[0];
document.querySelector('div'); // gets the first element.
?

How to create folder with PHP code?

You can create a directory with PHP using the mkdir() function.

mkdir("/path/to/my/dir", 0700);

You can use fopen() to create a file inside that directory with the use of the mode w.

fopen('myfile.txt', 'w');

w : Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

jQuery move to anchor location on page load

Description

You can do this using jQuery's .scrollTop() and .offset() method

Check out my sample and this jsFiddle Demonstration

Sample

$(function() {
    $(document).scrollTop( $("#header").offset().top );  
});

More Information

CSS Box Shadow - Top and Bottom Only

So this is my first answer here, and because I needed something similar I did with pseudo elements for 2 inner shadows, and an extra DIV for an upper outer shadow. Don't know if this is the best solutions but maybe it will help someone.

HTML

<div class="shadow-block">
    <div class="shadow"></div>
    <div class="overlay">
        <div class="overlay-inner">
            content here
        </div>
    </div>
</div>

CSS

.overlay {
    background: #f7f7f4;
    height: 185px;
    overflow: hidden;
    position: relative;
    width: 100%; 
}

.overlay:before {
    border-radius: 50% 50% 50% 50%;
    box-shadow: 0 0 50px 2px rgba(1, 1, 1, 0.6);
    content: " ";
    display: block;
    margin: 0 auto;
    width: 80%;
}

.overlay:after {
    border-radius: 50% 50% 50% 50%;
    box-shadow: 0 0 70px 5px rgba(1, 1, 1, 0.5);
    content: "-";
    display: block;
    margin: 0 auto;
    position: absolute;
    bottom: -65px;
    left: -50%;
    right: -50%;
    width: 80%;
}

.shadow {
    position: relative;
    width:100%;
    height:8px;
    margin: 0 0 -22px 0;
    -webkit-box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
    box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
    border-radius: 50%;
}

How do I measure a time interval in C?

On Linux you can use clock_gettime():

clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); // get initial time-stamp

// ... do stuff ... //

clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end);   // get final time-stamp

double t_ns = (double)(end.tv_sec - start.tv_sec) * 1.0e9 +
              (double)(end.tv_nsec - start.tv_nsec);
                                                 // subtract time-stamps and
                                                 // multiply to get elapsed
                                                 // time in ns

CSS table column autowidth

You could specify the width of all but the last table cells and add a table-layout:fixed and a width to the table.

You could set

table tr ul.actions {margin: 0; white-space:nowrap;}

(or set this for the last TD as Sander suggested instead).

This forces the inline-LIs not to break. Unfortunately this does not lead to a new width calculation in the containing UL (and this parent TD), and therefore does not autosize the last TD.

This means: if an inline element has no given width, a TD's width is always computed automatically first (if not specified). Then its inline content with this calculated width gets rendered and the white-space-property is applied, stretching its content beyond the calculated boundaries.

So I guess it's not possible without having an element within the last TD with a specific width.

Does WGET timeout?

Since in your question you said it's a PHP script, maybe the best solution could be to simply add in your script:

ignore_user_abort(TRUE);

In this way even if wget terminates, the PHP script goes on being processed at least until it does not exceeds max_execution_time limit (ini directive: 30 seconds by default).

As per wget anyay you should not change its timeout, according to the UNIX manual the default wget timeout is 900 seconds (15 minutes), whis is much larger that the 5-6 minutes you need.

Android: Center an image

Simply add this to your ImageView.

android:layout_gravity="center" 

Difference between return 1, return 0, return -1 and exit?

As explained here, in the context of main both return and exit do the same thing

Q: Why do we need to return or exit?

A: To indicate execution status.

In your example even if you didnt have return or exit statements the code would run fine (Assuming everything else is syntactically,etc-ally correct. Also, if (and it should be) main returns int you need that return 0 at the end).

But, after execution you don't have a way to find out if your code worked as expected. You can use the return code of the program (In *nix environments , using $?) which gives you the code (as set by exit or return) . Since you set these codes yourself you understand at which point the code reached before terminating.

You can write return 123 where 123 indicates success in the post execution checks.

Usually, in *nix environments 0 is taken as success and non-zero codes as failures.

Adding a legend to PyPlot in Matplotlib in the simplest manner possible

You can access the Axes instance (ax) with plt.gca(). In this case, you can use

plt.gca().legend()

You can do this either by using the label= keyword in each of your plt.plot() calls or by assigning your labels as a tuple or list within legend, as in this working example:

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-0.75,1,100)
y0 = np.exp(2 + 3*x - 7*x**3)
y1 = 7-4*np.sin(4*x)
plt.plot(x,y0,x,y1)
plt.gca().legend(('y0','y1'))
plt.show()

pltGcaLegend

However, if you need to access the Axes instance more that once, I do recommend saving it to the variable ax with

ax = plt.gca()

and then calling ax instead of plt.gca().

What are all the escape characters?

You can find the full list here.

  • \t Insert a tab in the text at this point.
  • \b Insert a backspace in the text at this point.
  • \n Insert a newline in the text at this point.
  • \r Insert a carriage return in the text at this point.
  • \f Insert a formfeed in the text at this point.
  • \' Insert a single quote character in the text at this point.
  • \" Insert a double quote character in the text at this point.
  • \\ Insert a backslash character in the text at this point.

Use of document.getElementById in JavaScript

Here in your code demo is id where you want to display your result after click event has occur and just nothing.

You can take anything

<p id="demo">

or

<div id="demo"> 

It is just node in a document where you just want to display your result.

Import module from subfolder

Just to notify here. (from a newbee, keviv22)

Never and ever for the sake of your own good, name the folders or files with symbols like "-" or "_". If you did so, you may face few issues. like mine, say, though your command for importing is correct, you wont be able to successfully import the desired files which are available inside such named folders.

Invalid Folder namings as follows:

  • Generic-Classes-Folder
  • Generic_Classes_Folder

valid Folder namings for above:

  • GenericClassesFolder or Genericclassesfolder or genericClassesFolder (or like this without any spaces or special symbols among the words)

What mistake I did:

consider the file structure.

Parent
   . __init__.py
   . Setup
     .. __init__.py
     .. Generic-Class-Folder
        ... __init__.py
        ... targetClass.py
   . Check
     .. __init__.py
     .. testFile.py

What I wanted to do?

  • from testFile.py, I wanted to import the 'targetClass.py' file inside the Generic-Class-Folder file to use the function named "functionExecute" in 'targetClass.py' file

What command I did?

  • from 'testFile.py', wrote command, from Core.Generic-Class-Folder.targetClass import functionExecute
  • Got errors like SyntaxError: invalid syntax

Tried many searches and viewed many stackoverflow questions and unable to decide what went wrong. I cross checked my files multiple times, i used __init__.py file, inserted environment path and hugely worried what went wrong......

And after a long long long time, i figured this out while talking with a friend of mine. I am little stupid to use such naming conventions. I should never use space or special symbols to define a name for any folder or file. So, this is what I wanted to convey. Have a good day!

(sorry for the huge post over this... just letting my frustrations go.... :) Thanks!)

Converting a value to 2 decimal places within jQuery

You need to use the .toFixed() method

It takes as a parameter the number of digits to show after the decimal point.

$(document).ready(function() {
  $('.add').click(function() {
     var value = parseFloat($('#total').text()) + parseFloat($(this).data('amount'))/100
     $('#total').text( value.toFixed(2) );
  });
})

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

The 'best' way to do this would be to set a property on a view object once the update is successful. You can then access this property in the view and inform the user accordingly.

Having said that it would be possible to trigger an alert from the controller code by doing something like this -

public ActionResult ActionName(PostBackData postbackdata)
{
    //your DB code
    return new JavascriptResult { Script = "alert('Successfully registered');" };
}

You can find further info in this question - How to display "Message box" using MVC3 controller

Node.js global proxy setting

Unfortunately, it seems that proxy information must be set on each call to http.request. Node does not include a mechanism for global proxy settings.

The global-tunnel-ng module on NPM appears to handle this, however:

var globalTunnel = require('global-tunnel-ng');

globalTunnel.initialize({
  host: '10.0.0.10',
  port: 8080,
  proxyAuth: 'userId:password', // optional authentication
  sockets: 50 // optional pool size for each http and https
});

After the global settings are establish with a call to initialize, both http.request and the request library will use the proxy information.

The module can also use the http_proxy environment variable:

process.env.http_proxy = 'http://proxy.example.com:3129';
globalTunnel.initialize();

number_format() with MySQL

http://blogs.mysql.com/peterg/2009/04/

In Mysql 6.1 you will be able to do FORMAT(X,D [,locale_name] )

As in

 SELECT format(1234567,2,’de_DE’);

For now this ability does not exist, though you MAY be able to set your locale in your database my.ini check it out.

Clear android application user data

Hello UdayaLakmal,

public class MyApplication extends Application {
    private static MyApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static MyApplication getInstance(){
        return instance;
    }

    public void clearApplicationData() {
        File cache = getCacheDir();
        File appDir = new File(cache.getParent());
        if(appDir.exists()){
            String[] children = appDir.list();
            for(String s : children){
                if(!s.equals("lib")){
                    deleteDir(new File(appDir, s));
                    Log.i("TAG", "File /data/data/APP_PACKAGE/" + s +" DELETED");
                }
            }
        }
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        return dir.delete();
    }
}

Please check this and let me know...

You can download code from here